-
Notifications
You must be signed in to change notification settings - Fork 7
/
repo.go
94 lines (83 loc) · 1.75 KB
/
repo.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
)
var errDone = errors.New("done")
var errTop = errors.New("top of fs")
func up(done func(dir string) error) error {
top := false
p, err := os.Getwd()
if err != nil {
return err
}
p = filepath.Clean(p)
for {
// check our predicate for this level
if err := done(p); err != nil {
return err
}
// already at the top but found nothing
if top {
return errTop
}
// go up one level
// make a note if we're at the top
new := filepath.Dir(p)
top = new == p
p = new
}
}
func Roots() (repo, project string, err error) {
stat := func(dir, p string) (os.FileInfo, error) {
return os.Stat(filepath.Join(dir, p))
}
err = up(func(dir string) error {
if repo == "" {
fi, err := stat(dir, ".git")
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
if err == nil && fi.IsDir() {
repo = dir
}
}
if project == "" {
fi, err := stat(dir, "go.mod")
if err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
if err == nil && fi.Mode().IsRegular() {
project = dir
}
}
// found both
if repo != "" && project != "" {
return errDone
}
return nil
})
// up always returns an error
switch err {
case errDone:
return repo, project, nil
case errTop:
// no errors but missing go.mod and/or .git
if project == "" {
err = errors.New("could not find repository root")
} else {
err = errors.New("could not find project or repository root")
}
default:
// stat error while searching for go.mod and .git
if project == "" {
err = fmt.Errorf("could not find repository root: %w", err)
} else {
err = fmt.Errorf("could not find project or repository root: %w", err)
}
}
return "", "", err
}