generated from TBD54566975/tbd-project-template
-
Notifications
You must be signed in to change notification settings - Fork 18
/
magefile.go
262 lines (230 loc) · 6.38 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
//go:build mage
package main
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"strings"
"syscall"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
"github.com/sirupsen/logrus"
"golang.org/x/term"
)
const (
Go = "go"
)
// Build builds the library.
func Build() error {
println("Building...")
version, err := sh.Output("git", "describe", "--always", "--tags")
if err != nil {
println("error getting current version: ", err.Error())
}
return sh.Run(Go, "build", fmt.Sprintf("-ldflags=-X github.com/TBD54566975/did-dht/config.Version=%s", version), "-tags", "jwx_es256k", "./...")
}
// Clean deletes any build artifacts.
func Clean() {
println("Cleaning...")
_ = os.RemoveAll("bin")
}
// Test runs unit tests without coverage.
// The mage `-v` option will trigger a verbose output of the test
func Test() error {
return runTests()
}
func runTests(extraTestArgs ...string) error {
args := []string{"test"}
if mg.Verbose() {
args = append(args, "-v")
}
args = append(args, "-tags=jwx_es256k")
args = append(args, "-covermode=atomic")
args = append(args, "-coverprofile=coverage.out")
args = append(args, extraTestArgs...)
args = append(args, "./...")
testEnv := map[string]string{
"CGO_ENABLED": "1",
"GO111MODULE": "on",
}
writer := ColorizeTestStdout()
_, _ = fmt.Printf("%+v", args)
_, err := sh.Exec(testEnv, writer, os.Stderr, Go, args...)
return err
}
// CITest runs unit tests with coverage as a part of CI.
// The mage `-v` option will trigger a verbose output of the test
func CITest() error {
return runCITests()
}
func runCITests(extraTestArgs ...string) error {
args := []string{"test"}
if mg.Verbose() {
args = append(args, "-v")
}
args = append(args, "-tags=jwx_es256k")
args = append(args, "-covermode=atomic")
args = append(args, "-coverprofile=coverage.out")
args = append(args, "-race")
args = append(args, extraTestArgs...)
args = append(args, "./...")
testEnv := map[string]string{
"CGO_ENABLED": "1",
"GO111MODULE": "on",
}
writer := ColorizeTestStdout()
fmt.Printf("%+v", args)
_, err := sh.Exec(testEnv, writer, os.Stderr, Go, args...)
return err
}
func Deps() error {
return brewInstall("golangci-lint")
}
func brewInstall(formula string) error {
return sh.Run("brew", "install", formula)
}
func Lint() error {
return sh.Run("golangci-lint", "run")
}
// Spec generates an OpenAPI spec yaml based on code annotations.
func Spec() error {
swagCommand := "swag"
if err := installIfNotPresent(swagCommand, "github.com/swaggo/swag/v2/cmd/[email protected]"); err != nil {
logrus.WithError(err).Error("failed to install swag")
return err
}
// We need to download deps first as a workaround to https://github.com/TBD54566975/did-dht/issues/515
if err := sh.Run(Go, "mod", "download"); err != nil {
logrus.WithError(err).Error("failed to download dependencies")
return err
}
if err := sh.Run(swagCommand, "fmt", "-d", "pkg/server"); err != nil {
logrus.WithError(err).Error("failed to format swagger docs")
return err
}
return sh.Run(swagCommand, "init", "-g", "cmd/main.go", "--overridesFile", "docs/overrides.swaggo", "--pd", "--parseInternal", "-ot", "yaml")
}
func ColorizeTestOutput(w io.Writer) io.Writer {
writer := NewRegexpWriter(w, `PASS.*`, "\033[32m$0\033[0m")
return NewRegexpWriter(writer, `FAIL.*`, "\033[31m$0\033[0m")
}
func ColorizeTestStdout() io.Writer {
if term.IsTerminal(syscall.Stdout) {
return ColorizeTestOutput(os.Stdout)
}
return os.Stdout
}
type regexpWriter struct {
inner io.Writer
re *regexp.Regexp
repl []byte
}
func NewRegexpWriter(inner io.Writer, re string, repl string) io.Writer {
return ®expWriter{inner, regexp.MustCompile(re), []byte(repl)}
}
func (w *regexpWriter) Write(p []byte) (int, error) {
r := w.re.ReplaceAll(p, w.repl)
n, err := w.inner.Write(r)
if n > len(r) {
n = len(r)
}
return n, err
}
func runGo(cmd string, args ...string) error {
return sh.Run(findOnPathOrGoPath(Go), append([]string{"run", cmd}, args...)...)
}
// InstallIfNotPresent installs a go based tool (if not already installed)
func installIfNotPresent(execName, goPackage string) error {
usr, err := user.Current()
if err != nil {
logrus.WithError(err).Fatal()
return err
}
pathOfExec := findOnPathOrGoPath(execName)
if len(pathOfExec) == 0 {
cmd := exec.Command(Go, "get", "-u", goPackage)
if err := runGoCommand(usr, *cmd); err != nil {
logrus.WithError(err).Warnf("Error running command: %s", cmd.String())
cmd = exec.Command(Go, "install", goPackage)
if err := runGoCommand(usr, *cmd); err != nil {
logrus.WithError(err).Fatalf("Error running command: %s", cmd.String())
return err
}
}
logrus.Infof("Successfully installed %s", goPackage)
}
return nil
}
func runGoCommand(usr *user.User, cmd exec.Cmd) error {
cmd.Dir = usr.HomeDir
if err := cmd.Start(); err != nil {
logrus.WithError(err).Fatalf("Error running command: %s", cmd.String())
return err
}
return cmd.Wait()
}
func findOnPathOrGoPath(execName string) string {
if p := findOnPath(execName); p != "" {
return p
}
p := filepath.Join(goPath(), "bin", execName)
if _, err := os.Stat(p); err == nil {
return p
}
fmt.Printf("Could not find %s on PATH or in GOPATH/bin\n", execName)
return ""
}
func findOnPath(execName string) string {
pathEnv := os.Getenv("PATH")
pathDirectories := strings.Split(pathEnv, string(os.PathListSeparator))
for _, pathDirectory := range pathDirectories {
possible := filepath.Join(pathDirectory, execName)
stat, err := os.Stat(possible)
if err == nil || os.IsExist(err) {
if (stat.Mode() & 0111) != 0 {
return possible
}
}
}
return ""
}
func goPath() string {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
return ""
}
goPath, goPathSet := os.LookupEnv("GOPATH")
if !goPathSet {
goPath = filepath.Join(usr.HomeDir, Go)
}
return goPath
}
// CBT runs clean; build; test
func CBT() error {
Clean()
if err := Build(); err != nil {
return err
}
if err := Test(); err != nil {
return err
}
return nil
}
// Vuln downloads and runs govulncheck https://go.dev/blog/vuln
func Vuln() error {
println("Vulnerability checks...")
if err := installGoVulnIfNotPresent(); err != nil {
logrus.WithError(err).Error("error installing go-vuln")
return err
}
return sh.Run("govulncheck", "./...")
}
func installGoVulnIfNotPresent() error {
return installIfNotPresent("govulncheck", "golang.org/x/vuln/cmd/govulncheck@latest")
}