diff --git a/README.md b/README.md index 1ec45b2..d79938e 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,8 @@ Assuming you've installed the command as above and you've got `$GOPATH/bin` in y godotenv -f /some/path/to/.env some_command with some args ``` -If you don't specify `-f` it will fall back on the default of loading `.env` in `PWD` +If you don't specify `-f` it will fall back on the default of loading `.env` in `PWD`. +Optional flag `-s` removes all the loaded files if the command fails and returns the same exit code. ### Writing Env Files diff --git a/cmd/godotenv/cmd.go b/cmd/godotenv/cmd.go index 8dce420..e027f21 100644 --- a/cmd/godotenv/cmd.go +++ b/cmd/godotenv/cmd.go @@ -4,28 +4,32 @@ import ( "flag" "fmt" "log" - + "os" + "os/exec" "strings" "github.com/joho/godotenv" ) func main() { - var showHelp bool + var showHelp, deleteFileOnError bool flag.BoolVar(&showHelp, "h", false, "show help") var rawEnvFilenames string flag.StringVar(&rawEnvFilenames, "f", "", "comma separated paths to .env files") + flag.BoolVar(&deleteFileOnError, "s", false, "delete .env files if the command fails, copy exit status") flag.Parse() usage := ` Run a process with an env setup from a .env file -godotenv [-f ENV_FILE_PATHS] COMMAND_ARGS +godotenv [-f ENV_FILE_PATHS] [-s] COMMAND_ARGS -ENV_FILE_PATHS: comma separated paths to .env files +ENV_FILE_PATHS: comma separated paths to .env files (.env is the default) COMMAND_ARGS: command and args you want to run + -s delete .env files if the command fails, copy exit status + example godotenv -f /path/to/something/.env,/another/path/.env fortune ` @@ -49,6 +53,20 @@ example err := godotenv.Exec(envFilenames, cmd, cmdArgs) if err != nil { + if deleteFileOnError { + if len(envFilenames) == 0 { + envFilenames = []string{".env"} + } + for _, filename := range envFilenames { + fileErr := os.Remove(filename) + if fileErr != nil { + log.Println(fileErr) + } + } + if state, ok := err.(*exec.ExitError); ok { + os.Exit(state.ExitCode()) + } + } log.Fatal(err) } }