Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion godotenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
39 changes: 39 additions & 0 deletions godotenv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}