Skip to content

Commit

Permalink
cmd: Fix exiting with custom status code, add caddy -v (#5874)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
francislavoie and mohammed90 authored Oct 11, 2023
1 parent b245ecd commit 9c419f1
Show file tree
Hide file tree
Showing 5 changed files with 164 additions and 106 deletions.
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

0 comments on commit 9c419f1

Please sign in to comment.