mirror of
https://github.com/juanfont/headscale.git
synced 2026-08-07 15:58:45 +09:00
cmd/headscale/cli: silence cobra error/usage output and centralise error formatting
Set SilenceErrors and SilenceUsage on the root command so that cobra never prints usage text for runtime errors. A SetFlagErrorFunc callback re-enables usage output specifically for flag-parsing errors (the kubectl pattern). Add printError to utils.go and switch Execute() to ExecuteC() so the returned error is formatted as JSON/YAML when --output requests machine-readable output.
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"slices"
|
||||
@@ -39,6 +38,14 @@ func init() {
|
||||
StringP("output", "o", "", "Output format. Empty for human-readable, 'json', 'json-line' or 'yaml'")
|
||||
rootCmd.PersistentFlags().
|
||||
Bool("force", false, "Disable prompts and forces the execution")
|
||||
|
||||
// Re-enable usage output only for flag-parsing errors; runtime errors
|
||||
// from RunE should never dump usage text.
|
||||
rootCmd.SetFlagErrorFunc(func(cmd *cobra.Command, err error) error {
|
||||
cmd.SilenceUsage = false
|
||||
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
func initConfig() {
|
||||
@@ -140,12 +147,15 @@ var rootCmd = &cobra.Command{
|
||||
headscale is an open source implementation of the Tailscale control server
|
||||
|
||||
https://github.com/juanfont/headscale`,
|
||||
SilenceErrors: true,
|
||||
SilenceUsage: true,
|
||||
}
|
||||
|
||||
func Execute() {
|
||||
err := rootCmd.Execute()
|
||||
cmd, err := rootCmd.ExecuteC()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
outputFormat, _ := cmd.Flags().GetString("output")
|
||||
printError(err, outputFormat)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user