-
Notifications
You must be signed in to change notification settings - Fork 18
/
expander.go
39 lines (32 loc) · 1 KB
/
expander.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package expander
import (
"fmt"
"sort"
"strings"
)
func ExpandEnvironmentVariables(s string, env map[string]string) string {
const maxExpansionIterations = 10
// Create a sorted view of the environment map keys to expand the longest keys first
// and avoid cases where "$CIRRUS_BRANCH" is expanded into "true_BRANCH", assuming
// env = map[string]string{"CIRRUS": "true", "CIRRUS_BRANCH": "main"})
var sortedKeys []string
for key := range env {
sortedKeys = append(sortedKeys, key)
}
sort.Slice(sortedKeys, func(i, j int) bool {
return !(sortedKeys[i] < sortedKeys[j])
})
for i := 0; i < maxExpansionIterations; i++ {
beforeExpansion := s
for _, key := range sortedKeys {
s = strings.ReplaceAll(s, fmt.Sprintf("$%s", key), env[key])
s = strings.ReplaceAll(s, fmt.Sprintf("${%s}", key), env[key])
s = strings.ReplaceAll(s, fmt.Sprintf("%%%s%%", key), env[key])
}
// Don't wait till the end of the loop if we are not progressing
if s == beforeExpansion {
break
}
}
return s
}