1
1
local M = {}
2
2
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.
4
4
--- @param t table
5
- --- @param path string
5
+ --- @param keypath string
6
6
--- @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
11
11
end
12
+
13
+ t = t [segment ]
12
14
end
15
+
13
16
return t
14
17
end
15
18
16
- --- Parse string for configuration template
19
+ --- Parses and resolves keypath string for configuration template.
17
20
--- @param str string
18
21
--- @param spec Spec
19
22
--- @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
22
25
return str
23
26
end
24
27
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
31
30
end
32
31
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
33
36
function M .parse (template , spec )
34
37
local result = {}
35
38
36
39
for group , opts in pairs (template ) do
37
40
if type (opts ) == ' table' then
38
41
local new = {}
42
+
39
43
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 )
45
45
end
46
+
46
47
result [group ] = new
47
48
else
48
- result [group ] = parse_string (opts , spec )
49
+ result [group ] = parse_keypath (opts , spec )
49
50
end
50
51
end
51
52
@@ -56,7 +57,7 @@ function M.parse_template_str(template, spec)
56
57
return (
57
58
template :gsub (' ($%b{})' , function (w )
58
59
local path = w :sub (3 , - 2 )
59
- local value = get_path (spec , path ) or w
60
+ local value = get_keypath (spec , path ) or w
60
61
if type (value ) == ' table' then
61
62
return value .base and value .base or value
62
63
else
0 commit comments