-
Notifications
You must be signed in to change notification settings - Fork 0
/
findup.go
71 lines (53 loc) · 1.25 KB
/
findup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package gofindup
import (
"io/ioutil"
"os"
"path/filepath"
)
type readDir func(string) ([]os.FileInfo, error)
var defaultReadDir readDir = ioutil.ReadDir
func hasFile(name, dir string, readdir readDir) (bool, error) {
files, err := readdir(dir)
if err != nil {
return false, err
}
for _, f := range files {
if name == f.Name() {
return true, nil
}
}
return false, nil
}
func findupFrom(name, dir string, readdir readDir) (string, error) {
for {
found, err := hasFile(name, dir, readdir)
if err != nil {
return "", err
}
if found {
return filepath.Join(dir, name), nil
}
parent := filepath.Dir(dir)
if parent == dir {
return "", nil
}
dir = parent
}
}
func findup(name string, readdir readDir) (string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", err
}
return findupFrom(name, cwd, readdir)
}
// Recursively find a file by walking up parents in the file tree
// starting from a specific directory.
func FindupFrom(name, dir string) (string, error) {
return findupFrom(name, dir, defaultReadDir)
}
// Recursively find a file by walking up parents in the file tree
// starting from the current working directory.
func Findup(name string) (string, error) {
return findup(name, defaultReadDir)
}