Skip to content

Commit

Permalink
Merge pull request #7 from muchobien/feat/add-silent-flag
Browse files Browse the repository at this point in the history
feat/add silent flag
  • Loading branch information
KROSF authored Aug 21, 2022
2 parents 6e7459b + 78b94b2 commit 66378ec
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
6 changes: 6 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ func main() {
Aliases: []string{"o"},
Usage: "Override existing environment variables with new ones",
},
&cli.BoolFlag{
Name: "silent",
Aliases: []string{"s"},
Value: false,
Usage: "Ignore errors if .env file is not found",
},
&cli.BoolFlag{
Name: "watch",
Aliases: []string{"w"},
Expand Down
38 changes: 37 additions & 1 deletion internal/common/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package common

import (
"fmt"
"os"
"strings"

"github.com/joho/godotenv"
Expand All @@ -11,8 +12,9 @@ import (
func Read(cCtx *cli.Context) (dict map[string]string, err error) {
filenames := cCtx.StringSlice("file")
extraEnvs := cCtx.StringSlice("env")
silent := cCtx.Bool("silent")

dict, err = godotenv.Read(filenames...)
dict, err = readFiles(filenames, silent)

if err != nil {
return
Expand All @@ -29,3 +31,37 @@ func Read(cCtx *cli.Context) (dict map[string]string, err error) {

return
}

func readFiles(filenames []string, silent bool) (envMap map[string]string, err error) {
envMap = make(map[string]string)

for _, filename := range filenames {
individualEnvMap, individualErr := readFile(filename)

if silent {
fmt.Fprintf(os.Stderr, "Warning: %s\n", individualErr)
continue
}

if individualErr != nil {
err = individualErr
return
}

for key, value := range individualEnvMap {
envMap[key] = value
}
}

return
}

func readFile(filename string) (envMap map[string]string, err error) {
file, err := os.Open(filename)
if err != nil {
return
}
defer file.Close()

return godotenv.Parse(file)
}

0 comments on commit 66378ec

Please sign in to comment.