From 7e0155c557509ed0e894028a9862a87ed1ecd12d Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Wed, 15 May 2024 10:13:43 -0300 Subject: [PATCH] fix: disable logs on some commands (#4865) closes #4864 Signed-off-by: Carlos Alexandro Becker --- cmd/root.go | 18 ++++++++++++++++-- cmd/root_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index d94fd0db3..b5d21bf39 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -28,6 +28,10 @@ func (cmd *rootCmd) Execute(args []string) { cmd.cmd.SetArgs(append([]string{"release"}, args...)) } + if shouldDisableLogs(args) { + log.SetLevel(log.FatalLevel) + } + if err := cmd.cmd.Execute(); err != nil { code := 1 msg := "command failed" @@ -73,13 +77,13 @@ Check out our website for more information, examples and documentation: https:// SilenceErrors: true, Args: cobra.NoArgs, ValidArgsFunction: cobra.NoFileCompletions, - PersistentPreRun: func(_ *cobra.Command, _ []string) { + PersistentPreRun: func(*cobra.Command, []string) { if root.verbose || root.debug { log.SetLevel(log.DebugLevel) log.Debug("verbose output enabled") } }, - PersistentPostRun: func(_ *cobra.Command, _ []string) { + PersistentPostRun: func(*cobra.Command, []string) { log.Info("thanks for using goreleaser!") }, } @@ -103,6 +107,16 @@ Check out our website for more information, examples and documentation: https:// return root } +func shouldDisableLogs(args []string) bool { + return len(args) > 0 && (args[0] == "help" || + args[0] == "completion" || + args[0] == "man" || + args[0] == "docs" || + args[0] == "jsonschema" || + args[0] == cobra.ShellCompRequestCmd || + args[0] == cobra.ShellCompNoDescRequestCmd) +} + func shouldPrependRelease(cmd *cobra.Command, args []string) bool { // find current cmd, if its not root, it means the user actively // set a command, so let it go diff --git a/cmd/root_test.go b/cmd/root_test.go index 4b4a23a40..6eba67653 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -2,9 +2,11 @@ package cmd import ( "bytes" + "strings" "testing" goversion "github.com/caarlos0/go-version" + "github.com/spf13/cobra" "github.com/stretchr/testify/require" ) @@ -100,3 +102,26 @@ func TestShouldPrependRelease(t *testing.T) { require.False(t, result([]string{"__completeNoDesc"})) }) } + +func TestShouldDisableLogs(t *testing.T) { + testCases := []struct { + args []string + expect bool + }{ + {nil, false}, + {[]string{"release"}, false}, + {[]string{"release", "--clean"}, false}, + {[]string{"help"}, true}, + {[]string{"completion"}, true}, + {[]string{"man"}, true}, + {[]string{"jsonschema"}, true}, + {[]string{"docs"}, true}, + {[]string{cobra.ShellCompRequestCmd}, true}, + {[]string{cobra.ShellCompNoDescRequestCmd}, true}, + } + for _, tC := range testCases { + t.Run(strings.Join(tC.args, " "), func(t *testing.T) { + require.Equal(t, tC.expect, shouldDisableLogs(tC.args)) + }) + } +}