-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
magefile.go
109 lines (95 loc) · 2.07 KB
/
magefile.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// +build mage,go1.9
package main
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/magefile/mage/sh"
)
const (
// Linting tools.
goplsImportPath = "golang.org/x/tools/gopls"
goimportsImportPath = "golang.org/x/tools/cmd/goimports"
golintImportPath = "golang.org/x/lint/golint"
bin = ".bin"
)
var (
goCmd = os.Getenv("GOCMD")
goVersion = runtime.Version()
cwd, _ = os.Getwd()
)
func init() {
if goCmd == "" {
goCmd = "go"
}
}
// Fix runs "goimports -w ." to fix all files.
func Fix() error {
root, err := findRoot(cwd)
if err != nil {
return err
}
goimportsCmd := filepath.Join(root, bin, "goimports")
return sh.Run(goimportsCmd, "-w", root)
}
// Install installs all development dependencies.
func Install() error {
root, err := findRoot(cwd)
if err != nil {
return err
}
deps := []string{
goplsImportPath, // not used in CI
goimportsImportPath,
golintImportPath,
}
gobin := filepath.Join(root, bin)
for _, dep := range deps {
if err := sh.RunWith(
map[string]string{"GOBIN": gobin},
goCmd, "install", dep,
); err != nil {
return err
}
}
return nil
}
// Lint lints using "golint" and "goimports".
func Lint() error {
root, err := findRoot(cwd)
if err != nil {
return err
}
goimportsCmd := filepath.Join(root, bin, "goimports")
goimportsDiff, err := sh.Output(goimportsCmd, "-d", root)
if err != nil {
return err
}
if goimportsDiff != "" {
return fmt.Errorf("\n%s", goimportsDiff)
}
golintCmd := filepath.Join(root, bin, "golint")
return sh.Run(golintCmd, "-set_exit_status", filepath.Join(root, "..."))
}
// Test tests using "go test".
func Test() error {
root, err := findRoot(cwd)
if err != nil {
return err
}
flags := strings.Split(os.Getenv("TEST_FLAGS"), " ")
args := append([]string{"test"}, flags...)
return sh.Run(goCmd, append(args, filepath.Join(root, "..."))...)
}
func findRoot(dir string) (string, error) {
matches, err := filepath.Glob(filepath.Join(dir, "go.mod"))
if err != nil {
return "", err
}
if matches != nil {
return dir, nil
}
return findRoot(filepath.Dir(dir))
}