Skip to content
This repository has been archived by the owner on Jan 27, 2021. It is now read-only.

Commit

Permalink
Merge pull request #11 from owncloud/feature/config
Browse files Browse the repository at this point in the history
Load Config from Viper on Before hook
  • Loading branch information
refs authored Mar 18, 2020
2 parents a5dbced + c8c66c8 commit 2bcd722
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 40 deletions.
83 changes: 44 additions & 39 deletions pkg/command/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,45 +32,7 @@ func Execute() error {
Flags: flagset.RootWithConfig(cfg),

Before: func(c *cli.Context) error {
logger := NewLogger(cfg)

viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("GLAUTH")
viper.AutomaticEnv()

if c.IsSet("config-file") {
viper.SetConfigFile(c.String("config-file"))
} else {
viper.SetConfigName("glauth")

viper.AddConfigPath("/etc/ocis")
viper.AddConfigPath("$HOME/.ocis")
viper.AddConfigPath("./config")
}

if err := viper.ReadInConfig(); err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
logger.Info().
Msg("Continue without config")
case viper.UnsupportedConfigError:
logger.Fatal().
Err(err).
Msg("Unsupported config type")
default:
logger.Fatal().
Err(err).
Msg("Failed to read config")
}
}

if err := viper.Unmarshal(&cfg); err != nil {
logger.Fatal().
Err(err).
Msg("Failed to parse config")
}

return nil
return ParseConfig(c, cfg)
},

Commands: []*cli.Command{
Expand Down Expand Up @@ -101,3 +63,46 @@ func NewLogger(cfg *config.Config) log.Logger {
log.Color(cfg.Log.Color),
)
}

// ParseConfig loads glauth configuration from Viper known paths.
func ParseConfig(c *cli.Context, cfg *config.Config) error {
logger := NewLogger(cfg)

viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.SetEnvPrefix("GLAUTH")
viper.AutomaticEnv()

if c.IsSet("config-file") {
viper.SetConfigFile(c.String("config-file"))
} else {
viper.SetConfigName("glauth")

viper.AddConfigPath("/etc/ocis")
viper.AddConfigPath("$HOME/.ocis")
viper.AddConfigPath("./config")
}

if err := viper.ReadInConfig(); err != nil {
switch err.(type) {
case viper.ConfigFileNotFoundError:
logger.Info().
Msg("Continue without config")
case viper.UnsupportedConfigError:
logger.Fatal().
Err(err).
Msg("Unsupported config type")
default:
logger.Fatal().
Err(err).
Msg("Failed to read config")
}
}

if err := viper.Unmarshal(&cfg); err != nil {
logger.Fatal().
Err(err).
Msg("Failed to parse config")
}

return nil
}
2 changes: 1 addition & 1 deletion pkg/command/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func Server(cfg *config.Config) *cli.Command {

cfg.Backend.Servers = c.StringSlice("backend-server")

return nil
return ParseConfig(c, cfg)
},
Action: func(c *cli.Context) error {
logger := NewLogger(cfg)
Expand Down

0 comments on commit 2bcd722

Please sign in to comment.