Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd: Fix exiting with custom status code, add caddy -v #5874

Merged
merged 5 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Caddyfile.*
cmd/caddy/caddy
cmd/caddy/caddy.exe
cmd/caddy/tmp/*.exe
cmd/caddy/.env

# mac specific
.DS_Store
Expand Down
30 changes: 29 additions & 1 deletion cmd/cobra.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package caddycmd

import (
"fmt"

"github.com/spf13/cobra"

"github.com/caddyserver/caddy/v2"
)

var rootCmd = &cobra.Command{
Expand Down Expand Up @@ -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,
Expand All @@ -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()
}
Loading