Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions subst.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,22 @@ var reGroup = regexp.MustCompile(`\\([0-9]+)`)
// - ${variable/re/subst/} expands to the variable, with a regexp replacement.
// for instance, ${variable/^([^:]*):/\1/}, where variable=foo:bar, expands
// to foo.
//
// If the passed VariableMap implements CanSubstitute(key string) bool, then
// the method is called to determine whether the variable is to be substituted.
// If the method returns false, the variable is left untouched and is output
// as-is into the result.
func Substitute(s string, vars VariableMap) (string, error) {

type CanSubstitute interface {
CanSubstitute(key string) bool
}

cansubst := func(key string) bool { return true }
if cs, ok := vars.(CanSubstitute); ok {
cansubst = cs.CanSubstitute
}

var out strings.Builder
start := 0
outer:
Expand Down Expand Up @@ -104,6 +119,11 @@ outer:
break outer
}

if !cansubst(name) {
i += delim + 1
continue
}

out.WriteString(s[start:subsStart])
value, present := vars.Get(name)

Expand Down
47 changes: 47 additions & 0 deletions subst_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,27 @@
package shutil

import (
"strings"
"testing"
)

type PrefixedVarMap struct {
Prefix string
Values map[string]string
}

func (m *PrefixedVarMap) Get(key string) (value string, present bool) {
if !strings.HasPrefix(key, m.Prefix) {
return "", false
}
value, present = m.Values[key[len(m.Prefix):]]
return
}

func (m *PrefixedVarMap) CanSubstitute(key string) bool {
return strings.HasPrefix(key, m.Prefix)
}

func TestSubstitute(t *testing.T) {

t.Run("Simple", func(t *testing.T) {
Expand Down Expand Up @@ -69,4 +87,33 @@ func TestSubstitute(t *testing.T) {
}
})

t.Run("Partial", func(t *testing.T) {

tcases := []struct {
In, Expected string
Error bool
}{
{`${substitute.variable}`, "value", false},
{`${substitute.undefined}`, "", true},
{`${nosubstitute.variable}`, `${nosubstitute.variable}`, false},
}

vals := &PrefixedVarMap{
Prefix: "substitute.",
Values: map[string]string{"variable": "value"},
}

for _, tc := range tcases {
t.Run(tc.In, func(t *testing.T) {
actual, err := Substitute(tc.In, vals)
if tc.Error != (err != nil) {
t.Fatalf("unexpected error or success: %v", err)
}
if actual != tc.Expected {
t.Fatalf("expected %q, got %q", tc.Expected, actual)
}
})
}
})

}
Loading