From 83b9cbdc3feee6279a973dc366e2dd6514358936 Mon Sep 17 00:00:00 2001 From: Elchin Gasimov Date: Sun, 12 Jun 2022 12:01:52 +0400 Subject: [PATCH] Issue 175: Command does not load dotenv files if some do not exist --- godotenv.go | 16 +++++++++++++++- godotenv_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/godotenv.go b/godotenv.go index 975d7bc..20e24ca 100644 --- a/godotenv.go +++ b/godotenv.go @@ -137,7 +137,9 @@ func Unmarshal(str string) (envMap map[string]string, err error) { // If you want more fine grained control over your command it's recommended // that you use `Load()` or `Read()` and the `os/exec` package yourself. func Exec(filenames []string, cmd string, cmdArgs []string) error { - Load(filenames...) + + filteredFilenames := filterFilesNotExist(filenames) + Load(filteredFilenames...) command := exec.Command(cmd, cmdArgs...) command.Stdin = os.Stdin @@ -361,3 +363,15 @@ func doubleQuoteEscape(line string) string { } return line } + +func filterFilesNotExist(filenames []string) []string { + result := make([]string, 0, len(filenames)) + for _, fileName := range filenames { + if _, err := os.Stat(fileName); err != nil { + fmt.Fprintf(os.Stderr, "File: `%s` not found \n", fileName) + } else { + result = append(result, fileName) + } + } + return result +} diff --git a/godotenv_test.go b/godotenv_test.go index 49f6fe0..30bae2c 100644 --- a/godotenv_test.go +++ b/godotenv_test.go @@ -472,3 +472,42 @@ func TestRoundtrip(t *testing.T) { } } + +func Test_filterFilesNotExist(t *testing.T) { + type testCase struct { + description string + givenFilenames []string + expectedFileNames []string + } + + testCases := []testCase{ + testCase{ + description: "When all files do exist, then return all", + givenFilenames: []string{"fixtures/equals.env", "fixtures/exported.env"}, + expectedFileNames: []string{"fixtures/equals.env", "fixtures/exported.env"}, + }, + testCase{ + description: "When none of the files do exist, then return empty slice", + givenFilenames: []string{"not-existed-file.env", "wrong-fileName.env"}, + expectedFileNames: []string{}, + }, + testCase{ + description: "When some of the files do exist, then filter and return exist files", + givenFilenames: []string{"not-existed-file.env", "wrong-fileName.env", "fixtures/equals.env"}, + expectedFileNames: []string{"fixtures/equals.env"}, + }, + } + + for _, testCase := range testCases { + //when + actual := filterFilesNotExist(testCase.givenFilenames) + + //then + if !reflect.DeepEqual(actual, testCase.expectedFileNames) { + t.Error("For", testCase.description, + "\n Given: ", testCase.givenFilenames, + "\n Expected:", testCase.expectedFileNames, + "\n Got", actual) + } + } +}