Skip to content

Commit fc833cb

Browse files
committed
fix(template): don't use str[1] to get 1st char
In Lua, `str[1]` on a string always returns `nil`. Use `str:find('^#')` instead of `str[1] == '#'` to check the first byte/char instead.
1 parent da7281e commit fc833cb

File tree

1 file changed

+23
-22
lines changed

1 file changed

+23
-22
lines changed

lua/github-theme/util/template.lua

+23-22
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,52 @@
11
local M = {}
22

3-
---Walk path (one.two.three) in a table and return value
3+
---Walks/resolves keypath (one.two.three) against a table and returns the value.
44
---@param t table
5-
---@param path string
5+
---@param keypath string
66
---@return any
7-
local function get_path(t, path)
8-
for segment in path:gmatch('[^.]+') do
9-
if type(t) == 'table' then
10-
t = t[segment]
7+
local function get_keypath(t, keypath)
8+
for segment in keypath:gmatch('[^.]+') do
9+
if type(t) ~= 'table' then
10+
return t
1111
end
12+
13+
t = t[segment]
1214
end
15+
1316
return t
1417
end
1518

16-
---Parse string for configuration template
19+
---Parses and resolves keypath string for configuration template.
1720
---@param str string
1821
---@param spec Spec
1922
---@return any
20-
local function parse_string(str, spec)
21-
if str == '' then
23+
local function parse_keypath(str, spec)
24+
if type(str) ~= 'string' or str == '' or str:find('^#') then
2225
return str
2326
end
2427

25-
if str[1] == '#' then
26-
return str
27-
end
28-
29-
local path = get_path(spec, str)
30-
return path and path.base and path.base or path or str
28+
local path = get_keypath(spec, str)
29+
return path and (path.base or path) or str
3130
end
3231

32+
---Resolves any and all placeholders in a template.
33+
---@param template table a table holding placeholders
34+
---@param spec table a table to resolve placeholders against
35+
---@return table
3336
function M.parse(template, spec)
3437
local result = {}
3538

3639
for group, opts in pairs(template) do
3740
if type(opts) == 'table' then
3841
local new = {}
42+
3943
for key, value in pairs(opts) do
40-
if type(value) == 'string' then
41-
new[key] = parse_string(value, spec)
42-
elseif type(value) == 'number' then
43-
new[key] = value
44-
end
44+
new[key] = parse_keypath(value, spec)
4545
end
46+
4647
result[group] = new
4748
else
48-
result[group] = parse_string(opts, spec)
49+
result[group] = parse_keypath(opts, spec)
4950
end
5051
end
5152

@@ -56,7 +57,7 @@ function M.parse_template_str(template, spec)
5657
return (
5758
template:gsub('($%b{})', function(w)
5859
local path = w:sub(3, -2)
59-
local value = get_path(spec, path) or w
60+
local value = get_keypath(spec, path) or w
6061
if type(value) == 'table' then
6162
return value.base and value.base or value
6263
else

0 commit comments

Comments
 (0)