From 2c5b6093197d30644efd540aa0b8da1cab378d44 Mon Sep 17 00:00:00 2001 From: opsyne <85858658+opsyne@users.noreply.github.com> Date: Wed, 17 Aug 2022 01:13:57 -0700 Subject: [PATCH] Add a version command (#159) --- Makefile | 4 +++- flag.go | 8 ++++++++ version/version.go | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 version/version.go diff --git a/Makefile b/Makefile index 2288cb6..00dd58d 100644 --- a/Makefile +++ b/Makefile @@ -5,12 +5,14 @@ PREFIX=/usr/local BINDIR=$(PREFIX)/bin MANDIR=$(PREFIX)/share/man GO=go +TAGGED_RELEASE!=git describe --tags --abbrev=0 +LDFLAGS=-X "github.com/bouncepaw/mycorrhiza/version.taggedRelease=$(TAGGED_RELEASE)" all: mycorrhiza mycorrhiza: $(GO) generate $(GOFLAGS) - CGO_ENABLED=0 $(GO) build $(GOFLAGS) -o mycorrhiza . + CGO_ENABLED=0 $(GO) build -ldflags="$(LDFLAGS)" $(GOFLAGS) -o mycorrhiza . install: mkdir -m755 -p $(DESTDIR)$(BINDIR) $(DESTDIR)$(MANDIR)/man1 diff --git a/flag.go b/flag.go index b3dc935..05f4e1d 100644 --- a/flag.go +++ b/flag.go @@ -13,6 +13,7 @@ import ( "github.com/bouncepaw/mycorrhiza/cfg" "github.com/bouncepaw/mycorrhiza/files" "github.com/bouncepaw/mycorrhiza/user" + "github.com/bouncepaw/mycorrhiza/version" "golang.org/x/term" ) @@ -31,12 +32,19 @@ func printHelp() { // parseCliArgs parses CLI options and sets several important global variables. Call it early. func parseCliArgs() { var createAdminName string + var versionFlag bool flag.StringVar(&cfg.ListenAddr, "listen-addr", "", "Address to listen on. For example, 127.0.0.1:1737 or /run/mycorrhiza.sock.") flag.StringVar(&createAdminName, "create-admin", "", "Create a new admin. The password will be prompted in the terminal.") + flag.BoolVar(&versionFlag, "version", false, "Print version information and exit.") flag.Usage = printHelp flag.Parse() + if versionFlag { + fmt.Println(version.FormatVersion()) + os.Exit(0) + } + args := flag.Args() if len(args) == 0 { log.Fatal("error: pass a wiki directory") diff --git a/version/version.go b/version/version.go new file mode 100644 index 0000000..503ac47 --- /dev/null +++ b/version/version.go @@ -0,0 +1,32 @@ +package version + +import ( + "fmt" + "runtime/debug" + "strconv" +) + +// This is set through ldflags='-X ...' in the Makefile +var taggedRelease string = "Unknown" + +func FormatVersion() string { + var commitHash string = "Unknown" + var dirty string = "" + + info, ok := debug.ReadBuildInfo() + + if ok { + for _, setting := range info.Settings { + if setting.Key == "vcs.revision" { + commitHash = setting.Value + } else if setting.Key == "vcs.modified" { + modified, err := strconv.ParseBool(setting.Value) + if err == nil && modified { + dirty = "-dirty" + } + } + } + } + + return fmt.Sprintf("Mycorrhiza Wiki %s+%s%s", taggedRelease, commitHash[:7], dirty) +}