-
Notifications
You must be signed in to change notification settings - Fork 5
/
repo_root.go
71 lines (58 loc) · 1.47 KB
/
repo_root.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 repotools
import (
"fmt"
"os"
"path/filepath"
)
// GetRepoRoot uses the current working directory to find the repository root.
func GetRepoRoot() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("failed to get current directory: %w", err)
}
repoRootPath, err := FindRepoRoot(dir)
if err != nil {
return "", fmt.Errorf("failed to find git repository: %w", err)
}
return repoRootPath, nil
}
// FindRepoRoot returns the absolute path to the root directory of the
// repository, or error. If the dir passed in is a relative path it will be
// used relative to the current working directory of the executable.
func FindRepoRoot(dir string) (string, error) {
if len(dir) == 0 {
dir = "."
}
if !filepath.IsAbs(dir) {
var err error
dir, err = JoinWorkingDirectory(dir)
if err != nil {
return "", err
}
}
var found bool
for {
if dir == string(filepath.Separator) {
break
}
_, err := os.Stat(filepath.Join(dir, ".git"))
if err == nil {
found = true
break
}
dir = filepath.Dir(dir)
}
if !found {
return "", fmt.Errorf(".git directory not found")
}
return dir, nil
}
// JoinWorkingDirectory will return an absolute file system path of the passed
// in dir path with the current working directory.
func JoinWorkingDirectory(dir string) (string, error) {
wd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("failed to get working directory, %w", err)
}
return filepath.Join(wd, dir), nil
}