diff options
author | Francis Lavoie <lavofr@gmail.com> | 2023-10-11 11:46:18 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-10-11 09:46:18 -0600 |
commit | 9c419f1e1a4a82a8ed49bac3d54050890cb3e58e (patch) | |
tree | d2ddc1499646eb0aa9dbf95a7f757a8df5d4a623 /cmd/cobra.go | |
parent | b245ecd325428966ac4e4c208e268967d0e0cb83 (diff) |
cmd: Fix exiting with custom status code, add `caddy -v` (#5874)
* Simplify variables for commands
* Add --envfile support for adapt command
* Carry custom status code for commands to os.Exit()
* cmd: add `-v` and `--version` to root caddy command
* Add `--envfile` to `caddy environ`, extract flag parsing to func
---------
Co-authored-by: Mohammed Al Sahaf <msaa1990@gmail.com>
Diffstat (limited to 'cmd/cobra.go')
-rw-r--r-- | cmd/cobra.go | 30 |
1 files changed, 29 insertions, 1 deletions
diff --git a/cmd/cobra.go b/cmd/cobra.go index 4339cdb..c071f4a 100644 --- a/cmd/cobra.go +++ b/cmd/cobra.go @@ -1,7 +1,11 @@ package caddycmd import ( + "fmt" + "github.com/spf13/cobra" + + "github.com/caddyserver/caddy/v2" ) var rootCmd = &cobra.Command{ @@ -95,15 +99,22 @@ https://caddyserver.com/docs/running // kind of annoying to have all the help text printed out if // caddy has an error provisioning its modules, for instance... SilenceUsage: true, + Version: onlyVersionText(), } const fullDocsFooter = `Full documentation is available at: https://caddyserver.com/docs/command-line` func init() { + rootCmd.SetVersionTemplate("{{.Version}}") rootCmd.SetHelpTemplate(rootCmd.HelpTemplate() + "\n" + fullDocsFooter + "\n") } +func onlyVersionText() string { + _, f := caddy.Version() + return f +} + func caddyCmdToCobra(caddyCmd Command) *cobra.Command { cmd := &cobra.Command{ Use: caddyCmd.Name, @@ -123,7 +134,24 @@ func caddyCmdToCobra(caddyCmd Command) *cobra.Command { // in a cobra command's RunE field. func WrapCommandFuncForCobra(f CommandFunc) func(cmd *cobra.Command, _ []string) error { return func(cmd *cobra.Command, _ []string) error { - _, err := f(Flags{cmd.Flags()}) + status, err := f(Flags{cmd.Flags()}) + if status > 1 { + cmd.SilenceErrors = true + return &exitError{ExitCode: status, Err: err} + } return err } } + +// exitError carries the exit code from CommandFunc to Main() +type exitError struct { + ExitCode int + Err error +} + +func (e *exitError) Error() string { + if e.Err == nil { + return fmt.Sprintf("exiting with status %d", e.ExitCode) + } + return e.Err.Error() +} |