-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
126 lines (115 loc) · 2.55 KB
/
app.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package app
import (
"bytes"
"flag"
"fmt"
"io"
"os"
"text/template"
"github.com/herb-go/util"
)
var HelpModuleCmd = "help"
type ApplicationConfig struct {
Name string
Cmd string
Version string
IntroTemplate string
}
type Application struct {
Config *ApplicationConfig
Args []string
Env AppEnv
Cwd string
Modules *Modules
Stdout io.Writer
Stdin io.Reader
FlagDefaults string
HelpModuleCmd string
}
func (a *Application) ShowIntro() error {
t, err := template.New("intro").Parse(a.Config.IntroTemplate)
if err != nil {
return err
}
buf := bytes.NewBuffer([]byte{})
err = t.Execute(buf, a)
if err != nil {
return err
}
_, err = a.Println(buf.String())
return err
}
func (a *Application) Print(args ...interface{}) (n int, err error) {
return fmt.Fprint(a.Stdout, args...)
}
func (a *Application) Println(args ...interface{}) (n int, err error) {
return fmt.Fprintln(a.Stdout, args...)
}
func (a *Application) Printf(format string, args ...interface{}) (n int, err error) {
return fmt.Fprintf(a.Stdout, format, args...)
}
func (a *Application) Getenv(key string) string {
return a.Env.Getenv(key)
}
func (a *Application) appendFlagDefaults(flgs *flag.FlagSet) {
output := bytes.NewBuffer(nil)
flgs.SetOutput(output)
flgs.PrintDefaults()
a.FlagDefaults += output.String()
}
func (a *Application) PrintModuleHelp(m Module) {
a.FlagDefaults = ""
a.ShowIntro()
a.Print(m.Help(a))
a.appendFlagDefaults(m.FlagSet())
if a.FlagDefaults != "" {
a.Println("Options:")
a.Println(a.FlagDefaults)
}
}
func (a *Application) Setenv(key string, value string) error {
return a.Env.Setenv(key, value)
}
func (a *Application) Run() {
var cmd string
var args []string
var err error
if len(a.Args) < 2 {
err = a.ShowIntro()
if err == nil {
a.Printf("Type \"%s %s\" to get help.\n", a.Config.Cmd, HelpModuleCmd)
}
} else {
cmd = a.Args[1]
args = a.Args[2:]
m := a.Modules.Get(cmd)
if m == nil {
m = a.Modules.Get(HelpModuleCmd)
args=[]string{}
}
err = m.Exec(a, args)
}
if err != nil {
util.Println("Error: " + err.Error())
}
}
func NewApplication(config *ApplicationConfig) *Application {
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
return &Application{
Config: config,
Cwd: cwd,
Modules: NewModules(),
Stdout: os.Stdout,
Stdin: os.Stdin,
Env: OsEnv,
HelpModuleCmd: HelpModuleCmd,
}
}
func NewApplicationConfig() *ApplicationConfig {
return &ApplicationConfig{}
}
func init() {
}