1
Fork 0
mirror of https://github.com/caddyserver/caddy.git synced 2024-12-16 21:56:40 -05:00

cmd: Use a factory to create the caddy root command (#6533)

Co-authored-by: Francis Lavoie <lavofr@gmail.com>
This commit is contained in:
a 2024-08-21 22:29:42 -05:00 committed by GitHub
parent 2bb2ecc549
commit 8ccfedf2bb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 96 additions and 60 deletions

View file

@ -8,7 +8,8 @@ import (
"github.com/caddyserver/caddy/v2"
)
var rootCmd = &cobra.Command{
var defaultFactory = newRootCommandFactory(func() *cobra.Command {
return &cobra.Command{
Use: "caddy",
Long: `Caddy is an extensible server platform written in Go.
@ -101,13 +102,16 @@ https://caddyserver.com/docs/running
SilenceUsage: true,
Version: onlyVersionText(),
}
})
const fullDocsFooter = `Full documentation is available at:
https://caddyserver.com/docs/command-line`
func init() {
defaultFactory.Use(func(rootCmd *cobra.Command) {
rootCmd.SetVersionTemplate("{{.Version}}\n")
rootCmd.SetHelpTemplate(rootCmd.HelpTemplate() + "\n" + fullDocsFooter + "\n")
})
}
func onlyVersionText() string {

28
cmd/commandfactory.go Normal file
View file

@ -0,0 +1,28 @@
package caddycmd
import (
"github.com/spf13/cobra"
)
type rootCommandFactory struct {
constructor func() *cobra.Command
options []func(*cobra.Command)
}
func newRootCommandFactory(fn func() *cobra.Command) *rootCommandFactory {
return &rootCommandFactory{
constructor: fn,
}
}
func (f *rootCommandFactory) Use(fn func(cmd *cobra.Command)) {
f.options = append(f.options, fn)
}
func (f *rootCommandFactory) Build() *cobra.Command {
o := f.constructor()
for _, v := range f.options {
v(o)
}
return o
}

View file

@ -438,6 +438,7 @@ EXPERIMENTAL: May be changed or removed.
},
})
defaultFactory.Use(func(rootCmd *cobra.Command) {
RegisterCommand(Command{
Name: "manpage",
Usage: "--directory <path>",
@ -531,6 +532,7 @@ argument of --directory. If the directory does not exist, it will be created.
}
},
})
})
}
// RegisterCommand registers the command cmd.
@ -563,7 +565,9 @@ func RegisterCommand(cmd Command) {
if !commandNameRegex.MatchString(cmd.Name) {
panic("invalid command name")
}
defaultFactory.Use(func(rootCmd *cobra.Command) {
rootCmd.AddCommand(caddyCmdToCobra(cmd))
})
}
var commandNameRegex = regexp.MustCompile(`^[a-z0-9]$|^([a-z0-9]+-?[a-z0-9]*)+[a-z0-9]$`)

View file

@ -72,7 +72,7 @@ func Main() {
caddy.Log().Warn("failed to set GOMAXPROCS", zap.Error(err))
}
if err := rootCmd.Execute(); err != nil {
if err := defaultFactory.Build().Execute(); err != nil {
var exitError *exitError
if errors.As(err, &exitError) {
os.Exit(exitError.ExitCode)