forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbasepath.go
74 lines (58 loc) · 1.46 KB
/
basepath.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
package fsutils
import (
"bytes"
"cmp"
"context"
"fmt"
"os/exec"
"path/filepath"
"github.com/ldez/grignotin/goenv"
)
// Relative path modes.
const (
RelativePathModeGoMod = "gomod"
RelativePathModeGitRoot = "gitroot"
RelativePathModeCfg = "cfg"
RelativePathModeWd = "wd"
)
func AllRelativePathModes() []string {
return []string{RelativePathModeGoMod, RelativePathModeGitRoot, RelativePathModeCfg, RelativePathModeWd}
}
func GetBasePath(ctx context.Context, mode, cfgDir string) (string, error) {
mode = cmp.Or(mode, RelativePathModeCfg)
switch mode {
case RelativePathModeCfg:
if cfgDir == "" {
return GetBasePath(ctx, RelativePathModeWd, cfgDir)
}
return cfgDir, nil
case RelativePathModeGoMod:
goMod, err := goenv.GetOne(ctx, goenv.GOMOD)
if err != nil {
return "", fmt.Errorf("get go.mod path: %w", err)
}
return filepath.Dir(goMod), nil
case RelativePathModeGitRoot:
root, err := gitRoot(ctx)
if err != nil {
return "", fmt.Errorf("get git root: %w", err)
}
return root, nil
case RelativePathModeWd:
wd, err := Getwd()
if err != nil {
return "", fmt.Errorf("get wd: %w", err)
}
return wd, nil
default:
return "", fmt.Errorf("unknown relative path mode: %s", mode)
}
}
func gitRoot(ctx context.Context) (string, error) {
cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
out, err := cmd.Output()
if err != nil {
return "", err
}
return string(bytes.TrimSpace(out)), nil
}