forked from ulikunitz/xz
/
version-file.go
85 lines (68 loc) · 1.71 KB
/
version-file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2014-2021 Ulrich Kunitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"text/template"
)
const vfUsage = `xb version-file [options] <id>:<path>...
The command creates go file with a version constant. The version string
contains the contents of the VERSION environment variable or the output
of git describe.
-h prints this message and exits
-p package name (default main)
-o file name of output
`
func versionFileUsage(w io.Writer) {
fmt.Fprint(w, vfUsage)
}
func versionFile() {
cmdName := filepath.Base(os.Args[0])
log.SetPrefix(fmt.Sprintf("%s: ", cmdName))
log.SetFlags(0)
flag.CommandLine = flag.NewFlagSet(cmdName, flag.ExitOnError)
flag.Usage = func() { versionFileUsage(os.Stderr); os.Exit(1) }
help := flag.Bool("h", false, "")
pkg := flag.String("p", "main", "")
out := flag.String("o", "", "")
flag.Parse()
if *help {
versionFileUsage(os.Stdout)
os.Exit(0)
}
if *pkg == "" {
log.Fatal("option -p must not be empty")
}
var err error
w := os.Stdout
if *out != "" {
if w, err = os.Create(*out); err != nil {
log.Fatal(err)
}
}
// get the version string
version := os.Getenv("VERSION")
if version == "" {
b, err := exec.Command("git", "describe").Output()
if err != nil {
log.Fatalf("error %s while executing git describe", err)
}
version = string(b)
}
version = strings.TrimSpace(version)
versionTmpl := `package main
const version = "{{.}}"
`
tmpl := template.Must(template.New("version").Parse(versionTmpl))
if err = tmpl.Execute(w, version); err != nil {
log.Fatal(err)
}
}