Add "-s" option to delete dotenv files on command failure
Rationale: sometimes we want to secure our environment variables so that the next command cannot access them. We can chain the two operations: ``` godotenv cmd rm .env ``` The problem here is if the command fails, we do not remove the file. We can code some shell: ``` godotenv cmd || rm cmd && exit 1 ``` There are two problems now: 1. We lose the original exit code. 2. We have to write this for each executed command. `godotenv -s` solves everything.
This commit is contained in:
parent
ddf83eb33b
commit
c6e8ca9915
|
@ -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
|
||||
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue