You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

findup.go 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package gofindup
  2. import (
  3. "os"
  4. "path/filepath"
  5. "github.com/spf13/afero"
  6. )
  7. var fs = afero.NewOsFs()
  8. func hasFile(name, dir string, fs afero.Fs) (bool, error) {
  9. files, err := afero.ReadDir(fs, dir)
  10. if err != nil {
  11. return false, err
  12. }
  13. for _, f := range files {
  14. if name == f.Name() {
  15. return true, nil
  16. }
  17. }
  18. return false, nil
  19. }
  20. func findupFrom(name, dir string, fs afero.Fs) (string, error) {
  21. for {
  22. found, err := hasFile(name, dir, fs)
  23. if err != nil {
  24. return "", err
  25. }
  26. if found {
  27. return filepath.Join(dir, name), nil
  28. }
  29. parent := filepath.Dir(dir)
  30. if parent == dir {
  31. return "", nil
  32. }
  33. dir = parent
  34. }
  35. }
  36. func findup(name string, fs afero.Fs) (string, error) {
  37. cwd, err := os.Getwd()
  38. if err != nil {
  39. return "", err
  40. }
  41. return findupFrom(name, cwd, fs)
  42. }
  43. // Recursively find a file by walking up parents in the file tree
  44. // starting from a specific directory.
  45. func FindupFrom(name, dir string) (string, error) {
  46. return findupFrom(name, dir, fs)
  47. }
  48. // Recursively find a file by walking up parents in the file tree
  49. // starting from the current working directory.
  50. func Findup(name string) (string, error) {
  51. return findup(name, fs)
  52. }