From a02a692a7a66d9209cbf9d977d0e3d1d22691743 Mon Sep 17 00:00:00 2001 From: Sascha Grunert Date: Fri, 5 Jul 2024 10:26:38 +0200 Subject: [PATCH] Update golangci-lint and fix lints Signed-off-by: Sascha Grunert --- .golangci.yml | 13 +++- command/command.go | 28 ++++----- command/command_test.go | 130 ++++++++++++++++++++-------------------- command/global.go | 4 +- editor/editor.go | 2 +- hash/hash.go | 2 +- hash/hash_test.go | 33 +++++----- http/agent.go | 42 ++++++------- http/http.go | 2 +- http/http_test.go | 31 ++++++---- log/hooks.go | 12 ++-- log/log_test.go | 8 +-- log/step.go | 2 +- mage/boilerplate.go | 5 +- mage/cosign.go | 4 +- mage/dependency.go | 4 +- mage/golangci-lint.go | 9 +-- mage/ko.go | 4 +- mage/version.go | 8 +-- tar/tar_test.go | 48 +++++++-------- util/common.go | 16 ++--- util/common_test.go | 62 +++++++++---------- version/command.go | 4 +- version/version.go | 12 ++-- version/version_test.go | 2 +- 25 files changed, 251 insertions(+), 236 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 5832a68..a5d836f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -34,12 +34,14 @@ linters: - errchkjson - errname - fatcontext + - gci - ginkgolinter - gocheckcompilerdirectives - gochecksumtype - goconst - gocritic - gocyclo + - godot - godox - gofmt - gofumpt @@ -80,6 +82,7 @@ linters: - tagalign - tenv - testableexamples + - testifylint - typecheck - unconvert - unparam @@ -99,11 +102,9 @@ linters: # - forbidigo # - forcetypeassert # - funlen - # - gci # - gochecknoglobals # - gochecknoinits # - gocognit - # - godot # - inamedparam # - interfacebloat # - ireturn @@ -118,7 +119,6 @@ linters: # - nonamedreturns # - paralleltest # - tagliatelle - # - testifylint # - testpackage # - thelper # - tparallel @@ -127,6 +127,13 @@ linters: # - wrapcheck # - wsl linters-settings: + gci: + sections: + - standard + - default + - prefix(k8s.io) + - prefix(sigs.k8s.io) + - localmodule gocyclo: min-complexity: 40 godox: diff --git a/command/command.go b/command/command.go index bfb85d8..a645de6 100644 --- a/command/command.go +++ b/command/command.go @@ -30,7 +30,7 @@ import ( "github.com/sirupsen/logrus" ) -// A generic command abstraction +// A generic command abstraction. type Command struct { cmds []*command stdErrWriters, stdOutWriters []io.Writer @@ -39,7 +39,7 @@ type Command struct { filter *filter } -// The internal command representation +// The internal command representation. type command struct { *exec.Cmd pipeWriter *io.PipeWriter @@ -51,19 +51,19 @@ type filter struct { replaceAll string } -// A generic command exit status +// A generic command exit status. type Status struct { waitStatus syscall.WaitStatus *Stream } -// Stream combines standard output and error +// Stream combines standard output and error. type Stream struct { //nolint: errname stdOut string stdErr string } -// Commands is an abstraction over multiple Command structures +// Commands is an abstraction over multiple Command structures. type Commands []*Command // New creates a new command from the provided arguments. @@ -91,7 +91,7 @@ func cmdWithDir(dir, cmd string, args ...string) *exec.Cmd { return c } -// Pipe creates a new command where the previous should be piped to +// Pipe creates a new command where the previous should be piped to. func (c *Command) Pipe(cmd string, args ...string) *Command { pipeCmd := cmdWithDir(c.cmds[0].Dir, cmd, args...) @@ -121,7 +121,7 @@ func (c *Command) Verbose() *Command { } // isVerbose returns true if the command is in verbose mode, either set locally -// or global +// or global. func (c *Command) isVerbose() bool { return GetGlobalVerbose() || c.verbose } @@ -174,7 +174,7 @@ func (c *Command) Filter(regex, replaceAll string) (*Command, error) { // Run starts the command and waits for it to finish. It returns an error if // the command execution was not possible at all, otherwise the Status. -// This method prints the commands output during execution +// This method prints the commands output during execution. func (c *Command) Run() (res *Status, err error) { return c.run(true) } @@ -199,7 +199,7 @@ func (c *Command) RunSuccess() error { return err } -// String returns a string representation of the full command +// String returns a string representation of the full command. func (c *Command) String() string { str := []string{} for _, x := range c.cmds { @@ -246,7 +246,7 @@ func (c *Command) RunSilentSuccess() error { return err } -// run is the internal run method +// run is the internal run method. func (c *Command) run(printOutput bool) (res *Status, err error) { var runErr error stdOutBuffer := &bytes.Buffer{} @@ -371,17 +371,17 @@ func (c *Command) run(printOutput bool) (res *Status, err error) { return status, runErr } -// Success returns if a Status was successful +// Success returns if a Status was successful. func (s *Status) Success() bool { return s.waitStatus.ExitStatus() == 0 } -// ExitCode returns the exit status of the command status +// ExitCode returns the exit status of the command status. func (s *Status) ExitCode() int { return s.waitStatus.ExitStatus() } -// Output returns stdout of the command status +// Output returns stdout of the command status. func (s *Stream) Output() string { return s.stdOut } @@ -392,7 +392,7 @@ func (s *Stream) OutputTrimNL() string { return strings.TrimSpace(s.stdOut) } -// Error returns the stderr of the command status +// Error returns the stderr of the command status. func (s *Stream) Error() string { return s.stdErr } diff --git a/command/command_test.go b/command/command_test.go index 7050126..003101f 100644 --- a/command/command_test.go +++ b/command/command_test.go @@ -26,7 +26,7 @@ import ( func TestSuccess(t *testing.T) { res, err := New("echo", "hi").Run() - require.Nil(t, err) + require.NoError(t, err) require.True(t, res.Success()) require.Zero(t, res.ExitCode()) } @@ -36,7 +36,7 @@ func TestSuccessPipe(t *testing.T) { Pipe("cat"). Pipe("cat"). Run() - require.Nil(t, err) + require.NoError(t, err) require.True(t, res.Success()) require.Zero(t, res.ExitCode()) require.Equal(t, "hi", res.Output()) @@ -46,7 +46,7 @@ func TestFailurePipeWrongCommand(t *testing.T) { res, err := New("echo", "-n", "hi"). Pipe("wrong"). Run() - require.NotNil(t, err) + require.Error(t, err) require.Nil(t, res) } @@ -54,7 +54,7 @@ func TestFailurePipeWrongArgument(t *testing.T) { res, err := New("echo", "-n", "hi"). Pipe("cat", "--wrong"). Run() - require.Nil(t, err) + require.NoError(t, err) require.False(t, res.Success()) require.Empty(t, res.Output()) require.NotEmpty(t, res.Error()) @@ -62,94 +62,94 @@ func TestFailurePipeWrongArgument(t *testing.T) { func TestSuccessVerbose(t *testing.T) { res, err := New("echo", "hi").Verbose().Run() - require.Nil(t, err) + require.NoError(t, err) require.True(t, res.Success()) require.Zero(t, res.ExitCode()) } func TestSuccessWithWorkingDir(t *testing.T) { res, err := NewWithWorkDir("/", "ls", "-1").Run() - require.Nil(t, err) + require.NoError(t, err) require.True(t, res.Success()) require.Zero(t, res.ExitCode()) } func TestFailureWithWrongWorkingDir(t *testing.T) { res, err := NewWithWorkDir("/should/not/exist", "ls", "-1").Run() - require.NotNil(t, err) + require.Error(t, err) require.Nil(t, res) } func TestSuccessSilent(t *testing.T) { res, err := New("echo", "hi").RunSilent() - require.Nil(t, err) + require.NoError(t, err) require.True(t, res.Success()) } func TestSuccessSeparated(t *testing.T) { res, err := New("echo", "hi").RunSilent() - require.Nil(t, err) + require.NoError(t, err) require.True(t, res.Success()) } func TestSuccessSingleArgument(t *testing.T) { res, err := New("echo").Run() - require.Nil(t, err) + require.NoError(t, err) require.True(t, res.Success()) } func TestSuccessNoArgument(t *testing.T) { res, err := New("").Run() - require.NotNil(t, err) + require.Error(t, err) require.Nil(t, res) } func TestSuccessOutput(t *testing.T) { res, err := New("echo", "-n", "hello world").Run() - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, "hello world", res.Output()) } func TestSuccessOutputTrimNL(t *testing.T) { res, err := New("echo", "-n", "hello world\n").Run() - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, "hello world", res.OutputTrimNL()) } func TestSuccessError(t *testing.T) { res, err := New("cat", "/not/valid").Run() - require.Nil(t, err) + require.NoError(t, err) require.Empty(t, res.Output()) require.Contains(t, res.Error(), "No such file") } func TestSuccessOutputSeparated(t *testing.T) { res, err := New("echo", "-n", "hello").Run() - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, "hello", res.Output()) } func TestFailureStdErr(t *testing.T) { res, err := New("cat", "/not/valid").Run() - require.Nil(t, err) + require.NoError(t, err) require.False(t, res.Success()) - require.Equal(t, res.ExitCode(), 1) + require.Equal(t, 1, res.ExitCode()) } func TestFailureNotExisting(t *testing.T) { res, err := New("/not/valid").Run() - require.NotNil(t, err) + require.Error(t, err) require.Nil(t, res) } func TestSuccessExecute(t *testing.T) { err := Execute("echo", "-n", "hi", "ho") - require.Nil(t, err) + require.NoError(t, err) } func TestFailureExecute(t *testing.T) { err := Execute("cat", "/not/invalid") - require.NotNil(t, err) + require.Error(t, err) } func TestAvailableSuccessValidCommand(t *testing.T) { @@ -168,150 +168,150 @@ func TestAvailableFailure(t *testing.T) { } func TestSuccessRunSuccess(t *testing.T) { - require.Nil(t, New("echo", "hi").RunSuccess()) + require.NoError(t, New("echo", "hi").RunSuccess()) } func TestFailureRunSuccess(t *testing.T) { - require.NotNil(t, New("cat", "/not/available").RunSuccess()) + require.Error(t, New("cat", "/not/available").RunSuccess()) } func TestSuccessRunSilentSuccess(t *testing.T) { - require.Nil(t, New("echo", "hi").RunSilentSuccess()) + require.NoError(t, New("echo", "hi").RunSilentSuccess()) } func TestFailureRunSuccessSilent(t *testing.T) { - require.NotNil(t, New("cat", "/not/available").RunSilentSuccess()) + require.Error(t, New("cat", "/not/available").RunSilentSuccess()) } func TestSuccessRunSuccessOutput(t *testing.T) { res, err := New("echo", "-n", "hi").RunSuccessOutput() - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, "hi", res.Output()) } func TestFailureRunSuccessOutput(t *testing.T) { res, err := New("cat", "/not/available").RunSuccessOutput() - require.NotNil(t, err) + require.Error(t, err) require.Nil(t, res) } func TestSuccessRunSilentSuccessOutput(t *testing.T) { res, err := New("echo", "-n", "hi").RunSilentSuccessOutput() - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, "hi", res.Output()) } func TestFailureRunSilentSuccessOutput(t *testing.T) { res, err := New("cat", "/not/available").RunSilentSuccessOutput() - require.NotNil(t, err) + require.Error(t, err) require.Nil(t, res) } func TestSuccessLogWriter(t *testing.T) { f, err := os.CreateTemp("", "log") - require.Nil(t, err) - defer func() { require.Nil(t, os.Remove(f.Name())) }() + require.NoError(t, err) + defer func() { require.NoError(t, os.Remove(f.Name())) }() res, err := New("echo", "Hello World").AddWriter(f).RunSuccessOutput() - require.Nil(t, err) + require.NoError(t, err) content, err := os.ReadFile(f.Name()) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, res.Output(), string(content)) } func TestSuccessLogWriterMultiple(t *testing.T) { f, err := os.CreateTemp("", "log") - require.Nil(t, err) - defer func() { require.Nil(t, os.Remove(f.Name())) }() + require.NoError(t, err) + defer func() { require.NoError(t, os.Remove(f.Name())) }() b := &bytes.Buffer{} res, err := New("echo", "Hello World"). AddWriter(f). AddWriter(b). RunSuccessOutput() - require.Nil(t, err) + require.NoError(t, err) content, err := os.ReadFile(f.Name()) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, res.Output(), string(content)) require.Equal(t, res.Output(), b.String()) } func TestSuccessLogWriterSilent(t *testing.T) { f, err := os.CreateTemp("", "log") - require.Nil(t, err) - defer func() { require.Nil(t, os.Remove(f.Name())) }() + require.NoError(t, err) + defer func() { require.NoError(t, os.Remove(f.Name())) }() err = New("echo", "Hello World").AddWriter(f).RunSilentSuccess() - require.Nil(t, err) + require.NoError(t, err) content, err := os.ReadFile(f.Name()) - require.Nil(t, err) + require.NoError(t, err) require.Empty(t, content) } func TestSuccessLogWriterStdErr(t *testing.T) { f, err := os.CreateTemp("", "log") - require.Nil(t, err) - defer func() { require.Nil(t, os.Remove(f.Name())) }() + require.NoError(t, err) + defer func() { require.NoError(t, os.Remove(f.Name())) }() res, err := New("bash", "-c", ">&2 echo error"). AddWriter(f).RunSuccessOutput() - require.Nil(t, err) + require.NoError(t, err) content, err := os.ReadFile(f.Name()) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, res.Error(), string(content)) } func TestSuccessLogWriterStdErrAndStdOut(t *testing.T) { f, err := os.CreateTemp("", "log") - require.Nil(t, err) - defer func() { require.Nil(t, os.Remove(f.Name())) }() + require.NoError(t, err) + defer func() { require.NoError(t, os.Remove(f.Name())) }() res, err := New("bash", "-c", ">&2 echo stderr; echo stdout"). AddWriter(f).RunSuccessOutput() - require.Nil(t, err) + require.NoError(t, err) content, err := os.ReadFile(f.Name()) - require.Nil(t, err) + require.NoError(t, err) require.Contains(t, string(content), res.Output()) require.Contains(t, string(content), res.Error()) } func TestSuccessLogWriterStdErrAndStdOutOnlyStdErr(t *testing.T) { f, err := os.CreateTemp("", "log") - require.Nil(t, err) - defer func() { require.Nil(t, os.Remove(f.Name())) }() + require.NoError(t, err) + defer func() { require.NoError(t, os.Remove(f.Name())) }() res, err := New("bash", "-c", ">&2 echo stderr; echo stdout"). AddErrorWriter(f).RunSuccessOutput() - require.Nil(t, err) + require.NoError(t, err) content, err := os.ReadFile(f.Name()) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, res.Error(), string(content)) } func TestSuccessLogWriterStdErrAndStdOutOnlyStdOut(t *testing.T) { f, err := os.CreateTemp("", "log") - require.Nil(t, err) - defer func() { require.Nil(t, os.Remove(f.Name())) }() + require.NoError(t, err) + defer func() { require.NoError(t, os.Remove(f.Name())) }() res, err := New("bash", "-c", ">&2 echo stderr; echo stdout"). AddOutputWriter(f).RunSuccessOutput() - require.Nil(t, err) + require.NoError(t, err) content, err := os.ReadFile(f.Name()) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, res.Output(), string(content)) } func TestCommandsSuccess(t *testing.T) { res, err := New("echo", "1").Verbose(). Add("echo", "2").Add("echo", "3").Run() - require.Nil(t, err) + require.NoError(t, err) require.True(t, res.Success()) require.Zero(t, res.ExitCode()) require.Contains(t, res.Output(), "1") @@ -321,27 +321,27 @@ func TestCommandsSuccess(t *testing.T) { func TestCommandsFailure(t *testing.T) { res, err := New("echo", "1").Add("wrong").Add("echo", "3").Run() - require.NotNil(t, err) + require.Error(t, err) require.Nil(t, res) } func TestEnv(t *testing.T) { - require.Nil(t, os.Setenv("ABC", "test")) // preserved - require.Nil(t, os.Setenv("FOO", "test")) // overwritten + require.NoError(t, os.Setenv("ABC", "test")) // preserved + require.NoError(t, os.Setenv("FOO", "test")) // overwritten res, err := New("sh", "-c", "echo $TEST; echo $FOO; echo $ABC"). Env("TEST=123"). Env("FOO=bar"). RunSuccessOutput() - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, "123\nbar\ntest", res.OutputTrimNL()) } func TestFilterStdout(t *testing.T) { cmd, err := New("echo", "-n", "1 2 2 3").Filter("[25]", "0") - require.Nil(t, err) + require.NoError(t, err) res, err := cmd.Add("echo", "-n", "4 5 6 2 2").Run() - require.Nil(t, err) + require.NoError(t, err) require.True(t, res.Success()) require.Zero(t, res.ExitCode()) require.Equal(t, "\n1 0 0 3\n4 0 6 0 0", res.Output()) @@ -349,9 +349,9 @@ func TestFilterStdout(t *testing.T) { func TestFilterStderr(t *testing.T) { res, err := New("bash", "-c", ">&2 echo -n my secret").Filter("secret", "***") - require.Nil(t, err) + require.NoError(t, err) out, err := res.RunSilentSuccessOutput() - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, "my ***", out.Error()) require.Empty(t, out.Output()) } diff --git a/command/global.go b/command/global.go index 687e707..7ae559f 100644 --- a/command/global.go +++ b/command/global.go @@ -24,7 +24,7 @@ import ( // level. It should never be used directly to avoid data races. var atomicInt int32 -// SetGlobalVerbose sets the global command verbosity to the specified value +// SetGlobalVerbose sets the global command verbosity to the specified value. func SetGlobalVerbose(to bool) { var i int32 if to { @@ -33,7 +33,7 @@ func SetGlobalVerbose(to bool) { atomic.StoreInt32(&atomicInt, i) } -// GetGlobalVerbose returns the globally set command verbosity +// GetGlobalVerbose returns the globally set command verbosity. func GetGlobalVerbose() bool { return atomic.LoadInt32(&atomicInt) != 0 } diff --git a/editor/editor.go b/editor/editor.go index bf93e86..d0fda5a 100644 --- a/editor/editor.go +++ b/editor/editor.go @@ -39,7 +39,7 @@ const ( windowsShell = "cmd" ) -// Editor holds the command-line args to fire up the editor +// Editor holds the command-line args to fire up the editor. type Editor struct { Args []string Shell bool diff --git a/hash/hash.go b/hash/hash.go index 2cdde6f..0b1a32d 100644 --- a/hash/hash.go +++ b/hash/hash.go @@ -41,7 +41,7 @@ func SHA256ForFile(filename string) (string, error) { } // SHA1ForFile returns the hex-encoded sha1 hash for the provided filename. -// TODO: check if we can remove this function +// TODO: check if we can remove this function. func SHA1ForFile(filename string) (string, error) { return ForFile(filename, sha1.New()) //nolint: gosec } diff --git a/hash/hash_test.go b/hash/hash_test.go index 3d5043d..98e6fac 100644 --- a/hash/hash_test.go +++ b/hash/hash_test.go @@ -24,6 +24,7 @@ import ( "testing" "github.com/stretchr/testify/require" + kHash "sigs.k8s.io/release-utils/hash" ) @@ -36,10 +37,10 @@ func TestSHA512ForFile(t *testing.T) { { // success prepare: func() string { f, err := os.CreateTemp("", "") - require.Nil(t, err) + require.NoError(t, err) _, err = f.WriteString("test") - require.Nil(t, err) + require.NoError(t, err) return f.Name() }, @@ -58,9 +59,9 @@ func TestSHA512ForFile(t *testing.T) { res, err := kHash.SHA512ForFile(filename) if tc.shouldError { - require.NotNil(t, err) + require.Error(t, err) } else { - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, tc.expected, res) } } @@ -75,10 +76,10 @@ func TestSHA256ForFile(t *testing.T) { { // success prepare: func() string { f, err := os.CreateTemp("", "") - require.Nil(t, err) + require.NoError(t, err) _, err = f.WriteString("test") - require.Nil(t, err) + require.NoError(t, err) return f.Name() }, @@ -95,9 +96,9 @@ func TestSHA256ForFile(t *testing.T) { res, err := kHash.SHA256ForFile(filename) if tc.shouldError { - require.NotNil(t, err) + require.Error(t, err) } else { - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, tc.expected, res) } } @@ -112,10 +113,10 @@ func TestSHA1ForFile(t *testing.T) { { // success prepare: func() string { f, err := os.CreateTemp("", "") - require.Nil(t, err) + require.NoError(t, err) _, err = f.WriteString("test") - require.Nil(t, err) + require.NoError(t, err) return f.Name() }, @@ -132,9 +133,9 @@ func TestSHA1ForFile(t *testing.T) { res, err := kHash.SHA1ForFile(filename) if tc.shouldError { - require.NotNil(t, err) + require.Error(t, err) } else { - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, tc.expected, res) } } @@ -149,10 +150,10 @@ func TestForFile(t *testing.T) { { // success prepare: func() (string, hash.Hash) { f, err := os.CreateTemp("", "") - require.Nil(t, err) + require.NoError(t, err) _, err = f.WriteString("test") - require.Nil(t, err) + require.NoError(t, err) return f.Name(), sha1.New() //nolint: gosec }, @@ -177,9 +178,9 @@ func TestForFile(t *testing.T) { res, err := kHash.ForFile(filename, hasher) if tc.shouldError { - require.NotNil(t, err) + require.Error(t, err) } else { - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, tc.expected, res) } } diff --git a/http/agent.go b/http/agent.go index f0d2dc1..3477f30 100644 --- a/http/agent.go +++ b/http/agent.go @@ -34,7 +34,7 @@ const ( //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate //go:generate /usr/bin/env bash -c "cat ../scripts/boilerplate/boilerplate.generatego.txt httpfakes/fake_agent_implementation.go > httpfakes/_fake_agent_implementation.go && mv httpfakes/_fake_agent_implementation.go httpfakes/fake_agent_implementation.go" -// Agent is an http agent +// Agent is an http agent. type Agent struct { options *agentOptions AgentImplementation @@ -51,7 +51,7 @@ type AgentImplementation interface { type defaultAgentImplementation struct{} -// agentOptions has the configurable bits of the agent +// agentOptions has the configurable bits of the agent. type agentOptions struct { FailOnHTTPError bool // Set to true to fail on HTTP Status > 299 Retries uint // Number of times to retry when errors happen @@ -60,7 +60,7 @@ type agentOptions struct { PostContentType string // Content type to send when posting data } -// String returns a string representation of the options +// String returns a string representation of the options. func (ao *agentOptions) String() string { return fmt.Sprintf( "HTTP.Agent options: Timeout: %d - Retries: %d - FailOnHTTPError: %+v", @@ -76,7 +76,7 @@ var defaultAgentOptions = &agentOptions{ PostContentType: defaultPostContentType, } -// NewAgent return a new agent with default options +// NewAgent return a new agent with default options. func NewAgent() *Agent { return &Agent{ AgentImplementation: &defaultAgentImplementation{}, @@ -84,37 +84,37 @@ func NewAgent() *Agent { } } -// SetImplementation sets the agent implementation +// SetImplementation sets the agent implementation. func (a *Agent) SetImplementation(impl AgentImplementation) { a.AgentImplementation = impl } -// WithTimeout sets the agent timeout +// WithTimeout sets the agent timeout. func (a *Agent) WithTimeout(timeout time.Duration) *Agent { a.options.Timeout = timeout return a } -// WithRetries sets the number of times we'll attempt to fetch the URL +// WithRetries sets the number of times we'll attempt to fetch the URL. func (a *Agent) WithRetries(retries uint) *Agent { a.options.Retries = retries return a } -// WithFailOnHTTPError determines if the agent fails on HTTP errors (HTTP status not in 200s) +// WithFailOnHTTPError determines if the agent fails on HTTP errors (HTTP status not in 200s). func (a *Agent) WithFailOnHTTPError(flag bool) *Agent { a.options.FailOnHTTPError = flag return a } -// Client return an net/http client preconfigured with the agent options +// Client return an net/http client preconfigured with the agent options. func (a *Agent) Client() *http.Client { return &http.Client{ Timeout: a.options.Timeout, } } -// Get returns the body a a GET request +// Get returns the body a a GET request. func (a *Agent) Get(url string) (content []byte, err error) { request, err := a.GetRequest(url) if err != nil { @@ -125,7 +125,7 @@ func (a *Agent) Get(url string) (content []byte, err error) { return a.readResponseToByteArray(request) } -// GetRequest sends a GET request to a URL and returns the request and response +// GetRequest sends a GET request to a URL and returns the request and response. func (a *Agent) GetRequest(url string) (response *http.Response, err error) { logrus.Debugf("Sending GET request to %s", url) try := 0 @@ -149,7 +149,7 @@ func (a *Agent) GetRequest(url string) (response *http.Response, err error) { } } -// Post returns the body of a POST request +// Post returns the body of a POST request. func (a *Agent) Post(url string, postData []byte) (content []byte, err error) { response, err := a.PostRequest(url, postData) if err != nil { @@ -160,7 +160,7 @@ func (a *Agent) Post(url string, postData []byte) (content []byte, err error) { return a.readResponseToByteArray(response) } -// PostRequest sends the postData in a POST request to a URL and returns the request object +// PostRequest sends the postData in a POST request to a URL and returns the request object. func (a *Agent) PostRequest(url string, postData []byte) (response *http.Response, err error) { logrus.Debugf("Sending POST request to %s", url) try := 0 @@ -184,7 +184,7 @@ func (a *Agent) PostRequest(url string, postData []byte) (response *http.Respons } } -// Head returns the body of a HEAD request +// Head returns the body of a HEAD request. func (a *Agent) Head(url string) (content []byte, err error) { response, err := a.HeadRequest(url) if err != nil { @@ -195,7 +195,7 @@ func (a *Agent) Head(url string) (content []byte, err error) { return a.readResponseToByteArray(response) } -// HeadRequest sends a HEAD request to a URL and returns the request and response +// HeadRequest sends a HEAD request to a URL and returns the request and response. func (a *Agent) HeadRequest(url string) (response *http.Response, err error) { logrus.Debugf("Sending HEAD request to %s", url) try := 0 @@ -219,7 +219,7 @@ func (a *Agent) HeadRequest(url string) (response *http.Response, err error) { } } -// SendPostRequest sends the actual HTTP post to the server +// SendPostRequest sends the actual HTTP post to the server. func (impl *defaultAgentImplementation) SendPostRequest( client *http.Client, url string, postData []byte, contentType string, ) (response *http.Response, err error) { @@ -233,7 +233,7 @@ func (impl *defaultAgentImplementation) SendPostRequest( return response, nil } -// SendGetRequest performs the actual request +// SendGetRequest performs the actual request. func (impl *defaultAgentImplementation) SendGetRequest(client *http.Client, url string) ( response *http.Response, err error, ) { @@ -245,7 +245,7 @@ func (impl *defaultAgentImplementation) SendGetRequest(client *http.Client, url return response, nil } -// SendHeadRequest performs the actual request +// SendHeadRequest performs the actual request. func (impl *defaultAgentImplementation) SendHeadRequest(client *http.Client, url string) ( response *http.Response, err error, ) { @@ -257,7 +257,7 @@ func (impl *defaultAgentImplementation) SendHeadRequest(client *http.Client, url return response, nil } -// readResponseToByteArray returns the contents of an http response as a byte array +// readResponseToByteArray returns the contents of an http response as a byte array. func (a *Agent) readResponseToByteArray(response *http.Response) ([]byte, error) { var b bytes.Buffer if err := a.readResponse(response, &b); err != nil { @@ -290,7 +290,7 @@ func (a *Agent) readResponse(response *http.Response, w io.Writer) (err error) { return err } -// GetToWriter sends a get request and writes the response to an io.Writer +// GetToWriter sends a get request and writes the response to an io.Writer. func (a *Agent) GetToWriter(w io.Writer, url string) error { resp, err := a.AgentImplementation.SendGetRequest(a.Client(), url) if err != nil { @@ -300,7 +300,7 @@ func (a *Agent) GetToWriter(w io.Writer, url string) error { return a.readResponse(resp, w) } -// PostToWriter sends a request to a url and writes the response to an io.Writer +// PostToWriter sends a request to a url and writes the response to an io.Writer. func (a *Agent) PostToWriter(w io.Writer, url string, postData []byte) error { resp, err := a.AgentImplementation.SendPostRequest(a.Client(), url, postData, a.options.PostContentType) if err != nil { diff --git a/http/http.go b/http/http.go index c089f41..6c1136e 100644 --- a/http/http.go +++ b/http/http.go @@ -20,7 +20,7 @@ import ( "bytes" ) -// GetURLResponse returns the HTTP response for the provided URL if the request succeeds +// GetURLResponse returns the HTTP response for the provided URL if the request succeeds. func GetURLResponse(url string, trim bool) (string, error) { resp, err := NewAgent().Get(url) if err != nil { diff --git a/http/http_test.go b/http/http_test.go index 200d73a..d121ab9 100644 --- a/http/http_test.go +++ b/http/http_test.go @@ -26,6 +26,7 @@ import ( "testing" "github.com/stretchr/testify/require" + khttp "sigs.k8s.io/release-utils/http" "sigs.k8s.io/release-utils/http/httpfakes" ) @@ -35,7 +36,9 @@ func TestGetURLResponseSuccess(t *testing.T) { server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, _ *http.Request) { _, err := io.WriteString(w, "") - require.Nil(t, err) + if err != nil { + t.Fail() + } })) defer server.Close() @@ -43,7 +46,7 @@ func TestGetURLResponseSuccess(t *testing.T) { actual, err := khttp.GetURLResponse(server.URL, false) // Then - require.Nil(t, err) + require.NoError(t, err) require.Empty(t, actual) } @@ -53,7 +56,9 @@ func TestGetURLResponseSuccessTrimmed(t *testing.T) { server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, _ *http.Request) { _, err := io.WriteString(w, expected) - require.Nil(t, err) + if err != nil { + t.Fail() + } })) defer server.Close() @@ -61,7 +66,7 @@ func TestGetURLResponseSuccessTrimmed(t *testing.T) { actual, err := khttp.GetURLResponse(server.URL, true) // Then - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, strings.TrimSpace(expected), actual) } @@ -77,7 +82,7 @@ func TestGetURLResponseFailedStatus(t *testing.T) { _, err := khttp.GetURLResponse(server.URL, true) // Then - require.NotNil(t, err) + require.Error(t, err) } func NewTestAgent() *khttp.Agent { @@ -97,14 +102,14 @@ func TestAgentPost(t *testing.T) { agent.SetImplementation(fake) body, err := agent.Post("http://www.example.com/", []byte("Test string")) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, body, []byte("hello sig-release!")) // Now check error is handled fake.SendPostRequestReturns(resp, errors.New("HTTP Post error")) agent.SetImplementation(fake) _, err = agent.Post("http://www.example.com/", []byte("Test string")) - require.NotNil(t, err) + require.Error(t, err) } func TestAgentGet(t *testing.T) { @@ -119,14 +124,14 @@ func TestAgentGet(t *testing.T) { agent.SetImplementation(fake) b, err := agent.Get("http://www.example.com/") - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, b, []byte("hello sig-release!")) // Now check error is handled fake.SendGetRequestReturns(resp, errors.New("HTTP Post error")) agent.SetImplementation(fake) _, err = agent.Get("http://www.example.com/") - require.NotNil(t, err) + require.Error(t, err) } func TestAgentGetToWriter(t *testing.T) { @@ -182,14 +187,14 @@ func TestAgentHead(t *testing.T) { agent.SetImplementation(fake) b, err := agent.Head("http://www.example.com/") - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, b, []byte("hello sig-release!")) // Now check error is handled fake.SendHeadRequestReturns(resp, errors.New("HTTP Head error")) agent.SetImplementation(fake) _, err = agent.Head("http://www.example.com/") - require.NotNil(t, err) + require.Error(t, err) } func getTestResponse() *http.Response { @@ -262,9 +267,9 @@ func TestAgentOptions(t *testing.T) { // Test FailOnHTTPError // First we fail on server errors _, err := agent.WithFailOnHTTPError(true).Get("http://example.com/") - require.NotNil(t, err) + require.Error(t, err) // Then we just note them and do not fail _, err = agent.WithFailOnHTTPError(false).Get("http://example.com/") - require.Nil(t, err) + require.NoError(t, err) } diff --git a/log/hooks.go b/log/hooks.go index 04b5960..f9fcfcd 100644 --- a/log/hooks.go +++ b/log/hooks.go @@ -36,7 +36,7 @@ type wrapper struct { hook *FileNameHook } -// NewFilenameHook creates a new default FileNameHook +// NewFilenameHook creates a new default FileNameHook. func NewFilenameHook() *FileNameHook { return &FileNameHook{ field: "file", @@ -48,12 +48,12 @@ func NewFilenameHook() *FileNameHook { } // Levels returns the levels for which the hook is activated. This contains -// currently only the DebugLevel +// currently only the DebugLevel. func (f *FileNameHook) Levels() []logrus.Level { return []logrus.Level{logrus.DebugLevel} } -// Fire executes the hook for every logrus entry +// Fire executes the hook for every logrus entry. func (f *FileNameHook) Fire(entry *logrus.Entry) error { if f.formatter != entry.Logger.Formatter { f.formatter = &wrapper{entry.Logger.Formatter, f} @@ -62,7 +62,7 @@ func (f *FileNameHook) Fire(entry *logrus.Entry) error { return nil } -// Format returns the log format including the caller as field +// Format returns the log format including the caller as field. func (w *wrapper) Format(entry *logrus.Entry) ([]byte, error) { field := entry.WithField( w.hook.field, @@ -73,7 +73,7 @@ func (w *wrapper) Format(entry *logrus.Entry) ([]byte, error) { return w.old.Format(field) } -// findCaller returns the file, function and line number for the current call +// findCaller returns the file, function and line number for the current call. func (f *FileNameHook) findCaller() (file, function string, line int) { var pc uintptr // The maximum amount of frames to be iterated @@ -119,7 +119,7 @@ func caller(skip int) (pc uintptr, file string, line int) { return pc, file, line } -// shouldSkipPrefix returns true if the hook should be skipped, otherwise false +// shouldSkipPrefix returns true if the hook should be skipped, otherwise false. func (f *FileNameHook) shouldSkipPrefix(file string) bool { for i := range f.skipPrefix { if strings.HasPrefix(file, f.skipPrefix[i]) { diff --git a/log/log_test.go b/log/log_test.go index 7f8b686..acdc523 100644 --- a/log/log_test.go +++ b/log/log_test.go @@ -28,15 +28,15 @@ import ( func TestToFile(t *testing.T) { file, err := os.CreateTemp("", "log-test-") - require.Nil(t, err) + require.NoError(t, err) defer os.Remove(file.Name()) - require.Nil(t, log.SetupGlobalLogger("info")) - require.Nil(t, log.ToFile(file.Name())) + require.NoError(t, log.SetupGlobalLogger("info")) + require.NoError(t, log.ToFile(file.Name())) logrus.Info("test") content, err := os.ReadFile(file.Name()) - require.Nil(t, err) + require.NoError(t, err) require.Contains(t, string(content), "info") require.Contains(t, string(content), "test") diff --git a/log/step.go b/log/step.go index 242f31a..0853949 100644 --- a/log/step.go +++ b/log/step.go @@ -29,7 +29,7 @@ type StepLogger struct { currentStep uint } -// NewStepLogger creates a new logger +// NewStepLogger creates a new logger. func NewStepLogger(steps uint) *StepLogger { return &StepLogger{ Logger: logrus.StandardLogger(), diff --git a/mage/boilerplate.go b/mage/boilerplate.go index 876f040..c3e9801 100644 --- a/mage/boilerplate.go +++ b/mage/boilerplate.go @@ -29,11 +29,12 @@ import ( "github.com/uwu-tools/magex/shx" kpath "k8s.io/utils/path" + "sigs.k8s.io/release-utils/command" ) const ( - // repo-infra (used for boilerplate script) + // repo-infra (used for boilerplate script). defaultRepoInfraVersion = "v0.2.5" repoInfraURLBase = "https://raw.githubusercontent.com/kubernetes/repo-infra" ) @@ -118,7 +119,7 @@ func EnsureBoilerplateScript(version, boilerplateScript string, forceInstall boo return nil } -// VerifyBoilerplate runs copyright header checks +// VerifyBoilerplate runs copyright header checks. func VerifyBoilerplate(version, binDir, boilerplateDir string, forceInstall bool) error { if _, err := kpath.Exists(kpath.CheckSymlinkOnly, boilerplateDir); err != nil { return fmt.Errorf( diff --git a/mage/cosign.go b/mage/cosign.go index 9a58d36..40c412f 100644 --- a/mage/cosign.go +++ b/mage/cosign.go @@ -27,7 +27,7 @@ import ( const defaultCosignVersion = "v2.2.4" -// EnsureCosign makes sure that the specified cosign version is available +// EnsureCosign makes sure that the specified cosign version is available. func EnsureCosign(version string) error { if version == "" { version = defaultCosignVersion @@ -48,7 +48,7 @@ func EnsureCosign(version string) error { return nil } -// InstallCosign installs the required cosign version +// InstallCosign installs the required cosign version. func InstallCosign(version string) error { fmt.Println("Will install `cosign`") target := "cosign" diff --git a/mage/dependency.go b/mage/dependency.go index 6e6a664..e5b44cf 100644 --- a/mage/dependency.go +++ b/mage/dependency.go @@ -26,7 +26,7 @@ import ( ) const ( - // zeitgeist + // zeitgeist. defaultZeitgeistVersion = "v0.5.3" zeitgeistCmd = "zeitgeist" zeitgeistModule = "sigs.k8s.io/zeitgeist" @@ -91,7 +91,7 @@ func EnsureZeitgeistRemote(version string) error { return nil } -// VerifyDeps runs zeitgeist to verify dependency versions +// VerifyDeps runs zeitgeist to verify dependency versions. func VerifyDeps(version, basePath, configPath string, localOnly bool) error { if err := EnsureZeitgeist(version); err != nil { return fmt.Errorf("ensuring zeitgeist is installed: %w", err) diff --git a/mage/golangci-lint.go b/mage/golangci-lint.go index 1ae1566..c52022a 100644 --- a/mage/golangci-lint.go +++ b/mage/golangci-lint.go @@ -31,13 +31,14 @@ import ( "github.com/uwu-tools/magex/shx" kpath "k8s.io/utils/path" + "sigs.k8s.io/release-utils/command" "sigs.k8s.io/release-utils/env" ) const ( - // golangci-lint - defaultGolangCILintVersion = "v1.58.0" + // golangci-lint. + defaultGolangCILintVersion = "v1.59.1" golangciCmd = "golangci-lint" golangciConfig = ".golangci.yml" golangciURLBase = "https://raw.githubusercontent.com/golangci/golangci-lint" @@ -114,7 +115,7 @@ func EnsureGolangCILint(version string, forceInstall bool) error { return nil } -// RunGolangCILint runs all golang linters +// RunGolangCILint runs all golang linters. func RunGolangCILint(version string, forceInstall bool, args ...string) error { if _, err := kpath.Exists(kpath.CheckSymlinkOnly, golangciConfig); err != nil { return fmt.Errorf( @@ -203,7 +204,7 @@ func VerifyGoMod() error { return nil } -// VerifyBuild builds the project for a chosen set of platforms +// VerifyBuild builds the project for a chosen set of platforms. func VerifyBuild(scriptDir string) error { wd, err := os.Getwd() if err != nil { diff --git a/mage/ko.go b/mage/ko.go index 76dcda1..d949e0c 100644 --- a/mage/ko.go +++ b/mage/ko.go @@ -27,7 +27,7 @@ import ( const defaultKoVersion = "0.15.2" -// EnsureKO +// EnsureKO ensures that the ko binary exists. func EnsureKO(version string) error { if version == "" { version = defaultKoVersion @@ -48,7 +48,7 @@ func EnsureKO(version string) error { return nil } -// Maybe we can move this to release-utils +// Maybe we can move this to release-utils. func InstallKO(version string) error { fmt.Println("Will install `ko`") target := "ko" diff --git a/mage/version.go b/mage/version.go index 8104f35..c20178f 100644 --- a/mage/version.go +++ b/mage/version.go @@ -24,7 +24,7 @@ import ( "github.com/uwu-tools/magex/shx" ) -// getVersion gets a description of the commit, e.g. v0.30.1 (latest) or v0.30.1-32-gfe72ff73 (canary) +// getVersion gets a description of the commit, e.g. v0.30.1 (latest) or v0.30.1-32-gfe72ff73 (canary). func getVersion() (string, error) { version, err := shx.Output("git", "describe", "--tags", "--always") if err != nil { @@ -38,12 +38,12 @@ func getVersion() (string, error) { return "v0.0.0", nil } -// getCommit gets the hash of the current commit +// getCommit gets the hash of the current commit. func getCommit() (string, error) { return shx.Output("git", "rev-parse", "--short", "HEAD") } -// getGitState gets the state of the git repository +// getGitState gets the state of the git repository. func getGitState() string { _, err := shx.Output("git", "diff", "--quiet") if err != nil { @@ -53,7 +53,7 @@ func getGitState() string { return "clean" } -// getBuildDateTime gets the build date and time +// getBuildDateTime gets the build date and time. func getBuildDateTime() (string, error) { result, err := shx.Output("git", "log", "-1", "--pretty=%ct") if err != nil { diff --git a/tar/tar_test.go b/tar/tar_test.go index 51dcddb..5785864 100644 --- a/tar/tar_test.go +++ b/tar/tar_test.go @@ -30,13 +30,13 @@ import ( func TestCompress(t *testing.T) { baseTmpDir, err := os.MkdirTemp("", "compress-") - require.Nil(t, err) + require.NoError(t, err) defer os.RemoveAll(baseTmpDir) for _, fileName := range []string{ "1.txt", "2.bin", "3.md", } { - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( filepath.Join(baseTmpDir, fileName), []byte{1, 2, 3}, os.FileMode(0o644), @@ -44,12 +44,12 @@ func TestCompress(t *testing.T) { } subTmpDir := filepath.Join(baseTmpDir, "sub") - require.Nil(t, os.MkdirAll(subTmpDir, os.FileMode(0o755))) + require.NoError(t, os.MkdirAll(subTmpDir, os.FileMode(0o755))) for _, fileName := range []string{ "4.txt", "5.bin", "6.md", } { - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( filepath.Join(subTmpDir, fileName), []byte{4, 5, 6}, os.FileMode(0o644), @@ -58,7 +58,7 @@ func TestCompress(t *testing.T) { logrus.SetLevel(logrus.DebugLevel) - require.Nil(t, os.Symlink( + require.NoError(t, os.Symlink( filepath.Join(baseTmpDir, "1.txt"), filepath.Join(subTmpDir, "link"), )) @@ -69,11 +69,11 @@ func TestCompress(t *testing.T) { } tarFilePath := filepath.Join(baseTmpDir, "res.tar.gz") - require.Nil(t, Compress(tarFilePath, baseTmpDir, excludes...)) + require.NoError(t, Compress(tarFilePath, baseTmpDir, excludes...)) require.FileExists(t, tarFilePath) res := []string{"1.txt", "2.bin", "sub/4.txt", "sub/link"} - require.Nil(t, iterateTarball( + require.NoError(t, iterateTarball( tarFilePath, func(_ *tar.Reader, header *tar.Header) (bool, error) { require.Equal(t, res[0], header.Name) res = res[1:] @@ -84,16 +84,16 @@ func TestCompress(t *testing.T) { func TestCompressWithoutPreservingPath(t *testing.T) { baseTmpDir, err := os.MkdirTemp("", "compress-") - require.Nil(t, err) + require.NoError(t, err) defer os.RemoveAll(baseTmpDir) compressDir := filepath.Join(baseTmpDir, "to_compress") - require.Nil(t, os.MkdirAll(compressDir, os.FileMode(0o755))) + require.NoError(t, os.MkdirAll(compressDir, os.FileMode(0o755))) for _, fileName := range []string{ "1.txt", "2.bin", "3.md", } { - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( filepath.Join(compressDir, fileName), []byte{1, 2, 3}, os.FileMode(0o644), @@ -103,11 +103,11 @@ func TestCompressWithoutPreservingPath(t *testing.T) { logrus.SetLevel(logrus.DebugLevel) tarFilePath := filepath.Join(baseTmpDir, "res.tar.gz") - require.Nil(t, CompressWithoutPreservingPath(tarFilePath, compressDir)) + require.NoError(t, CompressWithoutPreservingPath(tarFilePath, compressDir)) require.FileExists(t, tarFilePath) res := []string{"1.txt", "2.bin", "3.md"} - require.Nil(t, iterateTarball( + require.NoError(t, iterateTarball( tarFilePath, func(_ *tar.Reader, header *tar.Header) (bool, error) { require.Equal(t, res[0], header.Name) res = res[1:] @@ -139,17 +139,17 @@ func TestExtract(t *testing.T) { 0x00, 0x00, } file, err := os.CreateTemp("", "tarball") - require.Nil(t, err) + require.NoError(t, err) defer os.Remove(file.Name()) _, err = file.Write(tarball) - require.Nil(t, err) + require.NoError(t, err) baseTmpDir, err := os.MkdirTemp("", "extract-") - require.Nil(t, err) - require.Nil(t, os.RemoveAll(baseTmpDir)) + require.NoError(t, err) + require.NoError(t, os.RemoveAll(baseTmpDir)) defer os.RemoveAll(baseTmpDir) - require.Nil(t, Extract(file.Name(), baseTmpDir)) + require.NoError(t, Extract(file.Name(), baseTmpDir)) res := []string{ filepath.Base(baseTmpDir), "1.txt", @@ -158,12 +158,12 @@ func TestExtract(t *testing.T) { "4.txt", "link", } - require.Nil(t, filepath.Walk( + require.NoError(t, filepath.Walk( baseTmpDir, func(_ string, fileInfo os.FileInfo, _ error) error { require.Equal(t, res[0], fileInfo.Name()) if res[0] == "link" { - require.True(t, fileInfo.Mode()&os.ModeSymlink == os.ModeSymlink) + require.Equal(t, os.ModeSymlink, fileInfo.Mode()&os.ModeSymlink) } res = res[1:] return nil @@ -173,7 +173,7 @@ func TestExtract(t *testing.T) { func TestReadFileFromGzippedTar(t *testing.T) { baseTmpDir, err := os.MkdirTemp("", "tar-read-file-") - require.Nil(t, err) + require.NoError(t, err) defer os.RemoveAll(baseTmpDir) const ( @@ -182,12 +182,12 @@ func TestReadFileFromGzippedTar(t *testing.T) { ) testTarPath := filepath.Join(baseTmpDir, "test.tar.gz") - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( filepath.Join(baseTmpDir, testFilePath), []byte(testFileContents), os.FileMode(0o644), )) - require.Nil(t, Compress(testTarPath, baseTmpDir, nil)) + require.NoError(t, Compress(testTarPath, baseTmpDir, nil)) type args struct { tarPath string @@ -222,10 +222,10 @@ func TestReadFileFromGzippedTar(t *testing.T) { r, err := ReadFileFromGzippedTar(tc.args.tarPath, tc.args.filePath) if tc.want.shouldErr { require.Nil(t, r) - require.NotNil(t, err) + require.Error(t, err) } else { file, err := io.ReadAll(r) - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, tc.want.fileContents, string(file)) } }) diff --git a/util/common.go b/util/common.go index 29b8646..2a112a3 100644 --- a/util/common.go +++ b/util/common.go @@ -45,23 +45,23 @@ var ( regexpGitToken = regexp.MustCompile(`git:[a-f0-9]{35,40}@github\.com`) ) -// UserInputError a custom error to handle more user input info +// UserInputError a custom error to handle more user input info. type UserInputError struct { ErrorString string isCtrlC bool } -// Error return the error string +// Error return the error string. func (e UserInputError) Error() string { return e.ErrorString } -// IsCtrlC return true if the user has hit Ctrl+C +// IsCtrlC return true if the user has hit Ctrl+C. func (e UserInputError) IsCtrlC() bool { return e.isCtrlC } -// NewUserInputError creates a new UserInputError +// NewUserInputError creates a new UserInputError. func NewUserInputError(message string, ctrlC bool) UserInputError { return UserInputError{ ErrorString: message, @@ -488,7 +488,7 @@ func Exists(path string) bool { return true } -// WrapText wraps a text +// WrapText wraps a text. func WrapText(originalText string, lineSize int) (wrappedText string) { words := strings.Fields(strings.TrimSpace(originalText)) wrappedText = words[0] @@ -507,7 +507,7 @@ func WrapText(originalText string, lineSize int) (wrappedText string) { } // StripControlCharacters takes a slice of bytes and removes control -// characters and bare line feeds (ported from the original bash anago) +// characters and bare line feeds (ported from the original bash anago). func StripControlCharacters(logData []byte) []byte { return regexpCRLF.ReplaceAllLiteral( regexpCtrlChar.ReplaceAllLiteral(logData, []byte{}), []byte{}, @@ -515,7 +515,7 @@ func StripControlCharacters(logData []byte) []byte { } // StripSensitiveData removes data deemed sensitive or non public -// from a byte slice (ported from the original bash anago) +// from a byte slice (ported from the original bash anago). func StripSensitiveData(logData []byte) []byte { // Remove OAuth tokens logData = regexpOauthToken.ReplaceAllLiteral(logData, []byte("__SANITIZED__:x-oauth-basic")) @@ -524,7 +524,7 @@ func StripSensitiveData(logData []byte) []byte { return logData } -// CleanLogFile cleans control characters and sensitive data from a file +// CleanLogFile cleans control characters and sensitive data from a file. func CleanLogFile(logPath string) (err error) { logrus.Debugf("Sanitizing logfile %s", logPath) diff --git a/util/common_test.go b/util/common_test.go index 29af825..baeb81a 100644 --- a/util/common_test.go +++ b/util/common_test.go @@ -36,7 +36,7 @@ func TestPackagesAvailableSuccess(t *testing.T) { for _, packages := range testcases { available, err := PackagesAvailable(packages...) - require.Nil(t, err) + require.NoError(t, err) require.True(t, available) } } @@ -60,18 +60,18 @@ func TestPackagesAvailableFailure(t *testing.T) { for _, packages := range testcases { actual, err := PackagesAvailable(packages...) - require.Nil(t, err) + require.NoError(t, err) require.False(t, actual) } } func TestMoreRecent(t *testing.T) { baseTmpDir, err := os.MkdirTemp("", "") - require.Nil(t, err) + require.NoError(t, err) // Create test files. testFileOne := filepath.Join(baseTmpDir, "testone.txt") - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( testFileOne, []byte("file-one-contents"), os.FileMode(0o644), @@ -80,7 +80,7 @@ func TestMoreRecent(t *testing.T) { time.Sleep(1 * time.Second) testFileTwo := filepath.Join(baseTmpDir, "testtwo.txt") - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( testFileTwo, []byte("file-two-contents"), os.FileMode(0o644), @@ -165,13 +165,13 @@ func TestMoreRecent(t *testing.T) { func TestCopyFile(t *testing.T) { srcDir, err := os.MkdirTemp("", "src") - require.Nil(t, err) + require.NoError(t, err) dstDir, err := os.MkdirTemp("", "dst") - require.Nil(t, err) + require.NoError(t, err) // Create test file. srcFileOnePath := filepath.Join(srcDir, "testone.txt") - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( srcFileOnePath, []byte("file-one-contents"), os.FileMode(0o644), @@ -221,9 +221,9 @@ func TestCopyFile(t *testing.T) { t.Run(name, func(t *testing.T) { copyErr := CopyFileLocal(tc.args.src, tc.args.dst, tc.args.required) if tc.shouldError { - require.NotNil(t, copyErr) + require.Error(t, copyErr) } else { - require.Nil(t, copyErr) + require.NoError(t, copyErr) } if copyErr == nil { _, err := os.Stat(tc.args.dst) @@ -237,20 +237,20 @@ func TestCopyFile(t *testing.T) { func TestCopyDirContentLocal(t *testing.T) { srcDir, err := os.MkdirTemp("", "src") - require.Nil(t, err) + require.NoError(t, err) dstDir, err := os.MkdirTemp("", "dst") - require.Nil(t, err) + require.NoError(t, err) // Create test file. srcFileOnePath := filepath.Join(srcDir, "testone.txt") - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( srcFileOnePath, []byte("file-one-contents"), os.FileMode(0o644), )) srcFileTwoPath := filepath.Join(srcDir, "testtwo.txt") - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( srcFileTwoPath, []byte("file-two-contents"), os.FileMode(0o644), @@ -300,18 +300,18 @@ func TestCopyDirContentLocal(t *testing.T) { func TestRemoveAndReplaceDir(t *testing.T) { dir, err := os.MkdirTemp("", "rm") - require.Nil(t, err) + require.NoError(t, err) // Create test file. fileOnePath := filepath.Join(dir, "testone.txt") - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( fileOnePath, []byte("file-one-contents"), os.FileMode(0o644), )) fileTwoPath := filepath.Join(dir, "testtwo.txt") - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( fileTwoPath, []byte("file-two-contents"), os.FileMode(0o644), @@ -357,11 +357,11 @@ func TestRemoveAndReplaceDir(t *testing.T) { func TestExist(t *testing.T) { dir, err := os.MkdirTemp("", "rm") - require.Nil(t, err) + require.NoError(t, err) // Create test file. fileOnePath := filepath.Join(dir, "testone.txt") - require.Nil(t, os.WriteFile( + require.NoError(t, os.WriteFile( fileOnePath, []byte("file-one-contents"), os.FileMode(0o644), @@ -422,29 +422,29 @@ func TestExist(t *testing.T) { } func cleanupTmp(t *testing.T, dir string) { - require.Nil(t, os.RemoveAll(dir)) + require.NoError(t, os.RemoveAll(dir)) } func TestTagStringToSemver(t *testing.T) { // Success version, err := TagStringToSemver("v1.2.3") - require.Nil(t, err) - require.Equal(t, version, semver.Version{Major: 1, Minor: 2, Patch: 3}) + require.NoError(t, err) + require.Equal(t, semver.Version{Major: 1, Minor: 2, Patch: 3}, version) // No Major.Minor.Patch elements found version, err = TagStringToSemver("invalid") - require.NotNil(t, err) - require.Equal(t, version, semver.Version{}) + require.Error(t, err) + require.Equal(t, semver.Version{}, version) // Version string empty version, err = TagStringToSemver("") - require.NotNil(t, err) - require.Equal(t, version, semver.Version{}) + require.Error(t, err) + require.Equal(t, semver.Version{}, version) } func TestSemverToTagString(t *testing.T) { version := semver.Version{Major: 1, Minor: 2, Patch: 3} - require.Equal(t, SemverToTagString(version), "v1.2.3") + require.Equal(t, "v1.2.3", SemverToTagString(version)) } func TestAddTagPrefix(t *testing.T) { @@ -550,17 +550,17 @@ func TestCleanLogFile(t *testing.T) { cleanLog := line1 + line2 + sanitizedTokenLine + line3 + line4 + line5 + "\n" logfile, err := os.CreateTemp("", "clean-log-test-") - require.Nil(t, err, "creating test logfile") + require.NoError(t, err, "creating test logfile") defer os.Remove(logfile.Name()) err = os.WriteFile(logfile.Name(), []byte(originalLog), os.FileMode(0o644)) - require.Nil(t, err, "writing test file") + require.NoError(t, err, "writing test file") // Now, run the cleanLogFile err = CleanLogFile(logfile.Name()) - require.Nil(t, err, "running log cleaner") + require.NoError(t, err, "running log cleaner") resultingData, err := os.ReadFile(logfile.Name()) - require.Nil(t, err, "reading modified file") + require.NoError(t, err, "reading modified file") require.NotEmpty(t, resultingData) // Must have changed diff --git a/version/command.go b/version/command.go index d916e93..d4d6bfe 100644 --- a/version/command.go +++ b/version/command.go @@ -27,7 +27,7 @@ import ( // // rootCmd.AddCommand(version.Version()) // -// ``` +// ```. func Version() *cobra.Command { return version("") } @@ -37,7 +37,7 @@ func Version() *cobra.Command { // // rootCmd.AddCommand(version.WithFont("starwars")) // -// ``` +// ```. func WithFont(fontName string) *cobra.Command { return version(fontName) } diff --git a/version/version.go b/version/version.go index 86de4f1..73a3cac 100644 --- a/version/version.go +++ b/version/version.go @@ -40,13 +40,13 @@ var ( // Output of "git describe". The prerequisite is that the // branch should be tagged using the correct versioning strategy. gitVersion = "devel" - // SHA1 from git, output of $(git rev-parse HEAD) + // SHA1 from git, output of $(git rev-parse HEAD). gitCommit = unknown - // State of git tree, either "clean" or "dirty" + // State of git tree, either "clean" or "dirty". gitTreeState = unknown - // Build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ') + // Build date in ISO8601 format, output of $(date -u +'%Y-%m-%dT%H:%M:%SZ'). buildDate = unknown - // flag to print the ascii name banner + // flag to print the ascii name banner. asciiName = "true" // goVersion is the used golang version. goVersion = unknown @@ -175,7 +175,7 @@ func GetVersionInfo() Info { return info } -// String returns the string representation of the version info +// String returns the string representation of the version info. func (i *Info) String() string { b := strings.Builder{} w := tabwriter.NewWriter(&b, 0, 0, 2, ' ', 0) @@ -205,7 +205,7 @@ func (i *Info) String() string { return b.String() } -// JSONString returns the JSON representation of the version info +// JSONString returns the JSON representation of the version info. func (i *Info) JSONString() (string, error) { b, err := json.MarshalIndent(i, "", " ") if err != nil { diff --git a/version/version_test.go b/version/version_test.go index a941e30..eaa166f 100644 --- a/version/version_test.go +++ b/version/version_test.go @@ -31,6 +31,6 @@ func TestVersionJSON(t *testing.T) { sut := GetVersionInfo() json, err := sut.JSONString() - require.Nil(t, err) + require.NoError(t, err) require.NotEmpty(t, json) }