Created
June 12, 2014 08:30
-
-
Save pranavraja/60ed95dbe5c80703de4e to your computer and use it in GitHub Desktop.
Environment variable helper
This file contains hidden or 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
// Build this using `go build` and put it in your PATH | |
package main | |
import ( | |
"encoding/json" | |
"os" | |
"os/exec" | |
"strings" | |
) | |
func main() { | |
f, err := os.Open(os.Getenv("HOME") + "/.erc") | |
if err != nil { | |
println(`Couldn't open ~/.erc, please create that file. | |
Example format: | |
{ "/Users/me/Projects/aws/": ["AWS_ACCESS_KEY_ID=asd","AWS_SECRET_ACCESS_KEY=sdf"] } | |
`) | |
return | |
} | |
defer f.Close() | |
vars := map[string][]string{} | |
err = json.NewDecoder(f).Decode(&vars) | |
if err != nil { | |
println(`~/.erc was in an invalid format: ` + err.Error() + `. | |
Example format: | |
{ "/Users/me/Projects/aws/": ["AWS_ACCESS_KEY_ID=asd","AWS_SECRET_ACCESS_KEY=sdf"] } | |
`) | |
return | |
} | |
wd, _ := os.Getwd() | |
env := os.Environ() | |
for pathPrefix, envs := range vars { | |
if strings.HasPrefix(wd, pathPrefix) { | |
env = append(env, envs...) | |
} | |
} | |
cmd := exec.Command("sh", "-c", strings.Join(os.Args[1:], " ")) | |
cmd.Stdout = os.Stdout | |
cmd.Stderr = os.Stderr | |
cmd.Env = env | |
err = cmd.Run() | |
if err != nil { | |
os.Exit(1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To pass down arguments with spaces in them, you need to double escape them, e.g.