feat(jobs): expand environment variables in paths
This commit is contained in:
@@ -19,6 +19,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -850,6 +851,29 @@ func SafeJoin(root, rel string) (string, error) {
|
||||
return joined, nil
|
||||
}
|
||||
|
||||
var envReferencePattern = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)\}`)
|
||||
|
||||
// ExpandEnv expands ${NAME} references using the current process environment.
|
||||
// It deliberately supports only shell-independent variable references; job
|
||||
// files are never passed through a shell. An unset variable is an error so a
|
||||
// typo cannot silently turn into a relative path.
|
||||
func ExpandEnv(value string) (string, error) {
|
||||
var missing string
|
||||
expanded := envReferencePattern.ReplaceAllStringFunc(value, func(reference string) string {
|
||||
name := reference[2 : len(reference)-1]
|
||||
resolved, ok := os.LookupEnv(name)
|
||||
if !ok {
|
||||
missing = name
|
||||
return reference
|
||||
}
|
||||
return resolved
|
||||
})
|
||||
if missing != "" {
|
||||
return "", fmt.Errorf("environment variable %q referenced by ${%s} is not set", missing, missing)
|
||||
}
|
||||
return expanded, nil
|
||||
}
|
||||
|
||||
// deepestExistingAncestor returns p itself if it exists, otherwise the nearest
|
||||
// existing parent directory (falling back to the filesystem root).
|
||||
func deepestExistingAncestor(p string) string {
|
||||
|
||||
@@ -135,6 +135,21 @@ func TestParseHumanSize(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandEnv(t *testing.T) {
|
||||
t.Setenv("RELSPEC_TEST_ROOT", "build/output")
|
||||
got, err := ExpandEnv("${RELSPEC_TEST_ROOT}/schema-${RELSPEC_TEST_ROOT}")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := "build/output/schema-build/output"; got != want {
|
||||
t.Fatalf("ExpandEnv = %q, want %q", got, want)
|
||||
}
|
||||
|
||||
if _, err := ExpandEnv("build/${RELSPEC_TEST_MISSING}"); err == nil {
|
||||
t.Fatal("expected missing environment variable error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadRejectsDuplicateJobAcrossFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a := filepath.Join(dir, "relspec.yml")
|
||||
|
||||
Reference in New Issue
Block a user