-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
204 lines (171 loc) · 4.59 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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package app
import (
"fmt"
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/yonymo/simplechat/pkg/common/cli/flag"
"github.com/yonymo/simplechat/pkg/common/cli/globalflag"
"github.com/yonymo/simplechat/pkg/common/term"
"github.com/yonymo/simplechat/pkg/errors"
"github.com/yonymo/simplechat/pkg/log"
"os"
)
var (
progressMessage = color.GreenString("==>")
)
type APP struct {
basename string
name string
description string
commands []*Command
args cobra.PositionalArgs
options CliOptions
runFunc RunFunc
cmd *cobra.Command
noConfig bool
silence bool
}
// Option defines optional parameters for initializing the application
// structure.
type Option func(*APP)
// WithOptions to open the application's function to read from the command line
// or read parameters from the configuration file.
func WithOptions(opt CliOptions) Option {
return func(a *APP) {
a.options = opt
}
}
// RunFunc defines the application's startup callback function.
type RunFunc func(basename string) error
// WithRunFunc is used to set the application startup callback function option.
func WithRunFunc(run RunFunc) Option {
return func(a *APP) {
a.runFunc = run
}
}
func WithNoConfig() Option {
return func(a *APP) {
a.noConfig = true
}
}
func (a *APP) buildCommand() {
cmd := cobra.Command{
Use: FormatBaseName(a.basename),
Short: a.name,
Long: a.description,
// stop printing usage when the command errors
SilenceUsage: true,
SilenceErrors: true,
Args: a.args,
}
// cmd.SetUsageTemplate(usageTemplate)
cmd.SetOut(os.Stdout)
cmd.SetErr(os.Stderr)
cmd.Flags().SortFlags = true
flag.InitFlags(cmd.Flags())
if len(a.commands) > 0 {
for _, command := range a.commands {
cmd.AddCommand(command.cobraCommand())
}
cmd.SetHelpCommand(helpCommand(FormatBaseName(a.basename)))
}
if a.runFunc != nil {
cmd.RunE = a.runCommand
}
var namedFlagSets flag.NamedFlagSets
if a.options != nil {
namedFlagSets = a.options.Flags()
fs := cmd.Flags()
for _, f := range namedFlagSets.FlagSets {
fs.AddFlagSet(f)
}
}
if !a.noConfig {
addConfigFlag(a.basename, namedFlagSets.FlagSet("global"))
}
globalflag.AddGlobalFlags(namedFlagSets.FlagSet("global"), cmd.Name())
// add new global flagset to cmd FlagSet
cmd.Flags().AddFlagSet(namedFlagSets.FlagSet("global"))
addCmdTemplate(&cmd, namedFlagSets)
a.cmd = &cmd
}
func (a *APP) runCommand(cmd *cobra.Command, args []string) error {
printWorkingDir()
flag.PrintFlags(cmd.Flags())
if !a.noConfig {
if err := viper.BindPFlags(cmd.Flags()); err != nil {
return err
}
if err := viper.Unmarshal(a.options); err != nil {
return err
}
}
if !a.silence {
log.Infof("%v Starting %s ...", progressMessage, a.name)
if !a.noConfig {
log.Infof("%v Config file used: `%s`", progressMessage, viper.ConfigFileUsed())
}
}
if a.options != nil {
if err := a.applyOptionRules(); err != nil {
return err
}
}
// run application
if a.runFunc != nil {
return a.runFunc(a.basename)
}
return nil
}
func (a *APP) applyOptionRules() error {
if completeableOptions, ok := a.options.(CompleteableOptions); ok {
if err := completeableOptions.Complete(); err != nil {
return err
}
}
if errs := a.options.Validate(); len(errs) != 0 {
return errors.NewAggregate(errs)
}
if printableOptions, ok := a.options.(PrintableOptions); ok && !a.silence {
log.Infof("%v Config: `%s`", progressMessage, printableOptions.String())
}
return nil
}
func printWorkingDir() {
wd, _ := os.Getwd()
log.Infof("%v WorkingDir: %s", progressMessage, wd)
}
func addCmdTemplate(cmd *cobra.Command, namedFlagSets flag.NamedFlagSets) {
usageFmt := "Usage:\n %s\n"
cols, _, _ := term.TerminalSize(cmd.OutOrStdout())
cmd.SetUsageFunc(func(cmd *cobra.Command) error {
fmt.Fprintf(cmd.OutOrStderr(), usageFmt, cmd.UseLine())
flag.PrintSections(cmd.OutOrStderr(), namedFlagSets, cols)
return nil
})
cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
fmt.Fprintf(cmd.OutOrStdout(), "%s\n\n"+usageFmt, cmd.Long, cmd.UseLine())
flag.PrintSections(cmd.OutOrStdout(), namedFlagSets, cols)
})
}
// NewApp creates a new application instance based on the given application name,
// binary name, and other options.
func NewApp(name string, basename string, opts ...Option) *APP {
a := &APP{
name: name,
basename: basename,
}
for _, o := range opts {
o(a)
}
a.buildCommand()
return a
}
// Run is used to launch the application.
func (a *APP) Run() {
if err := a.cmd.Execute(); err != nil {
fmt.Printf("%v %v\n", color.RedString("Error:"), err)
os.Exit(1)
}
}