[Enhancement] Detect configuration file (#13)
diff --git a/swctl/main.go b/swctl/main.go
index dfc5248..f260fc2 100644
--- a/swctl/main.go
+++ b/swctl/main.go
@@ -77,9 +77,9 @@
}
app.Before = interceptor.BeforeChain([]cli.BeforeFunc{
- expandConfigFile,
- altsrc.InitInputSourceWithContext(flags, altsrc.NewYamlSourceFromFlagFunc("config")),
setUpCommandLineContext,
+ expandConfigFile,
+ tryConfigFile(flags),
})
app.Flags = flags
@@ -93,19 +93,31 @@
return c.Set("config", util.ExpandFilePath(c.String("config")))
}
+func tryConfigFile(flags []cli.Flag) cli.BeforeFunc {
+ return func(c *cli.Context) error {
+ configFile := c.String("config")
+ if bytes, err := ioutil.ReadFile(configFile); err == nil {
+ log.Debug("Using configurations:\n", string(bytes))
+
+ err = altsrc.InitInputSourceWithContext(flags, altsrc.NewYamlSourceFromFlagFunc("config"))(c)
+ if err != nil {
+ return err
+ }
+ } else if os.IsNotExist(err) {
+ log.Debugf("open %s no such file, skip loading configuration file\n", c.GlobalString("config"))
+ } else {
+ return err
+ }
+
+ return nil
+ }
+}
+
func setUpCommandLineContext(c *cli.Context) error {
if c.Bool("debug") {
log.SetLevel(logrus.DebugLevel)
log.Debugln("Debug mode is enabled")
}
- configFile := c.String("config")
-
- if bytes, err := ioutil.ReadFile(configFile); err == nil {
- log.Debug("Using configurations:\n", string(bytes))
- } else {
- return err
- }
-
return nil
}