databricks-cli/libs/folders/folders.go

35 lines
671 B
Go
Raw Normal View History

2022-07-07 18:56:59 +00:00
package folders
import (
"errors"
"os"
"path/filepath"
2022-07-07 18:56:59 +00:00
)
// FindDirWithLeaf returns the first directory that holds `leaf`,
// traversing up to the root of the filesystem, starting at `dir`.
func FindDirWithLeaf(dir string, leaf string) (string, error) {
2022-07-07 18:56:59 +00:00
for {
_, err := os.Stat(filepath.Join(dir, leaf))
// No error means we found the leaf in dir.
if err == nil {
return dir, nil
}
// ErrNotExist means we continue traversal up the tree.
2022-07-07 18:56:59 +00:00
if errors.Is(err, os.ErrNotExist) {
next := filepath.Dir(dir)
if dir == next {
// Return if we cannot continue traversal.
return "", err
2022-07-07 18:56:59 +00:00
}
2022-07-07 18:56:59 +00:00
dir = next
continue
}
return "", err
2022-07-07 18:56:59 +00:00
}
}