Skip to content

Commit

Permalink
🚧 attempt to not have to hard-code version and build dates
Browse files Browse the repository at this point in the history
  • Loading branch information
acidjazz committed Mar 9, 2024
1 parent 5b08f69 commit f1f4fcb
Show file tree
Hide file tree
Showing 4 changed files with 180 additions and 4 deletions.
21 changes: 20 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,23 @@
PACKAGE=cli


EXE =
ifeq ($(shell go env GOOS),windows)
EXE = .exe
endif

## The following tasks delegate to `script/build.go` so they can be run cross-platform.

.PHONY: bin/vc$(EXE)
bin/vc$(EXE): script/build$(EXE)
@script/build$(EXE) $@

script/build$(EXE): script/build.go
ifeq ($(EXE),)
GOOS= GOARCH= GOARM= GOFLAGS= CGO_ENABLED= go build -o $@ $<
else
go build -o $@ $<
endif


ray:
@go get github.com/octoper/go-ray
Expand Down
4 changes: 4 additions & 0 deletions pkg/build/build.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package build

var Version = "DEV"
var Date = ""
7 changes: 4 additions & 3 deletions pkg/cmd/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/MakeNowJust/heredoc/v2"
"github.com/spf13/cobra"
"github.com/vulncheck-oss/cli/pkg/auth"
"github.com/vulncheck-oss/cli/pkg/build"
"github.com/vulncheck-oss/cli/pkg/cmd/ascii"
cmdVersion "github.com/vulncheck-oss/cli/pkg/cmd/version"
"os"
Expand All @@ -19,7 +20,7 @@ func (ae *AuthError) Error() string {
return ae.err.Error()
}

func NewCmdRoot(version, buildDate string) *cobra.Command {
func NewCmdRoot() *cobra.Command {
cmd := &cobra.Command{
Use: "vc <command> <subcommand> [flags]",
Short: "VulnCheck CLI.",
Expand All @@ -30,7 +31,7 @@ func NewCmdRoot(version, buildDate string) *cobra.Command {
$ vc backup abb
`),
Annotations: map[string]string{
"versionInfo": cmdVersion.Format(version, buildDate),
"versionInfo": cmdVersion.Format(build.Version, build.Date),
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {

Expand All @@ -54,7 +55,7 @@ func NewCmdRoot(version, buildDate string) *cobra.Command {

func Execute(version string, date string) {

if err := NewCmdRoot(version, date).Execute(); err != nil {
if err := NewCmdRoot().Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
Expand Down
152 changes: 152 additions & 0 deletions script/build.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package main

import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
)

var tasks = map[string]func(string) error{
"bin/vc": func(exe string) error {
ldflags := os.Getenv("GO_LDFLAGS")
ldflags = fmt.Sprintf("-X github.com/vulncheck-oss/cli/pkg/build.Version=%s %s", version(), ldflags)
ldflags = fmt.Sprintf("-X github.com/vulncheck-oss/cli/pkg/build.Date=%s %s", date(), ldflags)

return run("go", "build", "-trimpath", "-ldflags", ldflags, "-o", exe, "./cmd/vc")
},
"clean": func(_ string) error {
return rmrf("bin", "share")
},
}

var self string

func main() {
args := os.Args[:1]
for _, arg := range os.Args[1:] {
if idx := strings.IndexRune(arg, '='); idx >= 0 {
os.Setenv(arg[:idx], arg[idx+1:])
} else {
args = append(args, arg)
}
}

if len(args) < 2 {
if isWindowsTarget() {
args = append(args, filepath.Join("bin", "vc.exe"))
} else {
args = append(args, "bin/vc")
}
}

self = filepath.Base(args[0])
if self == "build" {
self = "build.go"
}

for _, task := range args[1:] {
t := tasks[normalizeTask(task)]
if t == nil {
fmt.Fprintf(os.Stderr, "Don't know how to build task `%s`.\n", task)
os.Exit(1)
}

err := t(task)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Fprintf(os.Stderr, "%s: building task `%s` failed.\n", self, task)
os.Exit(1)
}
}
}

func version() string {
if versionEnv := os.Getenv("VC_VERSION"); versionEnv != "" {
return versionEnv
}
if desc, err := cmdOutput("git", "describe", "--tags"); err == nil {
return desc
}
rev, _ := cmdOutput("git", "rev-parse", "--short", "HEAD")
return rev
}

func date() string {
t := time.Now()
if sourceDate := os.Getenv("SOURCE_DATE_EPOCH"); sourceDate != "" {
if sec, err := strconv.ParseInt(sourceDate, 10, 64); err == nil {
t = time.Unix(sec, 0)
}
}
return t.Format("2006-01-02")
}

func cmdOutput(args ...string) (string, error) {
exe, err := exec.LookPath(args[0])
if err != nil {
return "", err
}
cmd := exec.Command(exe, args[1:]...)
cmd.Stderr = io.Discard
out, err := cmd.Output()
return strings.TrimSuffix(string(out), "\n"), err
}

func run(args ...string) error {
exe, err := exec.LookPath(args[0])
if err != nil {
return err
}
announce(args...)
cmd := exec.Command(exe, args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}

func rmrf(targets ...string) error {
args := append([]string{"rm", "-rf"}, targets...)
announce(args...)
for _, target := range targets {
if err := os.RemoveAll(target); err != nil {
return err
}
}
return nil
}

func announce(args ...string) {
fmt.Println(shellInspect(args))
}

func shellInspect(args []string) string {
fmtArgs := make([]string, len(args))
for i, arg := range args {
if strings.ContainsAny(arg, " \t'\"") {
fmtArgs[i] = fmt.Sprintf("%q", arg)
} else {
fmtArgs[i] = arg
}
}
return strings.Join(fmtArgs, " ")
}

func normalizeTask(t string) string {
return filepath.ToSlash(strings.TrimSuffix(t, ".exe"))
}

func isWindowsTarget() bool {
if os.Getenv("GOOS") == "windows" {
return true
}
if runtime.GOOS == "windows" {
return true
}
return false
}

0 comments on commit f1f4fcb

Please sign in to comment.