build: replace make with mage

- Replace the makefile with the magefile
- Update the Dockerfile
- Update go.mod
This commit is contained in:
Dan Anglin 2023-08-11 14:59:21 +01:00
parent 52868d7aa8
commit 69c3165fc1
Signed by: dananglin
GPG key ID: 0C1D44CFBEE68638
5 changed files with 79 additions and 24 deletions

View file

@ -1,21 +0,0 @@
BINARY = spruce
INSTALL_PREFIX ?= /usr/local
CGO_ENABLED ?= 0
GOOS ?= linux
GOARCH ?= amd64
VERSION = 0.1.0
LDFLAGS = "-s -w -X main.version=$(VERSION) -X main.installPrefix=$(INSTALL_PREFIX)"
$(BINARY):
go build -ldflags=$(LDFLAGS) -v -a -o $(BINARY)
install: spruce
cp -f $(BINARY) $(INSTALL_PREFIX)/bin
chmod 0755 $(INSTALL_PREFIX)/bin/$(BINARY)
uninstall:
rm -f $(INSTALL_PREFIX)/bin/$(BINARY)
clean:
go clean

View file

@ -1,4 +1,5 @@
FROM golang:1.19-buster AS spruce-builder
# syntax=docker/dockerfile:1
FROM golang:1.21-buster AS spruce-builder
ENV CGO_ENABLED=0
ENV GOOS=linux
@ -10,7 +11,7 @@ WORKDIR /workspace
RUN go build -a -v -o /workspace/spruce
FROM alpine:3.17
FROM alpine:3.18
COPY --from=spruce-builder /workspace/spruce /usr/local/bin

4
go.mod
View file

@ -1,3 +1,5 @@
module codeflow.dananglin.me.uk/apollo/spruce
go 1.20
go 1.21
require github.com/magefile/mage v1.15.0

2
go.sum
View file

@ -0,0 +1,2 @@
github.com/magefile/mage v1.15.0 h1:BvGheCMAsG3bWUDbZ8AyXXpCNwU9u5CB6sM+HNb9HYg=
github.com/magefile/mage v1.15.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A=

71
magefiles/mage.go Normal file
View file

@ -0,0 +1,71 @@
//go:build mage
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/magefile/mage/mg"
"github.com/magefile/mage/sh"
)
var (
Default = Build
binary = "spruce"
defaultInstallPrefix = "/usr/local"
)
// Build builds the binary.
func Build() error {
flags := ldflags()
return sh.Run("go", "build", "-ldflags="+flags, "-v", "-a", "-o", binary, ".")
}
// Install installs the binary to the execution path.
func Install() error {
mg.Deps(Build)
installPrefix := os.Getenv("SPRUCE_INSTALL_PREFIX")
if installPrefix == "" {
installPrefix = defaultInstallPrefix
}
dest := filepath.Join(installPrefix, "bin", binary)
if err := sh.Copy(binary, dest); err != nil {
return fmt.Errorf("unable to install %s; %w", binary, err)
}
return nil
}
// Clean cleans the workspace
func Clean() error {
if err := sh.Rm(binary); err != nil {
return fmt.Errorf("unable to remove %s; %w", binary, err)
}
if err := sh.Run("go", "clean", "./..."); err != nil {
return fmt.Errorf("unable to run 'go clean'; %w", err)
}
return nil
}
// ldflags returns the build flags.
func ldflags() string {
ldflagsfmt := "-s -w -X main.version=%s"
return fmt.Sprintf(ldflagsfmt, version())
}
// version returns the latest git tag using git describe.
func version() string {
version, err := sh.Output("git", "describe", "--tags")
if err != nil {
version = "N/A"
}
return version
}