From b347684c9ed9ba60edd62c3687d540e2951d191a Mon Sep 17 00:00:00 2001 From: Philip Laine Date: Mon, 3 Jun 2024 17:58:49 +0200 Subject: [PATCH] fix: add custom error printing for Zarf commands (#2575) ## Description This change adds some custom logic for printing returned errors from Cobra commands. This will allow embedded tools like Helm to behave the same as the original tools. While the Zarf commands will print errors in the same expected error format. ## Related Issue Relates to #2567 ## Checklist before merging - [x] Test, docs, adr added or updated as needed - [x] [Contributor Guide Steps](https://github.com/defenseunicorns/zarf/blob/main/.github/CONTRIBUTING.md#developer-workflow) followed Signed-off-by: Austin Abro --- src/cmd/root.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/cmd/root.go b/src/cmd/root.go index 83fb28e61d..52e10044c1 100644 --- a/src/cmd/root.go +++ b/src/cmd/root.go @@ -17,6 +17,7 @@ import ( "github.com/defenseunicorns/zarf/src/pkg/layout" "github.com/defenseunicorns/zarf/src/pkg/message" "github.com/defenseunicorns/zarf/src/types" + "github.com/pterm/pterm" "github.com/spf13/cobra" ) @@ -44,9 +45,11 @@ var rootCmd = &cobra.Command{ common.SetupCLI() }, - Short: lang.RootCmdShort, - Long: lang.RootCmdLong, - Args: cobra.MaximumNArgs(1), + Short: lang.RootCmdShort, + Long: lang.RootCmdLong, + Args: cobra.MaximumNArgs(1), + SilenceUsage: true, + SilenceErrors: true, Run: func(cmd *cobra.Command, args []string) { zarfLogo := message.GetLogo() _, _ = fmt.Fprintln(os.Stderr, zarfLogo) @@ -65,7 +68,17 @@ var rootCmd = &cobra.Command{ // Execute is the entrypoint for the CLI. func Execute() { - cobra.CheckErr(rootCmd.Execute()) + cmd, err := rootCmd.ExecuteC() + if err == nil { + return + } + comps := strings.Split(cmd.CommandPath(), " ") + if len(comps) > 1 && comps[1] == "tools" { + cmd.PrintErrln(cmd.ErrPrefix(), err.Error()) + } else { + pterm.Error.Println(err.Error()) + } + os.Exit(1) } func init() {