-
Notifications
You must be signed in to change notification settings - Fork 18
/
magefile.go
93 lines (76 loc) · 2.42 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
// Copyright 2022 The OWASP Coraza contributors
// SPDX-License-Identifier: Apache-2.0
//go:build mage
// +build mage
package main
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
)
var addLicenseVersion = "v1.0.0" // https://github.com/google/addlicense
// TODO: Use recent version (for example v1.53.2) to run on Go 1.20 (https://github.com/golangci/golangci-lint/pull/3414)
var golangCILintVer = "v1.48.0" // https://github.com/golangci/golangci-lint/releases
var gosImportsVer = "v0.1.5" // https://github.com/rinchsan/gosimports/releases/tag/v0.1.5
var errRunGoModTidy = errors.New("go.mod/sum not formatted, commit changes")
var errNoGitDir = errors.New("no .git directory found")
// Format formats code in this repository.
func Format() error {
if err := sh.RunV("go", "mod", "tidy"); err != nil {
return err
}
// addlicense strangely logs skipped files to stderr despite not being erroneous, so use the long sh.Exec form to
// discard stderr too.
if _, err := sh.Exec(map[string]string{}, io.Discard, io.Discard, "go", "run", fmt.Sprintf("github.com/google/addlicense@%s", addLicenseVersion),
"-c", "The OWASP Coraza contributors",
"-s=only",
"-ignore", "**/*.yml",
"-ignore", "**/*.yaml",
"-ignore", "examples/**", "."); err != nil {
return err
}
return sh.RunV("go", "run", fmt.Sprintf("github.com/rinchsan/gosimports/cmd/gosimports@%s", gosImportsVer),
"-w",
"-local",
"github.com/corazawaf/coraza-spoa",
".")
}
// Lint verifies code quality.
func Lint() error {
if err := sh.RunV("go", "run", fmt.Sprintf("github.com/golangci/golangci-lint/cmd/golangci-lint@%s", golangCILintVer), "run"); err != nil {
return err
}
if err := sh.RunV("go", "mod", "tidy"); err != nil {
return err
}
if sh.Run("git", "diff", "--exit-code", "go.mod", "go.sum") != nil {
return errRunGoModTidy
}
return nil
}
// Test runs all tests.
func Test() error {
if err := sh.RunV("go", "test", "./..."); err != nil {
return err
}
return nil
}
// Precommit installs a git hook to run check when committing
func Precommit() error {
if _, err := os.Stat(filepath.Join(".git", "hooks")); os.IsNotExist(err) {
return errNoGitDir
}
f, err := os.ReadFile(".pre-commit.hook")
if err != nil {
return err
}
return os.WriteFile(filepath.Join(".git", "hooks", "pre-commit"), f, 0755)
}
// Check runs lint and tests.
func Check() {
mg.SerialDeps(Lint, Test)
}