-
Notifications
You must be signed in to change notification settings - Fork 90
/
main.go
96 lines (79 loc) · 1.72 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// gen is a tool for type-driven code generation for Go. Details and docs are available at https://clipperhouse.github.io/gen.
package main
import (
"fmt"
"os"
"regexp"
)
func main() {
var err error
defer func() {
if err != nil {
if !exitStatusMsg.MatchString(err.Error()) {
os.Stderr.WriteString(err.Error() + "\n")
}
os.Exit(1)
}
}()
err = runMain(os.Args)
}
var exitStatusMsg = regexp.MustCompile("^exit status \\d+$")
func runMain(args []string) error {
c := defaultConfig
cmd, force, tail, err := parseArgs(args)
if err != nil {
return err
}
c.IgnoreTypeCheckErrors = force
if len(cmd) == 0 {
// simply typed 'gen'; run is the default command
return run(c)
}
switch cmd {
case "add":
return add(c, tail...)
case "get":
return get(c, tail...)
case "list":
return list(c)
case "watch":
return watch(c)
default:
return help(c)
}
}
var s = struct{}{}
var cmds = map[string]struct{}{
"add": s,
"get": s,
"help": s,
"list": s,
"watch": s,
}
func parseArgs(args []string) (cmd string, force bool, tail []string, err error) {
for _, a := range args[1:] { // arg[0] is 'gen'
if _, ok := cmds[a]; ok {
if len(cmd) > 0 {
err = fmt.Errorf("more than one command specified; type gen help for usage")
break
}
cmd = a
continue
}
if a == "-f" {
force = true
continue
}
tail = append(tail, a)
}
// tail is only valid on add & get; otherwise an error
if len(tail) > 0 && cmd != "add" && cmd != "get" {
err = fmt.Errorf("unknown command(s) %v", tail)
tail = []string{}
}
// force flag is only valid with run & watch
if force && cmd != "" && cmd != "watch" {
err = fmt.Errorf("-f flag is not valid with %q", cmd)
}
return cmd, force, tail, err
}