allow variable reference in same env file

This commit is contained in:
Timon Ringwald 2022-08-17 00:15:44 +02:00
parent da57f36193
commit 766def5a01

16
main.go
View File

@ -27,20 +27,18 @@ func main() {
} }
defer envFile.Close() defer envFile.Close()
envVars := parseEnvFile(envFile) parseEnvFile(envFile)
args := flag.Args() args := flag.Args()
newEnv := append(os.Environ(), envVars...)
if len(args) == 0 { if len(args) == 0 {
for _, envVar := range newEnv { for _, envVar := range os.Environ() {
fmt.Println(envVar) fmt.Println(envVar)
} }
return return
} }
cmd := exec.Command(args[0], args[1:]...) cmd := exec.Command(args[0], args[1:]...)
cmd.Env = newEnv cmd.Env = os.Environ()
cmd.Stdin = os.Stdin cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
@ -56,21 +54,19 @@ func main() {
} }
} }
func parseEnvFile(r io.Reader) []string { func parseEnvFile(r io.Reader) {
env := make([]string, 0)
s := bufio.NewScanner(r) s := bufio.NewScanner(r)
l := 0 l := 0
for s.Scan() { for s.Scan() {
l++ l++
matches := EnvVarRegex.FindStringSubmatch(s.Text()) matches := EnvVarRegex.FindStringSubmatch(s.Text())
if len(matches) != 0 { if len(matches) != 0 {
key, value := matches[1], os.ExpandEnv(matches[2]) key, value := matches[1], os.ExpandEnv(matches[2])
env = append(env, fmt.Sprintf("%s=%s", key, value)) os.Setenv(key, value)
} else if s.Text() != "" && !EnvCommentRegex.MatchString(s.Text()) { } else if s.Text() != "" && !EnvCommentRegex.MatchString(s.Text()) {
panic(fmt.Sprintf("invalid env syntax on line %d", l)) panic(fmt.Sprintf("invalid env syntax on line %d", l))
} }
} }
return env
} }