-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
79 lines (69 loc) · 1.59 KB
/
main.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
package main
import (
"flag"
"fmt"
"github.com/aurelien-rainone/gotypes"
"io/ioutil"
"log"
"os"
)
var (
typename = flag.String("type", "", "type name to inspect; must be set")
outname = flag.String("out", "", "name of the generated file; if empty the eventually not correct output is printed on standard output")
filename string
)
func showUsage() {
fmt.Println("gencli - Automatically generate command-line interface for Surviveler")
fmt.Println()
fmt.Println("usage:")
fmt.Println(" gencli -type string -out string inputfile")
fmt.Println()
fmt.Println("options:")
fmt.Println(" inputfile")
fmt.Println(" go input file; must not be set if called from `go generate`")
flag.PrintDefaults()
}
func main() {
log.SetFlags(0)
log.SetPrefix("gencli: ")
flag.Usage = showUsage
flag.Parse()
if *typename == "" {
flag.Usage()
os.Exit(1)
}
file := ""
if flag.NArg() > 0 {
file = flag.Arg(0)
} else {
file = os.Getenv("GOFILE")
}
tdef, err := gotypes.Inspect(*typename, file)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, f := range tdef.Fields {
// add 'CliFlag' to the 'Meta' container
f.Meta["CliFlag"] = cliFlagFromType(f.Type)
}
buf := gotypes.Generate(CliTemplate, tdef, *outname == "")
if *outname != "" {
// generate output filename
err = ioutil.WriteFile(*outname, buf, 0644)
if err != nil {
log.Fatalf("writing output: %s", err)
}
}
}
func cliFlagFromType(t string) string {
switch t {
case "string":
return "StringFlag"
case "int":
return "IntFlag"
default:
log.Fatalf("unsupported struct field type: %s\n", t)
return ""
}
}