This repository has been archived by the owner on Dec 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
magefile.go
339 lines (300 loc) · 7.91 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
//go:build mage
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"io/fs"
"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"
gomobile = "gomobile"
)
// Build builds the library.
func Build() error {
println("Building...")
return sh.Run(Go, "build", "-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 Fuzz() error {
return runFuzzTests()
}
func runTests(extraTestArgs ...string) error {
args := []string{"test"}
if mg.Verbose() {
args = append(args, "-v")
}
args = append(args, "-tags=jwx_es256k")
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 runFuzzTests(extraTestArgs ...string) error {
dirs := []string{"./did"}
for _, dir := range dirs {
functionNames, _ := getFuzzTests(dir)
for _, testName := range functionNames {
args := []string{"test"}
if mg.Verbose() {
args = append(args, "-v")
}
args = append(args, dir)
args = append(args, fmt.Sprintf("-run=%s", testName))
args = append(args, fmt.Sprintf("-fuzz=%s", testName))
args = append(args, "-fuzztime=10s")
testEnv := map[string]string{
"CGO_ENABLED": "1",
"GO111MODULE": "on",
}
writer := ColorizeTestStdout()
fmt.Printf("%+v\n", args)
_, err := sh.Exec(testEnv, writer, os.Stderr, Go, args...)
if err != nil {
return err
}
}
}
return nil
}
func getFuzzTests(src string) ([]string, error) {
// src is the input for which we want to inspect the AST.
var testFilePaths []string
filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
if d.IsDir() {
return nil
}
if !strings.HasSuffix(path, "test.go") {
return nil
}
testFilePaths = append(testFilePaths, path)
return nil
})
// Create the AST by parsing src.
fset := token.NewFileSet() // positions are relative to fset
var testNames []string
for _, filename := range testFilePaths {
// Pass in nil to automatically parse the file
f, err := parser.ParseFile(fset, filename, nil, 0)
if err != nil {
panic(err)
}
ast.FileExports(f)
ast.FilterFile(f, func(s string) bool {
p := strings.HasPrefix(s, "Fuzz")
if p {
testNames = append(testNames, s)
}
return p
})
}
return testNames, nil
}
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")
}
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
}
// 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
}
// 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")
}
func installGoMobileIfNotPresent() error {
return installIfNotPresent(gomobile, "golang.org/x/mobile/cmd/gomobile@latest")
}
// IOS Generates the iOS packages
// Note: this command also installs "gomobile" if not present
func IOS() error {
if err := installGoMobileIfNotPresent(); err != nil {
logrus.WithError(err).Fatal("Error installing gomobile")
return err
}
println("Building iOS...")
bindIOS := sh.RunCmd(gomobile, "bind", "-target", "ios", "-tags", "jwx_es256k")
return bindIOS("./mobile")
}
// Android Generates the Android packages
// Note: this command also installs "gomobile" if not present
func Android() error {
if err := installGoMobileIfNotPresent(); err != nil {
logrus.WithError(err).Fatal("Error installing gomobile")
return err
}
apiLevel := "33"
println("Building Android - API Level: " + apiLevel + "...")
bindAndroid := sh.RunCmd("gomobile", "bind", "-target", "android", "-androidapi", "33", "-tags", "jwx_es256k")
return bindAndroid("./mobile")
}