Skip to content

Commit

Permalink
cmd/root: fix setting log level
Browse files Browse the repository at this point in the history
Parsing the command line this early in the code won't account for the
subcommands flags, causing the parse to fail. Since later in the code we
already check for the parsing errors considering the subcommands, we can
ignore the parse error for setting the log level in the initialization
code, thus even if some flags are wrong the debug level can be used.

Signed-off-by: Bruno Meneguele <[email protected]>
  • Loading branch information
bmeneg committed Feb 2, 2022
1 parent 32a1bd3 commit 6211a8a
Showing 1 changed file with 12 additions and 14 deletions.
26 changes: 12 additions & 14 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,20 +116,18 @@ func init() {

// We need to set the logger level before any other piece of code is
// called, thus we make sure we don't lose any debug message, but for
// that we need to parse the args from command input.
err := RootCmd.ParseFlags(os.Args[1:])
// Handle the err != nil case later
if err == nil {
debugLogger, _ := RootCmd.Flags().GetBool("debug")
quietLogger, _ := RootCmd.Flags().GetBool("quiet")
if debugLogger && quietLogger {
log.Fatal("option --debug cannot be combined with --quiet")
}
if debugLogger {
log.SetLogLevel(logger.LogLevelDebug)
} else if quietLogger {
log.SetLogLevel(logger.LogLevelNone)
}
// that we need to parse the args from command input and let flag errors be
// handled by the subcommands themselves.
_ = RootCmd.ParseFlags(os.Args[1:])
debugLogger, _ := RootCmd.Flags().GetBool("debug")
quietLogger, _ := RootCmd.Flags().GetBool("quiet")
if debugLogger && quietLogger {
log.Fatal("option --debug cannot be combined with --quiet")
}
if debugLogger {
log.SetLogLevel(logger.LogLevelDebug)
} else if quietLogger {
log.SetLogLevel(logger.LogLevelNone)
}
carapace.Gen(RootCmd)
}
Expand Down

0 comments on commit 6211a8a

Please sign in to comment.