summaryrefslogtreecommitdiff
path: root/compflag/gen/main.go
blob: cbea96ff63dc75a58bc87a37397abe6371511475 (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
// Generates flags.go.
package main

import (
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"

	"github.com/posener/script"
)

const tmplGlob = "gen/*.go.gotmpl"

type flag struct {
	Name          string
	Type          string
	IsBool        bool
	CustomPredict bool
}

func (f flag) NewInternalTypeFuncName() string {
	return "new" + strings.Title(f.InternalTypeName())
}

func (f flag) InternalTypeName() string {
	return strings.ToLower(f.Name[:1]) + f.Name[1:] + "Value"
}

var flags = []flag{
	{Name: "String", Type: "string"},
	{Name: "Bool", Type: "bool", IsBool: true, CustomPredict: true},
	{Name: "Int", Type: "int"},
	{Name: "Duration", Type: "time.Duration"},
}

var tmpl = template.Must(template.ParseGlob(tmplGlob))

func main() {
	for _, t := range tmpl.Templates() {
		fileName := outFileName(t.Name())
		f, err := os.Create(fileName)
		if err != nil {
			panic(err)
		}
		defer f.Close()

		log.Printf("Writing %s", fileName)
		err = t.Execute(f, flags)
		if err != nil {
			panic(err)
		}

		// Format the file.
		err = script.ExecHandleStderr(os.Stderr, "goimports", "-w", fileName).ToStdout()
		if err != nil {
			panic(err)
		}
	}
}

func outFileName(templateName string) string {
	name := filepath.Base(templateName)
	// Remove .gotmpl suffix.
	return name[:strings.LastIndex(name, ".")]
}