Skip to content

Instantly share code, notes, and snippets.

@eugene-babichenko
Created September 28, 2019 13:33
Show Gist options
  • Save eugene-babichenko/f37d15626160914427563dff2edd57ed to your computer and use it in GitHub Desktop.
Save eugene-babichenko/f37d15626160914427563dff2edd57ed to your computer and use it in GitHub Desktop.
Makefile for building version strings from Git data and including that version numbers into go programs
package main
import (
// ...
)
var version = "dev"
func main() {
// ...
}
TAG_COMMIT := $(shell git rev-list --abbrev-commit --tags --max-count=1)
TAG := $(shell git describe --abbrev=0 --tags ${TAG_COMMIT} 2>/dev/null || true)
COMMIT := $(shell git rev-parse --short HEAD)
DATE := $(shell git log -1 --format=%cd --date=format:"%Y%m%d")
VERSION := $(TAG:v%=%)
ifneq ($(COMMIT), $(TAG_COMMIT))
VERSION := $(VERSION)-next-$(COMMIT)-$(DATE)
endif
ifeq $(VERSION,)
VERSION := $(COMMIT)-$(DATA)
endif
ifneq ($(shell git status --porcelain),)
VERSION := $(VERSION)-dirty
endif
FLAGS := -ldflags "-X main.version=$(VERSION)"
build:
go build $(FLAGS) -o projectname-$(VERSION) main.go
run:
go run $(FLAGS) main.go
install:
go install $(FLAGS)
@chenyanchen
Copy link

make build
Makefile:9: *** invalid syntax in conditional.  Stop.

The 9 line should be change to

ifeq ($(VERSION),)

@KlfJoat
Copy link

KlfJoat commented Feb 2, 2024

And line 10 should be changed to

	VERSION := $(COMMIT)-$(DATE)

("DATE", not "DATA")

@KlfJoat
Copy link

KlfJoat commented Feb 2, 2024

Also, when run on a repo that truly has no tags, $(COMMIT)-$(DATE) is not what VERSION gets set to. It gets set to -next-$(COMMIT)-$(DATE).

To do as designed in the blog post, lines 9&10 should be changed to

ifeq ($(TAG_COMMIT),)
	VERSION := $(COMMIT)-$(DATE)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment