-
Notifications
You must be signed in to change notification settings - Fork 0
/
program.go
84 lines (63 loc) · 1.32 KB
/
program.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
package program
import (
"fmt"
"os"
)
type Main func(*Program)
type Program struct {
Name string
Description string
Main Main
command *Command
options map[string]*Option
arguments []*Argument
selectedCommand *Command
Quiet bool
DebugLevel int
}
func NewProgram(name, description string) *Program {
p := &Program{
Name: name,
Description: description,
options: make(map[string]*Option),
}
p.addDefaultOptions()
return p
}
func (p *Program) SetMain(main Main) {
if p.command != nil {
panic("cannot have a main function with commands")
}
p.Main = main
}
func (p *Program) Run() {
var main Main
if p.selectedCommand == nil {
if p.Main == nil {
panic("missing main function")
}
main = p.Main
} else {
main = p.selectedCommand.Main
}
main(p)
}
func (p *Program) Debug(level int, format string, args ...interface{}) {
if level > p.DebugLevel {
return
}
fmt.Fprintf(os.Stderr, format+"\n", args...)
}
func (p *Program) Info(format string, args ...interface{}) {
if p.Quiet {
return
}
fmt.Fprintf(os.Stderr, format+"\n", args...)
}
func (p *Program) Error(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "error: "+format+"\n", args...)
}
func (p *Program) Fatal(format string, args ...interface{}) {
p.Error(format, args...)
os.Exit(1)
}