goserv/vendor/git.rootprojects.org/root/go-gitver/v2/gitver.go

105 lines
2.0 KiB
Go
Raw Normal View History

2020-10-12 21:29:25 +00:00
//go:generate go run -mod=vendor git.rootprojects.org/root/go-gitver/v2
2020-10-11 00:03:26 +00:00
package main
import (
"bytes"
"fmt"
"go/format"
"os"
"text/template"
"time"
2020-10-12 21:29:25 +00:00
"git.rootprojects.org/root/go-gitver/v2/gitver"
2020-10-11 00:03:26 +00:00
)
var commit, version, date string
var exitCode int
var verFile = "xversion.go"
func main() {
pkg := "main"
args := os.Args[1:]
for i := range args {
arg := args[i]
if "-f" == arg || "--fail" == arg {
exitCode = 1
} else if ("--outfile" == arg || "-o" == arg) && len(args) > i+1 {
verFile = args[i+1]
args[i+1] = ""
} else if "--package" == arg && len(args) > i+1 {
pkg = args[i+1]
args[i+1] = ""
} else if "-V" == arg || "version" == arg || "-version" == arg || "--version" == arg {
fmt.Println(commit)
fmt.Println(version)
fmt.Println(date)
os.Exit(0)
}
}
if "" != os.Getenv("GITVER_FAIL") && "false" != os.Getenv("GITVER_FAIL") {
exitCode = 1
}
v, err := gitver.ExecAndParse()
if nil != err {
fmt.Fprintf(os.Stderr, "Failed to get git version: %s\n", err)
if exitCode > 0 {
os.Exit(exitCode)
}
v = &gitver.Versions{
Timestamp: time.Now(),
}
}
// Create or overwrite the go file from template
var buf bytes.Buffer
if err := versionTpl.Execute(&buf, struct {
Package string
Timestamp string
Version string
Commit string
}{
Package: pkg,
Timestamp: v.Timestamp.Format(time.RFC3339),
Version: v.Version,
Commit: v.Rev,
}); nil != err {
panic(err)
}
// Format
src, err := format.Source(buf.Bytes())
if nil != err {
panic(err)
}
// Write to disk (in the Current Working Directory)
f, err := os.Create(verFile)
if nil != err {
panic(err)
}
if _, err := f.Write(src); nil != err {
panic(err)
}
if err := f.Close(); nil != err {
panic(err)
}
}
var versionTpl = template.Must(template.New("").Parse(`// Code generated by go generate; DO NOT EDIT.
package {{ .Package }}
func init() {
{{ if .Commit -}}
commit = "{{ .Commit }}"
{{ end -}}
{{ if .Version -}}
version = "{{ .Version }}"
{{ end -}}
date = "{{ .Timestamp }}"
}
`))