Skip to content

Commit

Permalink
review: rework findInParentTree logic
Browse files Browse the repository at this point in the history
Signed-off-by: Marco Molteni <[email protected]>
  • Loading branch information
marco-m committed Mar 25, 2020
1 parent 6542dbc commit 94d8474
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 15 deletions.
35 changes: 22 additions & 13 deletions internal/command/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,26 +199,35 @@ func joinEnv(env []string) string {
// If found, returns the absolute path to the file.
func findInParentTree(secretsFile string, leafDir string) (string, error) {
if filepath.IsAbs(secretsFile) {
return "", fmt.Errorf("file specified (%s) is an absolute path: will not recurse up", secretsFile)
return "", fmt.Errorf(
"file specified (%s) is an absolute path: will not recurse up", secretsFile)
}

for {
joinedPath := filepath.Join(leafDir, secretsFile)
if _, err := os.Stat(joinedPath); err == nil {
// File found -- return the current filepath
return joinedPath, nil
} else if os.IsNotExist(err) {
upOne := filepath.Dir(leafDir)
if upOne == leafDir {
return "", fmt.Errorf(
"unable to locate file specified (%s): reached root of file system", secretsFile)

_, err := os.Stat(joinedPath)

if err != nil {
// If the file is not present, we just move up one level and run the next loop
// iteration
if os.IsNotExist(err) {
upOne := filepath.Dir(leafDir)
if upOne == leafDir {
return "", fmt.Errorf(
"unable to locate file specified (%s): reached root of file system", secretsFile)
}

leafDir = upOne
continue
}
// Move up to parent dir
leafDir = upOne
} else {
// Any other error

// If we have an unexpected error, we fail-fast
return "", fmt.Errorf("unable to locate file specified (%s): %s", secretsFile, err)
}

// If there's no error, we found the file so we return it
return joinedPath, nil
}
}

Expand Down
16 changes: 14 additions & 2 deletions internal/command/action_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,10 +302,22 @@ func TestLocateFileRecurseUp(t *testing.T) {
So(err, ShouldBeNil)
defer os.RemoveAll(topDir)

badFileName := "/foo/bar/baz"
absFileName := "/foo/bar/baz"
wantErrMsg := "file specified (/foo/bar/baz) is an absolute path: will not recurse up"

_, err = findInParentTree(badFileName, topDir)
_, err = findInParentTree(absFileName, topDir)
So(err.Error(), ShouldEqual, wantErrMsg)
})

Convey("returns a friendly error in unexpected circumstances (100% coverage)", t, func() {
topDir, err := ioutil.TempDir("", "summon")
So(err, ShouldBeNil)
defer os.RemoveAll(topDir)

fileNameWithNulByte := "pizza\x00margherita"
wantErrMsg := "unable to locate file specified (pizza\x00margherita): stat"

_, err = findInParentTree(fileNameWithNulByte, topDir)
So(err.Error(), ShouldStartWith, wantErrMsg)
})
}

0 comments on commit 94d8474

Please sign in to comment.