Skip to content

Instantly share code, notes, and snippets.

@pranavraja
Created June 12, 2014 08:30
Show Gist options
  • Save pranavraja/60ed95dbe5c80703de4e to your computer and use it in GitHub Desktop.
Save pranavraja/60ed95dbe5c80703de4e to your computer and use it in GitHub Desktop.
Environment variable helper
// 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)
}
}
@pranavraja
Copy link
Author

To pass down arguments with spaces in them, you need to double escape them, e.g.

cat 'a b' => cat 'a\ b'
cat a\ b => cat a\\ b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment