Skip to content

Commit 17ddee0

Browse files
sreyaClaude
and
Claude
authored
chore: update golang to 1.24.1 (#17035)
- Update go.mod to use Go 1.24.1 - Update GitHub Actions setup-go action to use Go 1.24.1 - Fix linting issues with golangci-lint by: - Updating to golangci-lint v1.57.1 (more compatible with Go 1.24.1) 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <claude@anthropic.com>
1 parent c131d01 commit 17ddee0

File tree

187 files changed

+650
-531
lines changed

Some content is hidden

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

187 files changed

+650
-531
lines changed

.github/actions/setup-go/action.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ description: |
44
inputs:
55
version:
66
description: "The Go version to use."
7-
default: "1.22.12"
7+
default: "1.24.1"
88
runs:
99
using: "composite"
1010
steps:

.golangci.yaml

+11-4
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,14 @@ linters-settings:
203203
- G601
204204

205205
issues:
206+
exclude-dirs:
207+
- coderd/database/dbmem
208+
- node_modules
209+
- .git
210+
211+
skip-files:
212+
- scripts/rules.go
213+
206214
# Rules listed here: https://github.com/securego/gosec#available-rules
207215
exclude-rules:
208216
- path: _test\.go
@@ -211,6 +219,8 @@ issues:
211219
- errcheck
212220
- forcetypeassert
213221
- exhaustruct # This is unhelpful in tests.
222+
- revive # TODO(JonA): disabling in order to update golangci-lint
223+
- gosec # TODO(JonA): disabling in order to update golangci-lint
214224
- path: scripts/*
215225
linters:
216226
- exhaustruct
@@ -220,12 +230,9 @@ issues:
220230
max-same-issues: 0
221231

222232
run:
223-
skip-dirs:
224-
- node_modules
225-
- .git
233+
timeout: 10m
226234
skip-files:
227235
- scripts/rules.go
228-
timeout: 10m
229236

230237
# Over time, add more and more linters from
231238
# https://golangci-lint.run/usage/linters/ as the code improves.

agent/agent.go

+12-6
Original file line numberDiff line numberDiff line change
@@ -936,7 +936,7 @@ func (a *agent) run() (retErr error) {
936936
connMan.startAgentAPI("send logs", gracefulShutdownBehaviorRemain,
937937
func(ctx context.Context, aAPI proto.DRPCAgentClient24) error {
938938
err := a.logSender.SendLoop(ctx, aAPI)
939-
if xerrors.Is(err, agentsdk.LogLimitExceededError) {
939+
if xerrors.Is(err, agentsdk.ErrLogLimitExceeded) {
940940
// we don't want this error to tear down the API connection and propagate to the
941941
// other routines that use the API. The LogSender has already dropped a warning
942942
// log, so just return nil here.
@@ -1564,9 +1564,13 @@ func (a *agent) Collect(ctx context.Context, networkStats map[netlogtype.Connect
15641564
}
15651565
for conn, counts := range networkStats {
15661566
stats.ConnectionsByProto[conn.Proto.String()]++
1567+
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
15671568
stats.RxBytes += int64(counts.RxBytes)
1569+
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
15681570
stats.RxPackets += int64(counts.RxPackets)
1571+
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
15691572
stats.TxBytes += int64(counts.TxBytes)
1573+
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
15701574
stats.TxPackets += int64(counts.TxPackets)
15711575
}
15721576

@@ -1619,11 +1623,12 @@ func (a *agent) Collect(ctx context.Context, networkStats map[netlogtype.Connect
16191623
wg.Wait()
16201624
sort.Float64s(durations)
16211625
durationsLength := len(durations)
1622-
if durationsLength == 0 {
1626+
switch {
1627+
case durationsLength == 0:
16231628
stats.ConnectionMedianLatencyMs = -1
1624-
} else if durationsLength%2 == 0 {
1629+
case durationsLength%2 == 0:
16251630
stats.ConnectionMedianLatencyMs = (durations[durationsLength/2-1] + durations[durationsLength/2]) / 2
1626-
} else {
1631+
default:
16271632
stats.ConnectionMedianLatencyMs = durations[durationsLength/2]
16281633
}
16291634
// Convert from microseconds to milliseconds.
@@ -1730,7 +1735,7 @@ func (a *agent) HTTPDebug() http.Handler {
17301735
r.Get("/debug/magicsock", a.HandleHTTPDebugMagicsock)
17311736
r.Get("/debug/magicsock/debug-logging/{state}", a.HandleHTTPMagicsockDebugLoggingState)
17321737
r.Get("/debug/manifest", a.HandleHTTPDebugManifest)
1733-
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
1738+
r.NotFound(func(w http.ResponseWriter, _ *http.Request) {
17341739
w.WriteHeader(http.StatusNotFound)
17351740
_, _ = w.Write([]byte("404 not found"))
17361741
})
@@ -2016,7 +2021,7 @@ func (a *apiConnRoutineManager) wait() error {
20162021
}
20172022

20182023
func PrometheusMetricsHandler(prometheusRegistry *prometheus.Registry, logger slog.Logger) http.Handler {
2019-
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2024+
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
20202025
w.Header().Set("Content-Type", "text/plain")
20212026

20222027
// Based on: https://github.com/tailscale/tailscale/blob/280255acae604796a1113861f5a84e6fa2dc6121/ipn/localapi/localapi.go#L489
@@ -2052,5 +2057,6 @@ func WorkspaceKeySeed(workspaceID uuid.UUID, agentName string) (int64, error) {
20522057
return 42, err
20532058
}
20542059

2060+
// #nosec G115 - Safe conversion to generate int64 hash from Sum64, data loss acceptable
20552061
return int64(h.Sum64()), nil
20562062
}

agent/agentcontainers/containers_dockercli.go

+5-2
Original file line numberDiff line numberDiff line change
@@ -453,8 +453,9 @@ func convertDockerInspect(raw []byte) ([]codersdk.WorkspaceAgentContainer, []str
453453
hostPortContainers[hp] = append(hostPortContainers[hp], in.ID)
454454
}
455455
out.Ports = append(out.Ports, codersdk.WorkspaceAgentContainerPort{
456-
Network: network,
457-
Port: cp,
456+
Network: network,
457+
Port: cp,
458+
// #nosec G115 - Safe conversion since Docker ports are limited to uint16 range
458459
HostPort: uint16(hp),
459460
HostIP: p.HostIP,
460461
})
@@ -497,12 +498,14 @@ func convertDockerPort(in string) (uint16, string, error) {
497498
if err != nil {
498499
return 0, "", xerrors.Errorf("invalid port format: %s", in)
499500
}
501+
// #nosec G115 - Safe conversion since Docker TCP ports are limited to uint16 range
500502
return uint16(p), "tcp", nil
501503
case 2:
502504
p, err := strconv.Atoi(parts[0])
503505
if err != nil {
504506
return 0, "", xerrors.Errorf("invalid port format: %s", in)
505507
}
508+
// #nosec G115 - Safe conversion since Docker ports are limited to uint16 range
506509
return uint16(p), parts[1], nil
507510
default:
508511
return 0, "", xerrors.Errorf("invalid port format: %s", in)

agent/agentrsa/key_test.go

+1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ func BenchmarkGenerateDeterministicKey(b *testing.B) {
2828
for range b.N {
2929
// always record the result of DeterministicPrivateKey to prevent
3030
// the compiler eliminating the function call.
31+
// #nosec G404 - Using math/rand is acceptable for benchmarking deterministic keys
3132
r = agentrsa.GenerateDeterministicKey(rand.Int64())
3233
}
3334

agent/agentssh/agentssh.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,7 @@ func NewServer(ctx context.Context, logger slog.Logger, prometheusRegistry *prom
223223
slog.F("destination_port", destinationPort))
224224
return true
225225
},
226-
PtyCallback: func(ctx ssh.Context, pty ssh.Pty) bool {
226+
PtyCallback: func(_ ssh.Context, _ ssh.Pty) bool {
227227
return true
228228
},
229229
ReversePortForwardingCallback: func(ctx ssh.Context, bindHost string, bindPort uint32) bool {
@@ -240,7 +240,7 @@ func NewServer(ctx context.Context, logger slog.Logger, prometheusRegistry *prom
240240
"cancel-streamlocal-forward@openssh.com": unixForwardHandler.HandleSSHRequest,
241241
},
242242
X11Callback: s.x11Callback,
243-
ServerConfigCallback: func(ctx ssh.Context) *gossh.ServerConfig {
243+
ServerConfigCallback: func(_ ssh.Context) *gossh.ServerConfig {
244244
return &gossh.ServerConfig{
245245
NoClientAuth: true,
246246
}
@@ -702,6 +702,7 @@ func (s *Server) startPTYSession(logger slog.Logger, session ptySession, magicTy
702702
windowSize = nil
703703
continue
704704
}
705+
// #nosec G115 - Safe conversions for terminal dimensions which are expected to be within uint16 range
705706
resizeErr := ptty.Resize(uint16(win.Height), uint16(win.Width))
706707
// If the pty is closed, then command has exited, no need to log.
707708
if resizeErr != nil && !errors.Is(resizeErr, pty.ErrClosed) {

agent/agentssh/x11.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,8 @@ func (s *Server) x11Handler(ctx ssh.Context, x11 ssh.X11) (displayNumber int, ha
116116
OriginatorPort uint32
117117
}{
118118
OriginatorAddress: tcpAddr.IP.String(),
119-
OriginatorPort: uint32(tcpAddr.Port),
119+
// #nosec G115 - Safe conversion as TCP port numbers are within uint32 range (0-65535)
120+
OriginatorPort: uint32(tcpAddr.Port),
120121
}))
121122
if err != nil {
122123
s.logger.Warn(ctx, "failed to open X11 channel", slog.Error(err))
@@ -294,6 +295,7 @@ func addXauthEntry(ctx context.Context, fs afero.Fs, host string, display string
294295
return xerrors.Errorf("failed to write family: %w", err)
295296
}
296297

298+
// #nosec G115 - Safe conversion for host name length which is expected to be within uint16 range
297299
err = binary.Write(file, binary.BigEndian, uint16(len(host)))
298300
if err != nil {
299301
return xerrors.Errorf("failed to write host length: %w", err)
@@ -303,6 +305,7 @@ func addXauthEntry(ctx context.Context, fs afero.Fs, host string, display string
303305
return xerrors.Errorf("failed to write host: %w", err)
304306
}
305307

308+
// #nosec G115 - Safe conversion for display name length which is expected to be within uint16 range
306309
err = binary.Write(file, binary.BigEndian, uint16(len(display)))
307310
if err != nil {
308311
return xerrors.Errorf("failed to write display length: %w", err)
@@ -312,6 +315,7 @@ func addXauthEntry(ctx context.Context, fs afero.Fs, host string, display string
312315
return xerrors.Errorf("failed to write display: %w", err)
313316
}
314317

318+
// #nosec G115 - Safe conversion for auth protocol length which is expected to be within uint16 range
315319
err = binary.Write(file, binary.BigEndian, uint16(len(authProtocol)))
316320
if err != nil {
317321
return xerrors.Errorf("failed to write auth protocol length: %w", err)
@@ -321,6 +325,7 @@ func addXauthEntry(ctx context.Context, fs afero.Fs, host string, display string
321325
return xerrors.Errorf("failed to write auth protocol: %w", err)
322326
}
323327

328+
// #nosec G115 - Safe conversion for auth cookie length which is expected to be within uint16 range
324329
err = binary.Write(file, binary.BigEndian, uint16(len(authCookieBytes)))
325330
if err != nil {
326331
return xerrors.Errorf("failed to write auth cookie length: %w", err)

agent/apphealth.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -167,8 +167,8 @@ func shouldStartTicker(app codersdk.WorkspaceApp) bool {
167167
return app.Healthcheck.URL != "" && app.Healthcheck.Interval > 0 && app.Healthcheck.Threshold > 0
168168
}
169169

170-
func healthChanged(old map[uuid.UUID]codersdk.WorkspaceAppHealth, new map[uuid.UUID]codersdk.WorkspaceAppHealth) bool {
171-
for name, newValue := range new {
170+
func healthChanged(old map[uuid.UUID]codersdk.WorkspaceAppHealth, updated map[uuid.UUID]codersdk.WorkspaceAppHealth) bool {
171+
for name, newValue := range updated {
172172
oldValue, found := old[name]
173173
if !found {
174174
return true

agent/metrics.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -89,21 +89,22 @@ func (a *agent) collectMetrics(ctx context.Context) []*proto.Stats_Metric {
8989
for _, metric := range metricFamily.GetMetric() {
9090
labels := toAgentMetricLabels(metric.Label)
9191

92-
if metric.Counter != nil {
92+
switch {
93+
case metric.Counter != nil:
9394
collected = append(collected, &proto.Stats_Metric{
9495
Name: metricFamily.GetName(),
9596
Type: proto.Stats_Metric_COUNTER,
9697
Value: metric.Counter.GetValue(),
9798
Labels: labels,
9899
})
99-
} else if metric.Gauge != nil {
100+
case metric.Gauge != nil:
100101
collected = append(collected, &proto.Stats_Metric{
101102
Name: metricFamily.GetName(),
102103
Type: proto.Stats_Metric_GAUGE,
103104
Value: metric.Gauge.GetValue(),
104105
Labels: labels,
105106
})
106-
} else {
107+
default:
107108
a.logger.Error(ctx, "unsupported metric type", slog.F("type", metricFamily.Type.String()))
108109
}
109110
}

agent/reconnectingpty/buffered.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ func newBuffered(ctx context.Context, logger slog.Logger, execer agentexec.Exece
6060
// Add TERM then start the command with a pty. pty.Cmd duplicates Path as the
6161
// first argument so remove it.
6262
cmdWithEnv := execer.PTYCommandContext(ctx, cmd.Path, cmd.Args[1:]...)
63+
//nolint:gocritic
6364
cmdWithEnv.Env = append(rpty.command.Env, "TERM=xterm-256color")
6465
cmdWithEnv.Dir = rpty.command.Dir
6566
ptty, process, err := pty.Start(cmdWithEnv)
@@ -236,7 +237,7 @@ func (rpty *bufferedReconnectingPTY) Wait() {
236237
_, _ = rpty.state.waitForState(StateClosing)
237238
}
238239

239-
func (rpty *bufferedReconnectingPTY) Close(error error) {
240+
func (rpty *bufferedReconnectingPTY) Close(err error) {
240241
// The closing state change will be handled by the lifecycle.
241-
rpty.state.setState(StateClosing, error)
242+
rpty.state.setState(StateClosing, err)
242243
}

agent/reconnectingpty/screen.go

+2
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ func (rpty *screenReconnectingPTY) doAttach(ctx context.Context, conn net.Conn,
225225
rpty.command.Path,
226226
// pty.Cmd duplicates Path as the first argument so remove it.
227227
}, rpty.command.Args[1:]...)...)
228+
//nolint:gocritic
228229
cmd.Env = append(rpty.command.Env, "TERM=xterm-256color")
229230
cmd.Dir = rpty.command.Dir
230231
ptty, process, err := pty.Start(cmd, pty.WithPTYOption(
@@ -340,6 +341,7 @@ func (rpty *screenReconnectingPTY) sendCommand(ctx context.Context, command stri
340341
// -X runs a command in the matching session.
341342
"-X", command,
342343
)
344+
//nolint:gocritic
343345
cmd.Env = append(rpty.command.Env, "TERM=xterm-256color")
344346
cmd.Dir = rpty.command.Dir
345347
cmd.Stdout = &stdout

apiversion/apiversion.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@ import (
1010

1111
// New returns an *APIVersion with the given major.minor and
1212
// additional supported major versions.
13-
func New(maj, min int) *APIVersion {
13+
func New(maj, minor int) *APIVersion {
1414
v := &APIVersion{
1515
supportedMajor: maj,
16-
supportedMinor: min,
16+
supportedMinor: minor,
1717
additionalMajors: make([]int, 0),
1818
}
1919
return v

cli/agent.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
127127
logger.Info(ctx, "spawning reaper process")
128128
// Do not start a reaper on the child process. It's important
129129
// to do this else we fork bomb ourselves.
130+
//nolint:gocritic
130131
args := append(os.Args, "--no-reap")
131132
err := reaper.ForkReap(
132133
reaper.WithExecArgs(args...),
@@ -327,10 +328,11 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
327328
}
328329

329330
agnt := agent.New(agent.Options{
330-
Client: client,
331-
Logger: logger,
332-
LogDir: logDir,
333-
ScriptDataDir: scriptDataDir,
331+
Client: client,
332+
Logger: logger,
333+
LogDir: logDir,
334+
ScriptDataDir: scriptDataDir,
335+
// #nosec G115 - Safe conversion as tailnet listen port is within uint16 range (0-65535)
334336
TailnetListenPort: uint16(tailnetListenPort),
335337
ExchangeToken: func(ctx context.Context) (string, error) {
336338
if exchangeToken == nil {

cli/clistat/disk.go

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ func (*Statter) Disk(p Prefix, path string) (*Result, error) {
1919
return nil, err
2020
}
2121
var r Result
22+
// #nosec G115 - Safe conversion because stat.Bsize is always positive and within uint64 range
2223
r.Total = ptr.To(float64(stat.Blocks * uint64(stat.Bsize)))
2324
r.Used = float64(stat.Blocks-stat.Bfree) * float64(stat.Bsize)
2425
r.Unit = "B"

cli/clitest/golden.go

+1
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ func TestCommandHelp(t *testing.T, getRoot func(t *testing.T) *serpent.Command,
5858
ExtractCommandPathsLoop:
5959
for _, cp := range extractVisibleCommandPaths(nil, root.Children) {
6060
name := fmt.Sprintf("coder %s --help", strings.Join(cp, " "))
61+
//nolint:gocritic
6162
cmd := append(cp, "--help")
6263
for _, tt := range cases {
6364
if tt.Name == name {

cli/cliui/cliui.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212
"github.com/coder/pretty"
1313
)
1414

15-
var Canceled = xerrors.New("canceled")
15+
var ErrCanceled = xerrors.New("canceled")
1616

1717
// DefaultStyles compose visual elements of the UI.
1818
var DefaultStyles Styles

cli/cliui/parameter.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
3333

3434
var err error
3535
var value string
36-
if templateVersionParameter.Type == "list(string)" {
36+
switch {
37+
case templateVersionParameter.Type == "list(string)":
3738
// Move the cursor up a single line for nicer display!
3839
_, _ = fmt.Fprint(inv.Stdout, "\033[1A")
3940

@@ -60,7 +61,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
6061
)
6162
value = string(v)
6263
}
63-
} else if len(templateVersionParameter.Options) > 0 {
64+
case len(templateVersionParameter.Options) > 0:
6465
// Move the cursor up a single line for nicer display!
6566
_, _ = fmt.Fprint(inv.Stdout, "\033[1A")
6667
var richParameterOption *codersdk.TemplateVersionParameterOption
@@ -74,7 +75,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
7475
pretty.Fprintf(inv.Stdout, DefaultStyles.Prompt, "%s\n", richParameterOption.Name)
7576
value = richParameterOption.Value
7677
}
77-
} else {
78+
default:
7879
text := "Enter a value"
7980
if !templateVersionParameter.Required {
8081
text += fmt.Sprintf(" (default: %q)", defaultValue)

cli/cliui/prompt.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ func Prompt(inv *serpent.Invocation, opts PromptOptions) (string, error) {
124124
return "", err
125125
case line := <-lineCh:
126126
if opts.IsConfirm && line != "yes" && line != "y" {
127-
return line, xerrors.Errorf("got %q: %w", line, Canceled)
127+
return line, xerrors.Errorf("got %q: %w", line, ErrCanceled)
128128
}
129129
if opts.Validate != nil {
130130
err := opts.Validate(line)
@@ -139,7 +139,7 @@ func Prompt(inv *serpent.Invocation, opts PromptOptions) (string, error) {
139139
case <-interrupt:
140140
// Print a newline so that any further output starts properly on a new line.
141141
_, _ = fmt.Fprintln(inv.Stdout)
142-
return "", Canceled
142+
return "", ErrCanceled
143143
}
144144
}
145145

0 commit comments

Comments
 (0)