Skip to content

Instantly share code, notes, and snippets.

@sanbornm
Created June 16, 2016 16:26
Show Gist options
  • Save sanbornm/9db3f7e6161adb36b7b00aefd612005d to your computer and use it in GitHub Desktop.
Save sanbornm/9db3f7e6161adb36b7b00aefd612005d to your computer and use it in GitHub Desktop.
Utility package to find files traversing up the path
// Utility functions used to search up through directories for
// specific files.
package traverse
import (
"fmt"
"io/ioutil"
"path/filepath"
)
// Search a single directory for a specific file name
func SearchDirForFilename(dir string, filename string) (string, error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Println(err)
}
for _, file := range files {
if file.Name() == filename {
path, err := filepath.Abs(dir)
if err != nil {
return "", err
fmt.Printf("Could not determine absolute dir: %s", err)
}
return filepath.Join(path, file.Name()), nil
}
}
return "", nil
}
// Search directories going up looking for specific file name, limit 5
func FindFile(startingDir string, filename string) string {
// Max 5
for i := 0; i < 5; i++ {
dir, err := filepath.Abs(startingDir)
if err != nil {
fmt.Println(err)
}
startingDir = filepath.Join(startingDir, "..")
path, err := SearchDirForFilename(dir, filename)
if path != "" {
return path
}
}
return ""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment