-
Notifications
You must be signed in to change notification settings - Fork 13
/
init.go
231 lines (201 loc) · 6.29 KB
/
init.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package main
import (
"context"
"encoding/json"
"regexp"
"github.com/qingstor/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/qingstor/qsctl/v2/constants"
"github.com/qingstor/qsctl/v2/internal/pkg/ilog"
"github.com/qingstor/qsctl/v2/pkg/i18n"
"github.com/qingstor/qsctl/v2/utils"
)
//go:generate go run ../../internal/cmd/generator/i18nextract
//go:generate go run ../../internal/cmd/generator/i18ngenerator
var globalFlag = globalFlags{}
// register available flag vars here
type globalFlags struct {
// bench will be set if bench flag was set
bench bool
// configPath will be set if config flag was set
configPath string
debug bool
// zone will be set if zone flag was set
zone string
}
// multipartFlags embedded in flags which call multipart upload
type multipartFlags struct {
partThresholdStr string
partThreshold int64
partSizeStr string
partSize int64
}
// inExcludeFlags embedded in flags which use include and exclude regexps
type inExcludeFlags struct {
includeRegxStr string
includeRegx *regexp.Regexp
excludeRegxStr string
excludeRegx *regexp.Regexp
}
// rootCmd is the main command of qsctl
var rootCmd = &cobra.Command{
Use: constants.Name,
Long: constants.Description,
Version: constants.Version,
}
func init() {
initGlobalFlag()
// init flags for every single cmd
initCpFlag()
initLsFlag()
initMbFlag()
initMvFlag()
initPresignFlag()
initRbFlag()
initRmFlag()
initStatFlag()
initSyncFlag()
initTeeFlag()
// init config before command run
rootCmd.PersistentPreRunE = func(c *cobra.Command, args []string) error {
logger := ilog.InitLoggerWithDebug(globalFlag.debug)
ctx := log.ContextWithLogger(c.Context(), logger)
c.SetContext(ctx)
return initConfig(ctx)
}
rootCmd.AddCommand(ShellCommand)
// add sub-command to rootCmd
rootCmd.AddCommand(CatCommand)
rootCmd.AddCommand(CpCommand)
rootCmd.AddCommand(LsCommand)
rootCmd.AddCommand(MbCommand)
rootCmd.AddCommand(MvCommand)
rootCmd.AddCommand(PresignCommand)
rootCmd.AddCommand(RbCommand)
rootCmd.AddCommand(RmCommand)
rootCmd.AddCommand(StatCommand)
rootCmd.AddCommand(SyncCommand)
rootCmd.AddCommand(TeeCommand)
rootCmd.SetVersionTemplate(i18n.Sprintf(constants.VersionTemplate))
rootCmd.SetUsageTemplate(i18n.Sprintf(constants.UsageTemplate))
rootCmd.SetHelpTemplate(i18n.Sprintf(constants.HelpTemplate))
}
func initConfig(ctx context.Context) (err error) {
logger := log.FromContext(ctx)
// Allow viper read from env.
viper.SetEnvPrefix("qsctl")
viper.AutomaticEnv()
// Set default value for config.
viper.SetDefault(constants.ConfigHost, constants.DefaultHost)
viper.SetDefault(constants.ConfigPort, constants.DefaultPort)
viper.SetDefault(constants.ConfigProtocol, constants.DefaultProtocol)
viper.SetDefault(constants.ConfigEnableVirtualStyle, constants.DefaultEnableVirtualStyle)
// Load config from config file.
if globalFlag.configPath != "" {
// Use config file from the flag.
viper.SetConfigFile(globalFlag.configPath)
} else {
// Search config in home directory with name ".qingstor" (without extension).
viper.AddConfigPath("$HOME/.qingstor")
// Search config in XDG style.
viper.AddConfigPath("$HOME/.config/qingstor")
// Read from "/etc/qingstor" instead if not found.
viper.AddConfigPath("/etc/qingstor")
viper.SetConfigName("config")
}
// if zone flag was set, overwrite the config
if globalFlag.zone != "" {
viper.Set(constants.ConfigZone, globalFlag.zone)
}
// try to read config from path set above
err = viper.ReadInConfig()
if err == nil {
content, _ := json.Marshal(viper.AllSettings())
logger.Debug(
log.String("action", "load config success"),
log.String("config_path", viper.ConfigFileUsed()),
log.Bytes("content", content),
)
return nil
}
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
i18n.Printf("Load config failed [%v]", err)
return err
}
// if env set, get config from env
if configuredByEnv() {
i18n.Printf("Config not loaded, use default and environment value instead.")
logger.Debug(
log.String("action", "load config from env"),
)
return nil
}
return
}
func initGlobalFlag() {
// Add config flag which can be used in all sub commands.
rootCmd.PersistentFlags().StringVarP(&globalFlag.configPath, "config", "c",
"", i18n.Sprintf("assign config path manually"))
// Add zone flag which can be used in all sub commands.
rootCmd.PersistentFlags().StringVarP(&globalFlag.zone, constants.ZoneFlag, "z",
"", i18n.Sprintf("in which zone to do the operation"))
// Add config flag which can be used in all sub commands.
rootCmd.PersistentFlags().BoolVar(&globalFlag.bench, constants.BenchFlag,
false, i18n.Sprintf("enable benchmark or not"))
// Overwrite the default help flag to free -h shorthand.
rootCmd.PersistentFlags().Bool("help", false, i18n.Sprintf("help for this command"))
rootCmd.PersistentFlags().BoolVar(&globalFlag.debug, "debug", false, i18n.Sprintf("print logs for debug"))
}
func silenceUsage(c *cobra.Command) {
c.SilenceUsage = true
}
// configuredByEnv returns true if either ak or sk set
func configuredByEnv() bool {
return viper.GetString(constants.ConfigAccessKeyID) != "" &&
viper.GetString(constants.ConfigSecretAccessKey) != ""
}
// resetGlobalFlags used to reset global flags before each sub-command run in shell,
// to avoid flags from last call is still working
func resetGlobalFlags() {
globalFlag = globalFlags{}
}
// parse multipart flags
func (f *multipartFlags) parse() (err error) {
// parse multipart chunk size
if f.partSizeStr != "" {
// do not set chunk size default value, we need to check it when task init
f.partSize, err = utils.ParseByteSize(f.partSizeStr)
if err != nil {
return err
}
}
// parse multipart partThreshold
if f.partThresholdStr == "" {
f.partThreshold = constants.MaximumAutoMultipartSize
} else {
f.partThreshold, err = utils.ParseByteSize(f.partThresholdStr)
if err != nil {
return err
}
}
return nil
}
// parse include and exclude flags
func (f *inExcludeFlags) parse() (err error) {
// parse exclude regexp
if f.excludeRegxStr != "" {
f.excludeRegx, err = regexp.Compile(f.excludeRegxStr)
if err != nil {
return err
}
}
// parse include regexp
if f.includeRegxStr != "" {
f.includeRegx, err = regexp.Compile(f.includeRegxStr)
if err != nil {
return err
}
}
return nil
}