summaryrefslogtreecommitdiff
path: root/pkg/config/version/genver/main.go
blob: d4b72d8aee0cf74d60cd90f85aa71473ca57a3ff (plain)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main

import (
	"flag"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"text/template"
	"time"
)

var (
	flPackageName  = flag.String("package", "version", "name for the generated golang package")
	flVariableName = flag.String("variable", "VERSION", "variable name in the generated golang package")
	flOutputFile   = flag.String("output", "", "output filename (default stdout)")
)

func main() {
	flag.Parse()
	dir := "."
	if flag.NArg() > 0 {
		dir = flag.Args()[0]
	}
	dir, err := filepath.Abs(dir)
	if err != nil {
		log.Fatal(err)
	}

	var output io.Writer
	if len(*flOutputFile) > 0 {
		fh, err := os.Create(*flOutputFile)
		if err != nil {
			log.Fatal(err)
		}
		defer fh.Close()
		output = fh
	} else {
		output = os.Stdout
	}

	vers, err := GitDescribe(dir)
	if err != nil {
		vers = ReadVersionFile(dir)
	}
	vp := VersionPackage{
		Name:     *flPackageName,
		Path:     dir,
		Date:     time.Now(),
		Variable: *flVariableName,
		Version:  vers,
	}

	packageTemplate.Execute(output, vp)
}

// VersionPackage is the needed information to template a version package
type VersionPackage struct {
	Name     string
	Path     string
	Date     time.Time
	Variable string
	Version  string
}

var packageTemplate = template.Must(template.New("default").Parse(packageLayout))
var packageLayout = `package {{.Name}}
// AUTO-GENERATED. DO NOT EDIT
// {{.Date}}

// {{.Variable}} is generated by git-describe or static version file from gen.go
var {{.Variable}} = "{{.Version}}"
 `

// GitDescribe calls `git describe` in the provided path
func GitDescribe(path string) (string, error) {
	cwd, err := os.Getwd()
	if err != nil {
		return "", err
	}
	// TODO check if this is a directory
	if err := os.Chdir(path); err != nil {
		return "", err
	}
	defer os.Chdir(cwd)

	buf, err := exec.Command("git", "describe").CombinedOutput()
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(string(buf)), nil
}

func ReadVersionFile(path string) string {
	versionFile := filepath.Join(path, "../../../version")
	content, err := ioutil.ReadFile(versionFile)
	if err != nil {
		return "unknown"
	}
	return strings.Trim(string(content), "\n")
}