From fbf0aa3b4f6d86f0ef9da51ee60ef0bf5656d5e7 Mon Sep 17 00:00:00 2001 From: Arsen Musayelyan Date: Tue, 29 Nov 2022 13:49:26 -0800 Subject: [PATCH] Add git-version helper command --- docs/build-scripts.md | 17 +++++++++++++++++ helpers.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/docs/build-scripts.md b/docs/build-scripts.md index da880fa..eb2b931 100644 --- a/docs/build-scripts.md +++ b/docs/build-scripts.md @@ -465,4 +465,21 @@ Examples: ```bash install-library ./${name}/build/libadldap.so +``` + +### git-version + +`git-version` returns a version number based on the git revision of a repository. + +If an argument is provided, it will be used as the path to the repo. Otherwise, the current directory will be used. + +The version number will be the amount of revisions, a dot, and the short hash of the current revision. For example: `118.e4b8348`. + +The AUR's convention includes an `r` at the beginning of the version number. This is ommitted because some distros expect the version number to start with a digit. + +Examples: + +```bash +git-version +git-version "$srcdir/itd" ``` \ No newline at end of file diff --git a/helpers.go b/helpers.go index 372db6c..47584a5 100644 --- a/helpers.go +++ b/helpers.go @@ -10,6 +10,8 @@ import ( "strings" "unsafe" + "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/plumbing/object" "go.arsenm.dev/lure/internal/shutils" "golang.org/x/exp/slices" "mvdan.cc/sh/v3/interp" @@ -30,6 +32,7 @@ var helpers = shutils.ExecFuncs{ "install-manual": installManualCmd, "install-completion": installCompletionCmd, "install-library": installLibraryCmd, + "git-version": gitVersionCmd, } func installHelperCmd(prefix string, perms os.FileMode) shutils.ExecFunc { @@ -189,6 +192,40 @@ func getLibPrefix(hc interp.HandlerContext) string { return out } +func gitVersionCmd(hc interp.HandlerContext, cmd string, args []string) error { + path := hc.Dir + if len(args) > 0 { + path = resolvePath(hc, args[0]) + } + + r, err := git.PlainOpen(path) + if err != nil { + return fmt.Errorf("git-version: %w", err) + } + + revNum := 0 + commits, err := r.Log(&git.LogOptions{}) + if err != nil { + return fmt.Errorf("git-version: %w", err) + } + + commits.ForEach(func(*object.Commit) error { + revNum++ + return nil + }) + + HEAD, err := r.Head() + if err != nil { + return fmt.Errorf("git-version: %w", err) + } + + hash := HEAD.Hash().String() + + fmt.Fprintf(hc.Stdout, "%d.%s", revNum, hash[:7]) + + return nil +} + func helperInstall(from, to string, perms os.FileMode) error { err := os.MkdirAll(filepath.Dir(to), 0o755) if err != nil {