Skip to content

Commit 5461bd7

Browse files
committed
Added expand function
1 parent 4963de9 commit 5461bd7

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

pkg/provider/expand.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package provider
2+
3+
import "regexp"
4+
5+
var (
6+
reEval = regexp.MustCompile(`\$\{([^\}]+)\}|\$([a-zA-Z0-9_\.]+)`)
7+
)
8+
9+
// Expand replaces ${var} or $var in the string based on the mapping function.
10+
// For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv).
11+
func Expand(s string, mapping func(string) string) string {
12+
return reEval.ReplaceAllStringFunc(s, func(s string) string {
13+
if s[1] == '{' {
14+
return mapping(s[2 : len(s)-1])
15+
} else {
16+
return mapping(s[1:])
17+
}
18+
})
19+
}

pkg/provider/parser.go

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ func NewParser(plugins ...server.Plugin) (*Parser, error) {
4646
////////////////////////////////////////////////////////////////////////////////
4747
// PUBLIC METHODS
4848

49-
// Append an ast.Tree node
49+
// Append configurations from a JSON file
5050
func (p *Parser) ParseJSON(r io.Reader) error {
5151
var result error
5252

@@ -90,9 +90,23 @@ func (p *Parser) ParseJSON(r io.Reader) error {
9090
func (p *Parser) Bind() error {
9191
var result error
9292

93-
// Set the evaluation function
93+
// Evaluate each set instruction, creating a dependency graph
9494
ctx := ast.NewContext(func(ctx *ast.Context, value any) (any, error) {
95-
fmt.Printf("EVAL %s.%s => %q (%T)\n", ctx.Label(), ctx.Path(), value, value)
95+
switch value := value.(type) {
96+
case string:
97+
var expanded bool
98+
value = Expand(value, func(key string) string {
99+
expanded = true
100+
return "(ref:" + key + ")"
101+
})
102+
if expanded {
103+
fmt.Printf("EVAL %s.%s => %q (%T)\n", ctx.Label(), ctx.Path(), value, value)
104+
} else {
105+
fmt.Printf("SET %s.%s => %q (%T)\n", ctx.Label(), ctx.Path(), value, value)
106+
}
107+
default:
108+
fmt.Printf("SET %s.%s => %q (%T)\n", ctx.Label(), ctx.Path(), value, value)
109+
}
96110
return nil, nil
97111
})
98112

0 commit comments

Comments
 (0)