Skip to content
This repository has been archived by the owner on May 8, 2024. It is now read-only.

Commit

Permalink
Detect recursive definitions of environment variables (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
fkorotkov committed Aug 20, 2020
1 parent d7c8918 commit f0ab017
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
19 changes: 14 additions & 5 deletions internal/executor/env.go
Expand Up @@ -6,22 +6,22 @@ import (
"strings"
)

func ExpandText(text string, custom_env map[string]string) string {
func ExpandText(text string, customEnv map[string]string) string {
return expandTextExtended(text, func(name string) (string, bool) {
if userValue, ok := custom_env[name]; ok {
if userValue, ok := customEnv[name]; ok {
return userValue, true
}

return os.LookupEnv(name)
})
}

func ExpandTextOSFirst(text string, custom_env map[string]string) string {
func ExpandTextOSFirst(text string, customEnv map[string]string) string {
return expandTextExtended(text, func(name string) (string, bool) {
if osValue, ok := os.LookupEnv(name); ok {
return osValue, true
}
userValue, ok := custom_env[name]
userValue, ok := customEnv[name]
return userValue, ok
})
}
Expand All @@ -48,13 +48,22 @@ func expandTextExtended(text string, lookup func(string) (string, bool)) string
func expandEnvironmentRecursively(environment map[string]string) map[string]string {
result := make(map[string]string)
for key, value := range environment {
result[key] = ExpandTextOSFirst(value, environment)
result[key] = value
}
for step := 0; step < 10; step++ {
var changed = false
for key, value := range result {
originalValue := result[key]
expandedValue := ExpandTextOSFirst(value, result)

selfRecursion := strings.Contains(expandedValue, "$"+key) ||
strings.Contains(expandedValue, "${"+key) ||
strings.Contains(expandedValue, "%"+key)
if selfRecursion {
// detected self-recursion
continue
}

result[key] = expandedValue

if originalValue != expandedValue {
Expand Down
9 changes: 9 additions & 0 deletions internal/executor/env_test.go
Expand Up @@ -57,3 +57,12 @@ func Test_Environment(t *testing.T) {
t.Errorf("Wrong output: '%s'", result)
}
}

func Test_Recursive(t *testing.T) {
result := expandEnvironmentRecursively(map[string]string{"FOO": "Contains $FOO"})
if result["FOO"] == "Contains $FOO" {
t.Log("Passed")
} else {
t.Errorf("Wrong output: '%s'", result)
}
}

0 comments on commit f0ab017

Please sign in to comment.