-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: work-around incomplete variable interpolation
- Loading branch information
Showing
4 changed files
with
52 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package common | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
"regexp" | ||
"strings" | ||
|
||
"go.spiff.io/expand" | ||
) | ||
|
||
func CustomExpandVariables(input string, fn func(key string) (value string, ok bool)) string { | ||
input = ConvertSimpleVarsToBraces(input) | ||
input = strings.TrimSpace(input) | ||
input = strings.Trim(input, fmt.Sprintf("%v\"'", os.PathListSeparator)) | ||
return expand.Expand(input, fn) | ||
} | ||
|
||
func ConvertSimpleVarsToBraces(input string) string { | ||
r := regexp.MustCompile(`\$([0-9a-zA-Z_]+)`) | ||
return r.ReplaceAllStringFunc(input, func(m string) string { | ||
parts := r.FindStringSubmatch(m) | ||
return fmt.Sprintf(`${%s}`, parts[1]) | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
package common | ||
|
||
import ( | ||
"os" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func Test_expanding_with_custom_callback(t *testing.T) { | ||
input := "${VAR1}/$VAR2/bin" | ||
|
||
res := CustomExpandVariables(input, func(key string) (string, bool) { | ||
switch key { | ||
case "VAR1": | ||
return "/var1", true | ||
case "VAR2": | ||
return "var2", true | ||
default: | ||
return os.LookupEnv(key) | ||
} | ||
}) | ||
assert.Equal(t, "/var1/var2/bin", res) | ||
} |