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
|
//go:build mage
// Magefile provides build targets for the foostore project.
// Targets: Default (Build), Build, Test, Vet, Install, Uninstall, Clean
// Follows the same style as other projects (e.g. hexai).
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
)
const (
binary = "./foostore"
binaryName = "foostore"
mainPkg = "./cmd/foostore"
)
// Default builds the binary so that a bare `mage` invocation is equivalent to `mage build`.
func Default() { mg.Deps(Build) }
// Build compiles the binary to ./foostore.
func Build() error {
fmt.Println("Building", binary)
// Remove legacy output path from older builds to avoid confusion.
_ = os.Remove("./bin/foostore")
return sh.RunV("go", "build", "-o", binary, mainPkg)
}
// Test runs all tests in the module.
func Test() error {
fmt.Println("Running tests")
return sh.RunV("go", "test", "./...")
}
// Vet runs go vet on all packages.
func Vet() error {
fmt.Println("Vetting")
return sh.RunV("go", "vet", "./...")
}
// Install builds the binary and copies it to $GOPATH/bin (default ~/go/bin).
func Install() error {
mg.Deps(Build)
// Resolve GOPATH; fall back to ~/go when the environment variable is unset.
gopath := os.Getenv("GOPATH")
if gopath == "" {
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("resolving home directory: %w", err)
}
gopath = filepath.Join(home, "go")
}
binDir := filepath.Join(gopath, "bin")
if err := os.MkdirAll(binDir, 0o755); err != nil {
return fmt.Errorf("creating %s: %w", binDir, err)
}
dest := filepath.Join(binDir, binaryName)
return sh.RunV("cp", "-v", binary, dest)
}
// Uninstall removes the binary from $GOPATH/bin (default ~/go/bin).
// It is idempotent: if the binary is not installed, it succeeds silently.
func Uninstall() error {
// Mirror Install()'s GOPATH resolution so the paths always match.
gopath := os.Getenv("GOPATH")
if gopath == "" {
home, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("resolving home directory: %w", err)
}
gopath = filepath.Join(home, "go")
}
dest := filepath.Join(gopath, "bin", binaryName)
fmt.Println("Uninstalling", dest)
if err := os.Remove(dest); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
// Clean removes the local build artifact.
func Clean() error {
fmt.Println("Cleaning", binary)
if err := os.Remove(binary); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
_ = os.Remove("./bin/foostore")
return nil
}
|