2022-07-13 11:48:12 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"flag"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"regexp"
|
2022-08-29 13:41:47 +02:00
|
|
|
|
|
|
|
"git.milar.in/milarin/buildinfo"
|
2022-07-13 11:48:12 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
EnvFilePath = flag.String("f", ".env", "environment file")
|
|
|
|
|
|
|
|
EnvVarRegex = regexp.MustCompile(`^(.*?)=(.*?)$`)
|
|
|
|
EnvCommentRegex = regexp.MustCompile(`^[ \t]*#.*?$`)
|
2022-08-29 13:41:47 +02:00
|
|
|
|
|
|
|
ShowVersion = flag.Bool("v", false, "show version and exit")
|
2022-07-13 11:48:12 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
flag.Parse()
|
|
|
|
|
2022-08-29 13:41:47 +02:00
|
|
|
if *ShowVersion {
|
|
|
|
buildinfo.Print(buildinfo.Options{})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-07-13 11:48:12 +02:00
|
|
|
envFile, err := os.Open(*EnvFilePath)
|
|
|
|
if err != nil {
|
2022-07-25 17:15:16 +02:00
|
|
|
fmt.Fprintf(os.Stderr, "could not open file '%s': %s\n", *EnvFilePath, err.(*os.PathError).Err)
|
|
|
|
return
|
2022-07-13 11:48:12 +02:00
|
|
|
}
|
|
|
|
defer envFile.Close()
|
|
|
|
|
2022-08-17 00:15:44 +02:00
|
|
|
parseEnvFile(envFile)
|
2022-07-13 11:48:12 +02:00
|
|
|
args := flag.Args()
|
|
|
|
|
|
|
|
if len(args) == 0 {
|
2022-08-17 00:15:44 +02:00
|
|
|
for _, envVar := range os.Environ() {
|
2022-07-13 11:48:12 +02:00
|
|
|
fmt.Println(envVar)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
cmd := exec.Command(args[0], args[1:]...)
|
2022-08-17 00:15:44 +02:00
|
|
|
cmd.Env = os.Environ()
|
2022-07-13 11:48:12 +02:00
|
|
|
|
|
|
|
cmd.Stdin = os.Stdin
|
|
|
|
cmd.Stdout = os.Stdout
|
|
|
|
cmd.Stderr = os.Stderr
|
|
|
|
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
if exitErr, ok := err.(*exec.ExitError); ok {
|
|
|
|
os.Exit(exitErr.ExitCode())
|
|
|
|
return
|
|
|
|
} else {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-17 00:15:44 +02:00
|
|
|
func parseEnvFile(r io.Reader) {
|
2022-07-13 11:48:12 +02:00
|
|
|
s := bufio.NewScanner(r)
|
|
|
|
l := 0
|
2022-08-17 00:15:44 +02:00
|
|
|
|
2022-07-13 11:48:12 +02:00
|
|
|
for s.Scan() {
|
|
|
|
l++
|
|
|
|
|
|
|
|
matches := EnvVarRegex.FindStringSubmatch(s.Text())
|
|
|
|
if len(matches) != 0 {
|
|
|
|
key, value := matches[1], os.ExpandEnv(matches[2])
|
2022-08-17 00:15:44 +02:00
|
|
|
os.Setenv(key, value)
|
2022-08-04 17:04:00 +02:00
|
|
|
} else if s.Text() != "" && !EnvCommentRegex.MatchString(s.Text()) {
|
2022-07-13 11:48:12 +02:00
|
|
|
panic(fmt.Sprintf("invalid env syntax on line %d", l))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|