Skip to content

Commit d97380b

Browse files
committed
Fix more linting warnings and errors
1 parent 9f6eb7e commit d97380b

File tree

183 files changed

+37384
-925
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

183 files changed

+37384
-925
lines changed

.golangci.yaml

+7-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1-
run:
2-
skip-dirs:
1+
issues:
2+
exclude-dirs:
33
- vendor
4+
exclude-rules:
5+
- linters:
6+
- staticcheck
7+
text: "SA9004"
48

59
linters-settings:
610
errcheck:
@@ -31,12 +35,10 @@ linters-settings:
3135
- (*github.com/ActiveState/cli/pkg/platform/runtime/artifactcache.testArtifactCache).Store
3236
- github.com/ActiveState/cli/internal/testhelpers/osutil.RemoveConfigFile
3337
- (*github.com/ActiveState/cli/internal/logging.standardHandler).Emit
38+
- (*github.com/ActiveState/cli/internal/logging.fileHandler).Emit
3439
govet:
3540
disable:
3641
- composites
37-
linters:
38-
disable:
39-
- errcheck
4042

4143
# When issues occur with linting us the snippet below to help with debugging
4244
# linters:

cmd/state-installer/cmd.go

+2-36
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ import (
3434
"github.com/ActiveState/cli/internal/subshell/bash"
3535
"github.com/ActiveState/cli/pkg/project"
3636
"github.com/ActiveState/cli/pkg/sysinfo"
37-
"golang.org/x/crypto/ssh/terminal"
37+
"golang.org/x/term"
3838
)
3939

4040
type Params struct {
@@ -424,7 +424,7 @@ func postInstallEvents(out output.Outputer, cfg *config.Instance, an analytics.D
424424
an.EventWithLabel(anaConst.CatInstallerFunnel, "forward-activate-default-err", err.Error())
425425
return errs.Silence(errs.Wrap(err, "Could not activate %s, error returned: %s", params.activateDefault.String(), errs.JoinMessage(err)))
426426
}
427-
case !params.isUpdate && terminal.IsTerminal(int(os.Stdin.Fd())) && os.Getenv(constants.InstallerNoSubshell) != "true" && os.Getenv("TERM") != "dumb":
427+
case !params.isUpdate && term.IsTerminal(int(os.Stdin.Fd())) && os.Getenv(constants.InstallerNoSubshell) != "true" && os.Getenv("TERM") != "dumb":
428428
if err := ss.SetEnv(osutils.InheritEnv(envMap(binPath))); err != nil {
429429
return locale.WrapError(err, "err_subshell_setenv")
430430
}
@@ -489,37 +489,3 @@ func assertCompatibility() error {
489489

490490
return nil
491491
}
492-
493-
func noArgs() bool {
494-
return len(os.Args[1:]) == 0
495-
}
496-
497-
func shouldUpdateInstalledStateTool(stateExePath string) bool {
498-
logging.Debug("Checking if installed state tool is an older version.")
499-
500-
stdout, _, err := osutils.ExecSimple(stateExePath, []string{"--version", "--output", "json"}, os.Environ())
501-
if err != nil {
502-
logging.Debug("Could not determine state tool version.")
503-
return true // probably corrupted install
504-
}
505-
stdout = strings.Split(stdout, "\x00")[0] // TODO: DX-328
506-
507-
versionData := installation.VersionData{}
508-
err = json.Unmarshal([]byte(stdout), &versionData)
509-
if err != nil {
510-
logging.Debug("Could not read state tool version output")
511-
return true
512-
}
513-
514-
if versionData.Channel != constants.ChannelName {
515-
logging.Debug("State tool channel is different from installer.")
516-
return false // do not update, require --force
517-
}
518-
519-
if versionData.Version != constants.Version {
520-
logging.Debug("State tool version is different from installer.")
521-
return true
522-
}
523-
524-
return false
525-
}

cmd/state-installer/installer.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package main
22

33
import (
44
"errors"
5-
"io/ioutil"
65
"os"
76
"path/filepath"
87
"strings"
@@ -194,7 +193,7 @@ func detectCorruptedInstallDir(path string) error {
194193
}
195194

196195
// Detect if the install dir has files in it
197-
files, err := ioutil.ReadDir(path)
196+
files, err := os.ReadDir(path)
198197
if err != nil {
199198
return errs.Wrap(err, "Could not read directory: %s", path)
200199
}

cmd/state-installer/installer_lin_mac.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
package main
55

66
import (
7-
"io/ioutil"
87
"os"
98
"path/filepath"
109
"strings"
@@ -18,7 +17,7 @@ func (i *Installer) sanitizeInstallPath() error {
1817
return nil
1918
}
2019

21-
files, err := ioutil.ReadDir(i.path)
20+
files, err := os.ReadDir(i.path)
2221
if err != nil {
2322
return errs.Wrap(err, "Could not installation directory: %s", i.path)
2423
}

cmd/state-installer/test/integration/installer_int_test.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,10 @@ func (suite *InstallerIntegrationTestSuite) TestInstallWhileInUse() {
262262
cp2.ExpectExit() // the return code can vary depending on shell (e.g. zsh vs. bash); just assert the installer shell exited
263263

264264
oldStateExeFound := false
265-
for _, file := range fileutils.ListDirSimple(filepath.Join(installationDir(ts), "bin"), false) {
265+
files, err := fileutils.ListDirSimple(filepath.Join(installationDir(ts), "bin"), false)
266+
suite.Require().NoError(err)
267+
268+
for _, file := range files {
266269
if strings.Contains(file, "state.exe") && strings.HasSuffix(file, ".old") {
267270
oldStateExeFound = true
268271
break

cmd/state-svc/autostart/autostart.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,14 @@ func RegisterConfigListener(cfg *config.Instance) error {
2525
configMediator.AddListener(constants.AutostartSvcConfigKey, func() {
2626
if cfg.GetBool(constants.AutostartSvcConfigKey) {
2727
logging.Debug("Enabling autostart")
28-
autostart.Enable(app.Path(), Options)
28+
if err := autostart.Enable(app.Path(), Options); err != nil {
29+
logging.Error("Failed to enable autostart: %s", err)
30+
}
2931
} else {
3032
logging.Debug("Disabling autostart")
31-
autostart.Disable(app.Path(), Options)
33+
if err := autostart.Disable(app.Path(), Options); err != nil {
34+
logging.Error("Failed to disable autostart: %s", err)
35+
}
3236
}
3337
})
3438

cmd/state-svc/internal/messages/messages.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,8 @@ func (m *Messages) Check(command string, flags []string) ([]*graph.MessageInfo,
7676
}
7777
allMessages := cacheValue.([]*graph.MessageInfo)
7878

79-
conditionParams := &(*m.baseParams) // copy
79+
// copy the base params
80+
conditionParams := &(*m.baseParams) //nolint:staticcheck
8081
conditionParams.UserEmail = m.auth.Email()
8182
conditionParams.UserName = m.auth.WhoAmI()
8283
conditionParams.Command = command

cmd/state-svc/test/integration/svc_int_test.go

+10-9
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package integration
22

33
import (
44
"fmt"
5-
"io/ioutil"
65
"net"
76
"os"
87
"path/filepath"
@@ -53,15 +52,15 @@ func (suite *SvcIntegrationTestSuite) TestStartStop() {
5352
cp.Expect("Checking")
5453

5554
// Verify the server is running on its reported port.
56-
cp.ExpectRe("Port:\\s+:\\d+\\s")
57-
portRe := regexp.MustCompile("Port:\\s+:(\\d+)")
55+
cp.ExpectRe(`Port:\s+:\d+\s`)
56+
portRe := regexp.MustCompile(`Port:\s+:(\d+)`)
5857
port := portRe.FindStringSubmatch(cp.Output())[1]
5958
_, err := net.Listen("tcp", "localhost:"+port)
6059
suite.Error(err)
6160

6261
// Verify it created and wrote to its reported log file.
63-
cp.ExpectRe("Log:\\s+.+?\\.log")
64-
logRe := regexp.MustCompile("Log:\\s+(.+?\\.log)")
62+
cp.ExpectRe(`Log:\s+(.+?\.log)`)
63+
logRe := regexp.MustCompile(`Log:\s+(.+?\.log)`)
6564
logFile := logRe.FindStringSubmatch(cp.Output())[1]
6665
suite.True(fileutils.FileExists(logFile), "log file '"+logFile+"' does not exist")
6766
suite.True(len(fileutils.ReadFileUnsafe(logFile)) > 0, "log file is empty")
@@ -99,7 +98,8 @@ func (suite *SvcIntegrationTestSuite) TestSignals() {
9998
cp := ts.SpawnCmdWithOpts(ts.SvcExe, e2e.OptArgs("foreground"))
10099
cp.Expect("Starting")
101100
time.Sleep(1 * time.Second) // wait for the service to start up
102-
cp.Cmd().Process.Signal(syscall.SIGINT)
101+
err := cp.Cmd().Process.Signal(syscall.SIGINT)
102+
suite.NoError(err)
103103
cp.Expect("caught a signal: interrupt")
104104
cp.ExpectNotExitCode(0)
105105

@@ -114,7 +114,8 @@ func (suite *SvcIntegrationTestSuite) TestSignals() {
114114
cp = ts.SpawnCmdWithOpts(ts.SvcExe, e2e.OptArgs("foreground"))
115115
cp.Expect("Starting")
116116
time.Sleep(1 * time.Second) // wait for the service to start up
117-
cp.Cmd().Process.Signal(syscall.SIGTERM)
117+
err = cp.Cmd().Process.Signal(syscall.SIGTERM)
118+
suite.NoError(err)
118119
suite.NotContains(cp.Output(), "caught a signal")
119120
cp.ExpectExitCode(0) // should exit gracefully
120121

@@ -257,7 +258,7 @@ func (suite *SvcIntegrationTestSuite) TestLogRotation() {
257258
time.Sleep(initialWait) // wait for state-svc to perform initial log rotation
258259

259260
// Verify the log rotation pruned the dummy log files.
260-
files, err := ioutil.ReadDir(logDir)
261+
files, err := os.ReadDir(logDir)
261262
suite.Require().NoError(err)
262263
remainingFooFiles := 0
263264
for _, file := range files {
@@ -281,7 +282,7 @@ func (suite *SvcIntegrationTestSuite) TestLogRotation() {
281282
time.Sleep(logRotateInterval - initialWait) // wait for another log rotation
282283

283284
// Verify that another log rotation pruned the dummy log files.
284-
files, err = ioutil.ReadDir(logDir)
285+
files, err = os.ReadDir(logDir)
285286
suite.Require().NoError(err)
286287
remainingFooFiles = 0
287288
for _, file := range files {

cmd/state/autoupdate.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,6 @@ func isFreshInstall() bool {
192192
multilog.Error("Could not stat file: %s, error: %v", exe, err)
193193
return true
194194
}
195-
diff := time.Now().Sub(stat.ModTime())
195+
diff := time.Since(stat.ModTime())
196196
return diff < 24*time.Hour
197197
}

cmd/state/internal/cmdtree/branch.go

-24
Original file line numberDiff line numberDiff line change
@@ -23,30 +23,6 @@ func newBranchCommand(prime *primer.Values) *captain.Command {
2323
}).SetGroup(PlatformGroup).SetSupportsStructuredOutput().SetUnstable(true)
2424
}
2525

26-
func newBranchAddCommand(prime *primer.Values) *captain.Command {
27-
runner := branch.NewAdd(prime)
28-
29-
params := branch.AddParams{}
30-
31-
return captain.NewCommand(
32-
"add",
33-
locale.Tl("add_title", "Adding branch"),
34-
locale.Tl("add_description", "Add a branch to your project"),
35-
prime,
36-
[]*captain.Flag{},
37-
[]*captain.Argument{
38-
{
39-
Name: locale.Tl("branch_arg_name", "name"),
40-
Description: locale.Tl("branch_arg_name_description", "Branch to be created"),
41-
Value: &params.Label,
42-
Required: true,
43-
},
44-
},
45-
func(_ *captain.Command, _ []string) error {
46-
return runner.Run(params)
47-
}).SetSupportsStructuredOutput()
48-
}
49-
5026
func newBranchSwitchCommand(prime *primer.Values) *captain.Command {
5127
runner := swtch.New(prime)
5228

cmd/state/main.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,13 @@ func run(args []string, isInteractive bool, cfg *config.Instance, out output.Out
207207

208208
conditional := constraints.NewPrimeConditional(auth, pj, sshell.Shell())
209209
project.RegisterConditional(conditional)
210-
project.RegisterExpander("mixin", project.NewMixin(auth).Expander)
211-
project.RegisterExpander("secrets", project.NewSecretPromptingExpander(secretsapi.Get(auth), prompter, cfg, auth))
210+
if err := project.RegisterExpander("mixin", project.NewMixin(auth).Expander); err != nil {
211+
logging.Debug("Could not register mixin expander: %v", err)
212+
}
213+
214+
if err := project.RegisterExpander("secrets", project.NewSecretPromptingExpander(secretsapi.Get(auth), prompter, cfg, auth)); err != nil {
215+
logging.Debug("Could not register secrets expander: %v", err)
216+
}
212217

213218
// Run the actual command
214219
cmds := cmdtree.New(primer.New(pj, out, auth, prompter, sshell, conditional, cfg, ipcClient, svcmodel, an), args...)

go.mod

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ require (
6565
golang.org/x/net v0.8.0
6666
golang.org/x/sys v0.12.0
6767
golang.org/x/term v0.6.0
68-
golang.org/x/text v0.8.0
68+
golang.org/x/text v0.14.0
6969
gopkg.in/AlecAivazis/survey.v1 v1.8.8
7070
gopkg.in/src-d/go-git.v4 v4.13.1
7171
gopkg.in/toast.v1 v1.0.0-20180812000517-0a84660828b2

go.sum

+2
Original file line numberDiff line numberDiff line change
@@ -1322,6 +1322,8 @@ golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
13221322
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
13231323
golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68=
13241324
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
1325+
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
1326+
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
13251327
golang.org/x/time v0.0.0-20220922220347-f3bd1da661af/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
13261328
golang.org/x/time v0.1.0 h1:xYY+Bajn2a7VBmTM5GikTmnK8ZuX8YgnQCqZpbBNtmA=
13271329
golang.org/x/time v0.1.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=

internal/analytics/client/sync/reporters/ga-state.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,9 @@ func (r *GaCLIReporter) Event(category, action, source, label string, d *dimensi
5353
r.ga.CustomDimensionMap(legacyDimensionMap(d))
5454

5555
if category == anaConsts.CatRunCmd {
56-
r.ga.Send(ga.NewPageview())
56+
if err := r.ga.Send(ga.NewPageview()); err != nil {
57+
return errs.Wrap(err, "Could not send GA Pageview")
58+
}
5759
}
5860
event := ga.NewEvent(category, action)
5961
if label != "" {

internal/captain/command.go

+4-5
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,9 @@ func NewHiddenShimCommand(name string, prime primer, flags []*Flag, args []*Argu
226226
}
227227

228228
cmd.cobra.SetHelpFunc(func(_ *cobra.Command, args []string) {
229-
cmd.execute(cmd, args)
229+
if err := cmd.execute(cmd, args); err != nil {
230+
panic(err)
231+
}
230232
})
231233

232234
if err := cmd.setFlags(flags); err != nil {
@@ -284,7 +286,7 @@ func (c *Command) ShortDescription() string {
284286
}
285287

286288
func (c *Command) Execute(args []string) error {
287-
defer profile.Measure(fmt.Sprintf("cobra:Execute"), time.Now())
289+
defer profile.Measure("cobra:Execute", time.Now())
288290
c.cobra.SetArgs(args)
289291
err := c.cobra.Execute()
290292
c.cobra.SetArgs(nil)
@@ -772,9 +774,6 @@ func (c *Command) outputTitleIfAny() {
772774
// setupSensibleErrors inspects an error value for certain errors and returns a
773775
// wrapped error that can be checked and that is localized.
774776
func setupSensibleErrors(err error, args []string) error {
775-
if err, ok := err.(error); ok && err == nil {
776-
return nil
777-
}
778777
if err == nil {
779778
return nil
780779
}

internal/captain/values.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ func (p *PackageValue) Set(s string) error {
151151
p.Version = strings.TrimSpace(v[1])
152152
s = v[0]
153153
}
154-
if strings.Index(s, "/") == -1 {
154+
if !strings.Contains(s, "/") {
155155
p.Name = strings.TrimSpace(s)
156156
return nil
157157
}

internal/colorize/color_test.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
//go:build !windows
12
// +build !windows
3+
24
// Can't test this on Windows since on Windows it sends process instructions to change colors
35

46
package colorize
@@ -57,7 +59,8 @@ func Test_writeColorized(t *testing.T) {
5759
for _, tt := range tests {
5860
t.Run(tt.name, func(t *testing.T) {
5961
writer := &bytes.Buffer{}
60-
Colorize(tt.value, writer, tt.strip)
62+
_, err := Colorize(tt.value, writer, tt.strip)
63+
assert.NoError(t, err, "Colorize failed")
6164
assert.Equal(t, tt.expected, writer.String(), "Output did not match")
6265
})
6366
}

internal/config/instance.go

+5-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package config
33
import (
44
"database/sql"
55
"encoding/json"
6-
"fmt"
76
"os"
87
"path/filepath"
98
"sync"
@@ -64,7 +63,7 @@ func NewCustom(localPath string, thread *singlethread.Thread, closeThread bool)
6463
isNew := err != nil
6564

6665
t := time.Now()
67-
i.db, err = sql.Open("sqlite", fmt.Sprintf(`%s`, path))
66+
i.db, err = sql.Open("sqlite", path)
6867
if err != nil {
6968
return nil, errs.Wrap(err, "Could not create sqlite connection to %s", path)
7069
}
@@ -211,7 +210,10 @@ func (i *Instance) AllKeys() []string {
211210
defer rows.Close()
212211
for rows.Next() {
213212
var key string
214-
rows.Scan(&key)
213+
if err = rows.Scan(&key); err != nil {
214+
multilog.Error("config:AllKeys scan failed: %s", errs.JoinMessage(err))
215+
return nil
216+
}
215217
keys = append(keys, key)
216218
}
217219
return keys

0 commit comments

Comments
 (0)