|
0
|
1 // Package icf implements the Inherited Configuration Format parser.
|
|
|
2 //
|
|
|
3 // ICF is a rule-based configuration format with variables, abstract blocks
|
|
|
4 // (mixins), pattern matching with named capture groups, and brace expansion.
|
|
|
5 package icf
|
|
|
6
|
|
|
7 import (
|
|
|
8 "bufio"
|
|
|
9 "fmt"
|
|
|
10 "io"
|
|
|
11 "strings"
|
|
|
12 )
|
|
|
13
|
|
|
14 type Directive struct {
|
|
|
15 Key string
|
|
|
16 Args []string
|
|
|
17 }
|
|
|
18
|
|
|
19 type Config struct {
|
|
|
20 vars map[string]string
|
|
|
21 abstract map[string][]Directive
|
|
|
22 Blocks []ParsedBlock
|
|
|
23 }
|
|
|
24
|
|
|
25 type ParsedBlock struct {
|
|
|
26 ID string
|
|
|
27 Mixin string
|
|
|
28 Directives []Directive
|
|
|
29 }
|
|
|
30
|
|
2
|
31 type rawBlock struct {
|
|
|
32 id string
|
|
|
33 mixin string
|
|
|
34 directives []rawDirective
|
|
|
35 }
|
|
|
36
|
|
|
37 type rawDirective struct {
|
|
|
38 key string
|
|
|
39 args []string // after brace expansion, before var substitution
|
|
|
40 }
|
|
|
41
|
|
0
|
42 func Parse(r io.Reader) (*Config, error) {
|
|
2
|
43 lines, err := readLines(r)
|
|
|
44 if err != nil {
|
|
|
45 return nil, err
|
|
0
|
46 }
|
|
|
47
|
|
2
|
48 // --- Pass 1: collect variables ---
|
|
|
49 vars := make(map[string]string)
|
|
4
|
50 subst := makeSubst(vars)
|
|
|
51
|
|
2
|
52 for _, line := range lines {
|
|
|
53 if i := strings.Index(line, "="); i > 0 && !strings.HasPrefix(line, "|>") {
|
|
|
54 key := line[:i]
|
|
|
55 if isVarName(key) {
|
|
4
|
56 vars[key] = subst(strings.TrimSpace(line[i+1:]), nil)
|
|
2
|
57 }
|
|
|
58 }
|
|
|
59 }
|
|
|
60
|
|
|
61 // --- Pass 2: parse blocks (raw, no capture substitution yet) ---
|
|
|
62 var raws []rawBlock
|
|
|
63 var cur *rawBlock
|
|
0
|
64
|
|
|
65 flush := func() {
|
|
|
66 if cur != nil {
|
|
2
|
67 raws = append(raws, *cur)
|
|
0
|
68 cur = nil
|
|
|
69 }
|
|
|
70 }
|
|
|
71
|
|
2
|
72 for _, line := range lines {
|
|
0
|
73 if i := strings.Index(line, "="); i > 0 && !strings.HasPrefix(line, "|>") {
|
|
2
|
74 if isVarName(line[:i]) {
|
|
0
|
75 continue
|
|
|
76 }
|
|
|
77 }
|
|
|
78
|
|
|
79 if strings.HasPrefix(line, "|>") {
|
|
|
80 if cur == nil {
|
|
|
81 return nil, fmt.Errorf("icf: directive outside block: %q", line)
|
|
|
82 }
|
|
|
83 parts := strings.Fields(strings.TrimSpace(line[2:]))
|
|
|
84 if len(parts) == 0 {
|
|
|
85 continue
|
|
|
86 }
|
|
2
|
87 cur.directives = append(cur.directives, rawDirective{
|
|
|
88 key: parts[0],
|
|
|
89 args: braceExpand(parts[1:]),
|
|
0
|
90 })
|
|
|
91 continue
|
|
|
92 }
|
|
|
93
|
|
|
94 flush()
|
|
|
95 parts := strings.Fields(line)
|
|
2
|
96 rb := rawBlock{id: subst(parts[0], nil)}
|
|
0
|
97 if len(parts) >= 2 && strings.HasPrefix(parts[1], "@") {
|
|
2
|
98 rb.mixin = subst(parts[1][1:], nil)
|
|
0
|
99 }
|
|
2
|
100 cur = &rb
|
|
0
|
101 }
|
|
|
102 flush()
|
|
|
103
|
|
2
|
104 // --- Pass 3: separate abstract from concrete, apply var substitution ---
|
|
|
105 c := &Config{
|
|
|
106 vars: vars,
|
|
|
107 abstract: make(map[string][]Directive),
|
|
0
|
108 }
|
|
|
109
|
|
2
|
110 for _, rb := range raws {
|
|
|
111 dirs := make([]Directive, len(rb.directives))
|
|
|
112 for i, rd := range rb.directives {
|
|
|
113 args := make([]string, len(rd.args))
|
|
|
114 for j, a := range rd.args {
|
|
|
115 args[j] = subst(a, nil)
|
|
|
116 }
|
|
|
117 dirs[i] = Directive{Key: rd.key, Args: args}
|
|
|
118 }
|
|
|
119
|
|
|
120 if strings.HasPrefix(rb.id, "@") {
|
|
|
121 c.abstract[rb.id[1:]] = dirs
|
|
0
|
122 } else {
|
|
2
|
123 c.Blocks = append(c.Blocks, ParsedBlock{
|
|
|
124 ID: rb.id,
|
|
|
125 Mixin: rb.mixin,
|
|
|
126 Directives: dirs,
|
|
|
127 })
|
|
0
|
128 }
|
|
|
129 }
|
|
|
130
|
|
|
131 return c, nil
|
|
|
132 }
|
|
|
133
|
|
2
|
134 // Abstract returns the directives of a named abstract block.
|
|
|
135 // Returns nil if not found.
|
|
0
|
136 func (c *Config) Abstract(name string) []Directive {
|
|
2
|
137 return c.abstract[name]
|
|
0
|
138 }
|
|
|
139
|
|
|
140 // Match finds the most specific block matching input (e.g. "host/path") and
|
|
|
141 // returns resolved directives plus named captures.
|
|
2
|
142 // Domain is matched exactly; path uses prefix match.
|
|
0
|
143 func (c *Config) Match(input string) ([]Directive, map[string]string) {
|
|
|
144 inHost, inPath, _ := strings.Cut(input, "/")
|
|
|
145
|
|
|
146 type hit struct {
|
|
|
147 block ParsedBlock
|
|
|
148 captures map[string]string
|
|
|
149 score int
|
|
|
150 }
|
|
|
151 var best *hit
|
|
|
152
|
|
|
153 for _, b := range c.Blocks {
|
|
|
154 patHost, patPath, hasPath := strings.Cut(b.ID, "/")
|
|
|
155 caps := make(map[string]string)
|
|
|
156
|
|
|
157 domScore, ok := matchExact(patHost, inHost, caps)
|
|
|
158 if !ok {
|
|
|
159 continue
|
|
|
160 }
|
|
|
161
|
|
|
162 pathScore := 0
|
|
|
163 if hasPath {
|
|
|
164 pathScore, ok = matchPrefix(patPath, inPath, caps)
|
|
|
165 if !ok {
|
|
|
166 continue
|
|
|
167 }
|
|
|
168 }
|
|
|
169
|
|
|
170 score := domScore*1000 + pathScore
|
|
|
171 if best == nil || score > best.score {
|
|
|
172 best = &hit{block: b, captures: caps, score: score}
|
|
|
173 }
|
|
|
174 }
|
|
|
175
|
|
|
176 if best == nil {
|
|
|
177 return nil, nil
|
|
|
178 }
|
|
|
179
|
|
|
180 return c.ResolveBlock(best.block, best.captures), best.captures
|
|
|
181 }
|
|
|
182
|
|
2
|
183 // ResolveBlock merges mixin directives (lower priority) with block directives,
|
|
|
184 // then substitutes capture variables.
|
|
0
|
185 func (c *Config) ResolveBlock(b ParsedBlock, caps map[string]string) []Directive {
|
|
|
186 var merged []Directive
|
|
|
187 if b.Mixin != "" {
|
|
|
188 merged = append(merged, c.abstract[b.Mixin]...)
|
|
|
189 }
|
|
|
190 merged = append(merged, b.Directives...)
|
|
2
|
191
|
|
|
192 if len(caps) == 0 {
|
|
|
193 return merged
|
|
|
194 }
|
|
0
|
195
|
|
2
|
196 // Substitute capture variables into a copy
|
|
|
197 subst := makeSubst(c.vars)
|
|
|
198 out := make([]Directive, len(merged))
|
|
|
199 for i, d := range merged {
|
|
|
200 out[i].Key = d.Key
|
|
0
|
201 out[i].Args = make([]string, len(d.Args))
|
|
|
202 for j, a := range d.Args {
|
|
2
|
203 out[i].Args[j] = subst(a, caps)
|
|
0
|
204 }
|
|
|
205 }
|
|
|
206 return out
|
|
|
207 }
|
|
|
208
|
|
2
|
209 // makeSubst returns a function that substitutes $VAR in s,
|
|
|
210 // checking caps first, then vars.
|
|
|
211 func makeSubst(vars map[string]string) func(s string, caps map[string]string) string {
|
|
|
212 return func(s string, caps map[string]string) string {
|
|
|
213 if !strings.Contains(s, "$") {
|
|
|
214 return s
|
|
0
|
215 }
|
|
2
|
216 var b strings.Builder
|
|
|
217 i := 0
|
|
|
218 for i < len(s) {
|
|
|
219 if s[i] != '$' {
|
|
|
220 b.WriteByte(s[i])
|
|
|
221 i++
|
|
|
222 continue
|
|
|
223 }
|
|
|
224 j := i + 1
|
|
|
225 for j < len(s) && isVarChar(s[j]) {
|
|
|
226 j++
|
|
|
227 }
|
|
|
228 name := s[i+1 : j]
|
|
|
229 if caps != nil {
|
|
|
230 if v, ok := caps[name]; ok {
|
|
|
231 b.WriteString(v)
|
|
|
232 i = j
|
|
|
233 continue
|
|
|
234 }
|
|
|
235 }
|
|
|
236 if v, ok := vars[name]; ok {
|
|
|
237 b.WriteString(v)
|
|
|
238 } else {
|
|
|
239 b.WriteString(s[i:j])
|
|
|
240 }
|
|
|
241 i = j
|
|
0
|
242 }
|
|
2
|
243 return b.String()
|
|
|
244 }
|
|
|
245 }
|
|
|
246
|
|
|
247 func readLines(r io.Reader) ([]string, error) {
|
|
|
248 var out []string
|
|
|
249 scanner := bufio.NewScanner(r)
|
|
|
250 for scanner.Scan() {
|
|
|
251 line := stripComment(strings.TrimSpace(scanner.Text()))
|
|
|
252 if line != "" {
|
|
|
253 out = append(out, line)
|
|
0
|
254 }
|
|
|
255 }
|
|
2
|
256 return out, scanner.Err()
|
|
0
|
257 }
|
|
|
258
|
|
|
259 func matchExact(pat, s string, caps map[string]string) (int, bool) {
|
|
|
260 score, rem, ok := matchCaptures(pat, s, caps)
|
|
|
261 if !ok || rem != "" {
|
|
|
262 return 0, false
|
|
|
263 }
|
|
|
264 return score, true
|
|
|
265 }
|
|
|
266
|
|
|
267 func matchPrefix(pat, s string, caps map[string]string) (int, bool) {
|
|
|
268 score, _, ok := matchCaptures(pat, s, caps)
|
|
|
269 return score, ok
|
|
|
270 }
|
|
|
271
|
|
|
272 func matchCaptures(pat, inp string, caps map[string]string) (int, string, bool) {
|
|
|
273 for {
|
|
|
274 if pat == "" {
|
|
|
275 return 0, inp, true
|
|
|
276 }
|
|
|
277
|
|
|
278 if strings.HasPrefix(pat, "<") {
|
|
|
279 end := strings.Index(pat, ">")
|
|
|
280 if end == -1 {
|
|
|
281 return 0, "", false
|
|
|
282 }
|
|
|
283 capName := pat[1:end]
|
|
|
284 rest := pat[end+1:]
|
|
|
285
|
|
|
286 for split := 1; split <= len(inp); split++ {
|
|
2
|
287 score, finalRem, ok := matchCaptures(rest, inp[split:], caps)
|
|
0
|
288 if ok {
|
|
|
289 if capName != "_" {
|
|
2
|
290 caps[capName] = inp[:split]
|
|
0
|
291 }
|
|
|
292 return score, finalRem, true
|
|
|
293 }
|
|
|
294 }
|
|
|
295 return 0, "", false
|
|
|
296 }
|
|
|
297
|
|
|
298 if inp == "" || pat[0] != inp[0] {
|
|
|
299 return 0, "", false
|
|
|
300 }
|
|
|
301 score, rem, ok := matchCaptures(pat[1:], inp[1:], caps)
|
|
|
302 return score + 1, rem, ok
|
|
|
303 }
|
|
|
304 }
|
|
|
305
|
|
|
306 func braceExpand(args []string) []string {
|
|
|
307 var out []string
|
|
|
308 for _, a := range args {
|
|
|
309 out = append(out, expandOne(a)...)
|
|
|
310 }
|
|
|
311 return out
|
|
|
312 }
|
|
|
313
|
|
|
314 func expandOne(s string) []string {
|
|
|
315 start := strings.Index(s, "{")
|
|
|
316 end := strings.Index(s, "}")
|
|
|
317 if start == -1 || end == -1 || end < start {
|
|
|
318 return []string{s}
|
|
|
319 }
|
|
|
320 prefix := s[:start]
|
|
|
321 suffix := s[end+1:]
|
|
|
322 var out []string
|
|
|
323 for _, v := range strings.Split(s[start+1:end], ",") {
|
|
|
324 out = append(out, prefix+strings.TrimSpace(v)+suffix)
|
|
|
325 }
|
|
|
326 return out
|
|
|
327 }
|
|
|
328
|
|
|
329 func stripComment(line string) string {
|
|
|
330 if strings.HasPrefix(line, ";") {
|
|
|
331 return ""
|
|
|
332 }
|
|
|
333 if i := strings.Index(line, " ;"); i != -1 {
|
|
|
334 return strings.TrimSpace(line[:i])
|
|
|
335 }
|
|
|
336 return line
|
|
|
337 }
|
|
|
338
|
|
|
339 func isVarName(s string) bool {
|
|
|
340 if s == "" {
|
|
|
341 return false
|
|
|
342 }
|
|
|
343 for i := 0; i < len(s); i++ {
|
|
|
344 if !isVarChar(s[i]) {
|
|
|
345 return false
|
|
|
346 }
|
|
|
347 }
|
|
|
348 return true
|
|
|
349 }
|
|
|
350
|
|
|
351 func isVarChar(c byte) bool {
|
|
|
352 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
|
|
|
353 (c >= '0' && c <= '9') || c == '_'
|
|
2
|
354 } |