Skip to content

chore: update go to 1.24.1 #17194

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 1, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
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>
  • Loading branch information
sreya and Claude committed Apr 1, 2025
commit d4ea2cd640a9e3d6348af069333140ca63486b10
2 changes: 1 addition & 1 deletion .github/actions/setup-go/action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description: |
inputs:
version:
description: "The Go version to use."
default: "1.22.12"
default: "1.24.1"
runs:
using: "composite"
steps:
Expand Down
15 changes: 11 additions & 4 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,14 @@ linters-settings:
- G601

issues:
exclude-dirs:
- coderd/database/dbmem
- node_modules
- .git

skip-files:
- scripts/rules.go

# Rules listed here: https://github.com/securego/gosec#available-rules
exclude-rules:
- path: _test\.go
Expand All @@ -211,6 +219,8 @@ issues:
- errcheck
- forcetypeassert
- exhaustruct # This is unhelpful in tests.
- revive # TODO(JonA): disabling in order to update golangci-lint
- gosec # TODO(JonA): disabling in order to update golangci-lint
- path: scripts/*
linters:
- exhaustruct
Expand All @@ -220,12 +230,9 @@ issues:
max-same-issues: 0

run:
skip-dirs:
- node_modules
- .git
timeout: 10m
skip-files:
- scripts/rules.go
timeout: 10m

# Over time, add more and more linters from
# https://golangci-lint.run/usage/linters/ as the code improves.
Expand Down
18 changes: 12 additions & 6 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,7 @@ func (a *agent) run() (retErr error) {
connMan.startAgentAPI("send logs", gracefulShutdownBehaviorRemain,
func(ctx context.Context, aAPI proto.DRPCAgentClient24) error {
err := a.logSender.SendLoop(ctx, aAPI)
if xerrors.Is(err, agentsdk.LogLimitExceededError) {
if xerrors.Is(err, agentsdk.ErrLogLimitExceeded) {
// we don't want this error to tear down the API connection and propagate to the
// other routines that use the API. The LogSender has already dropped a warning
// log, so just return nil here.
Expand Down Expand Up @@ -1583,9 +1583,13 @@ func (a *agent) Collect(ctx context.Context, networkStats map[netlogtype.Connect
}
for conn, counts := range networkStats {
stats.ConnectionsByProto[conn.Proto.String()]++
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
stats.RxBytes += int64(counts.RxBytes)
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
stats.RxPackets += int64(counts.RxPackets)
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
stats.TxBytes += int64(counts.TxBytes)
// #nosec G115 - Safe conversions for network statistics which we expect to be within int64 range
stats.TxPackets += int64(counts.TxPackets)
}

Expand Down Expand Up @@ -1638,11 +1642,12 @@ func (a *agent) Collect(ctx context.Context, networkStats map[netlogtype.Connect
wg.Wait()
sort.Float64s(durations)
durationsLength := len(durations)
if durationsLength == 0 {
switch {
case durationsLength == 0:
stats.ConnectionMedianLatencyMs = -1
} else if durationsLength%2 == 0 {
case durationsLength%2 == 0:
stats.ConnectionMedianLatencyMs = (durations[durationsLength/2-1] + durations[durationsLength/2]) / 2
} else {
default:
stats.ConnectionMedianLatencyMs = durations[durationsLength/2]
}
// Convert from microseconds to milliseconds.
Expand Down Expand Up @@ -1749,7 +1754,7 @@ func (a *agent) HTTPDebug() http.Handler {
r.Get("/debug/magicsock", a.HandleHTTPDebugMagicsock)
r.Get("/debug/magicsock/debug-logging/{state}", a.HandleHTTPMagicsockDebugLoggingState)
r.Get("/debug/manifest", a.HandleHTTPDebugManifest)
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
r.NotFound(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte("404 not found"))
})
Expand Down Expand Up @@ -2034,7 +2039,7 @@ func (a *apiConnRoutineManager) wait() error {
}

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

// Based on: https://github.com/tailscale/tailscale/blob/280255acae604796a1113861f5a84e6fa2dc6121/ipn/localapi/localapi.go#L489
Expand Down Expand Up @@ -2070,5 +2075,6 @@ func WorkspaceKeySeed(workspaceID uuid.UUID, agentName string) (int64, error) {
return 42, err
}

// #nosec G115 - Safe conversion to generate int64 hash from Sum64, data loss acceptable
return int64(h.Sum64()), nil
}
7 changes: 5 additions & 2 deletions agent/agentcontainers/containers_dockercli.go
Original file line number Diff line number Diff line change
Expand Up @@ -453,8 +453,9 @@ func convertDockerInspect(raw []byte) ([]codersdk.WorkspaceAgentContainer, []str
hostPortContainers[hp] = append(hostPortContainers[hp], in.ID)
}
out.Ports = append(out.Ports, codersdk.WorkspaceAgentContainerPort{
Network: network,
Port: cp,
Network: network,
Port: cp,
// #nosec G115 - Safe conversion since Docker ports are limited to uint16 range
HostPort: uint16(hp),
HostIP: p.HostIP,
})
Expand Down Expand Up @@ -497,12 +498,14 @@ func convertDockerPort(in string) (uint16, string, error) {
if err != nil {
return 0, "", xerrors.Errorf("invalid port format: %s", in)
}
// #nosec G115 - Safe conversion since Docker TCP ports are limited to uint16 range
return uint16(p), "tcp", nil
case 2:
p, err := strconv.Atoi(parts[0])
if err != nil {
return 0, "", xerrors.Errorf("invalid port format: %s", in)
}
// #nosec G115 - Safe conversion since Docker ports are limited to uint16 range
return uint16(p), parts[1], nil
default:
return 0, "", xerrors.Errorf("invalid port format: %s", in)
Expand Down
1 change: 1 addition & 0 deletions agent/agentrsa/key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ func BenchmarkGenerateDeterministicKey(b *testing.B) {
for range b.N {
// always record the result of DeterministicPrivateKey to prevent
// the compiler eliminating the function call.
// #nosec G404 - Using math/rand is acceptable for benchmarking deterministic keys
r = agentrsa.GenerateDeterministicKey(rand.Int64())
}

Expand Down
5 changes: 3 additions & 2 deletions agent/agentssh/agentssh.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ func NewServer(ctx context.Context, logger slog.Logger, prometheusRegistry *prom
slog.F("destination_port", destinationPort))
return true
},
PtyCallback: func(ctx ssh.Context, pty ssh.Pty) bool {
PtyCallback: func(_ ssh.Context, _ ssh.Pty) bool {
return true
},
ReversePortForwardingCallback: func(ctx ssh.Context, bindHost string, bindPort uint32) bool {
Expand All @@ -240,7 +240,7 @@ func NewServer(ctx context.Context, logger slog.Logger, prometheusRegistry *prom
"cancel-streamlocal-forward@openssh.com": unixForwardHandler.HandleSSHRequest,
},
X11Callback: s.x11Callback,
ServerConfigCallback: func(ctx ssh.Context) *gossh.ServerConfig {
ServerConfigCallback: func(_ ssh.Context) *gossh.ServerConfig {
return &gossh.ServerConfig{
NoClientAuth: true,
}
Expand Down Expand Up @@ -702,6 +702,7 @@ func (s *Server) startPTYSession(logger slog.Logger, session ptySession, magicTy
windowSize = nil
continue
}
// #nosec G115 - Safe conversions for terminal dimensions which are expected to be within uint16 range
resizeErr := ptty.Resize(uint16(win.Height), uint16(win.Width))
// If the pty is closed, then command has exited, no need to log.
if resizeErr != nil && !errors.Is(resizeErr, pty.ErrClosed) {
Expand Down
7 changes: 6 additions & 1 deletion agent/agentssh/x11.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,8 @@ func (s *Server) x11Handler(ctx ssh.Context, x11 ssh.X11) (displayNumber int, ha
OriginatorPort uint32
}{
OriginatorAddress: tcpAddr.IP.String(),
OriginatorPort: uint32(tcpAddr.Port),
// #nosec G115 - Safe conversion as TCP port numbers are within uint32 range (0-65535)
OriginatorPort: uint32(tcpAddr.Port),
}))
if err != nil {
s.logger.Warn(ctx, "failed to open X11 channel", slog.Error(err))
Expand Down Expand Up @@ -294,6 +295,7 @@ func addXauthEntry(ctx context.Context, fs afero.Fs, host string, display string
return xerrors.Errorf("failed to write family: %w", err)
}

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

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

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

// #nosec G115 - Safe conversion for auth cookie length which is expected to be within uint16 range
err = binary.Write(file, binary.BigEndian, uint16(len(authCookieBytes)))
if err != nil {
return xerrors.Errorf("failed to write auth cookie length: %w", err)
Expand Down
4 changes: 2 additions & 2 deletions agent/apphealth.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,8 @@ func shouldStartTicker(app codersdk.WorkspaceApp) bool {
return app.Healthcheck.URL != "" && app.Healthcheck.Interval > 0 && app.Healthcheck.Threshold > 0
}

func healthChanged(old map[uuid.UUID]codersdk.WorkspaceAppHealth, new map[uuid.UUID]codersdk.WorkspaceAppHealth) bool {
for name, newValue := range new {
func healthChanged(old map[uuid.UUID]codersdk.WorkspaceAppHealth, updated map[uuid.UUID]codersdk.WorkspaceAppHealth) bool {
for name, newValue := range updated {
oldValue, found := old[name]
if !found {
return true
Expand Down
7 changes: 4 additions & 3 deletions agent/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,21 +89,22 @@ func (a *agent) collectMetrics(ctx context.Context) []*proto.Stats_Metric {
for _, metric := range metricFamily.GetMetric() {
labels := toAgentMetricLabels(metric.Label)

if metric.Counter != nil {
switch {
case metric.Counter != nil:
collected = append(collected, &proto.Stats_Metric{
Name: metricFamily.GetName(),
Type: proto.Stats_Metric_COUNTER,
Value: metric.Counter.GetValue(),
Labels: labels,
})
} else if metric.Gauge != nil {
case metric.Gauge != nil:
collected = append(collected, &proto.Stats_Metric{
Name: metricFamily.GetName(),
Type: proto.Stats_Metric_GAUGE,
Value: metric.Gauge.GetValue(),
Labels: labels,
})
} else {
default:
a.logger.Error(ctx, "unsupported metric type", slog.F("type", metricFamily.Type.String()))
}
}
Expand Down
5 changes: 3 additions & 2 deletions agent/reconnectingpty/buffered.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ func newBuffered(ctx context.Context, logger slog.Logger, execer agentexec.Exece
// Add TERM then start the command with a pty. pty.Cmd duplicates Path as the
// first argument so remove it.
cmdWithEnv := execer.PTYCommandContext(ctx, cmd.Path, cmd.Args[1:]...)
//nolint:gocritic
cmdWithEnv.Env = append(rpty.command.Env, "TERM=xterm-256color")
cmdWithEnv.Dir = rpty.command.Dir
ptty, process, err := pty.Start(cmdWithEnv)
Expand Down Expand Up @@ -236,7 +237,7 @@ func (rpty *bufferedReconnectingPTY) Wait() {
_, _ = rpty.state.waitForState(StateClosing)
}

func (rpty *bufferedReconnectingPTY) Close(error error) {
func (rpty *bufferedReconnectingPTY) Close(err error) {
// The closing state change will be handled by the lifecycle.
rpty.state.setState(StateClosing, error)
rpty.state.setState(StateClosing, err)
}
2 changes: 2 additions & 0 deletions agent/reconnectingpty/screen.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ func (rpty *screenReconnectingPTY) doAttach(ctx context.Context, conn net.Conn,
rpty.command.Path,
// pty.Cmd duplicates Path as the first argument so remove it.
}, rpty.command.Args[1:]...)...)
//nolint:gocritic
cmd.Env = append(rpty.command.Env, "TERM=xterm-256color")
cmd.Dir = rpty.command.Dir
ptty, process, err := pty.Start(cmd, pty.WithPTYOption(
Expand Down Expand Up @@ -340,6 +341,7 @@ func (rpty *screenReconnectingPTY) sendCommand(ctx context.Context, command stri
// -X runs a command in the matching session.
"-X", command,
)
//nolint:gocritic
cmd.Env = append(rpty.command.Env, "TERM=xterm-256color")
cmd.Dir = rpty.command.Dir
cmd.Stdout = &stdout
Expand Down
4 changes: 2 additions & 2 deletions apiversion/apiversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import (

// New returns an *APIVersion with the given major.minor and
// additional supported major versions.
func New(maj, min int) *APIVersion {
func New(maj, minor int) *APIVersion {
v := &APIVersion{
supportedMajor: maj,
supportedMinor: min,
supportedMinor: minor,
additionalMajors: make([]int, 0),
}
return v
Expand Down
10 changes: 6 additions & 4 deletions cli/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
logger.Info(ctx, "spawning reaper process")
// Do not start a reaper on the child process. It's important
// to do this else we fork bomb ourselves.
//nolint:gocritic
args := append(os.Args, "--no-reap")
err := reaper.ForkReap(
reaper.WithExecArgs(args...),
Expand Down Expand Up @@ -327,10 +328,11 @@ func (r *RootCmd) workspaceAgent() *serpent.Command {
}

agnt := agent.New(agent.Options{
Client: client,
Logger: logger,
LogDir: logDir,
ScriptDataDir: scriptDataDir,
Client: client,
Logger: logger,
LogDir: logDir,
ScriptDataDir: scriptDataDir,
// #nosec G115 - Safe conversion as tailnet listen port is within uint16 range (0-65535)
TailnetListenPort: uint16(tailnetListenPort),
ExchangeToken: func(ctx context.Context) (string, error) {
if exchangeToken == nil {
Expand Down
1 change: 1 addition & 0 deletions cli/clistat/disk.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func (*Statter) Disk(p Prefix, path string) (*Result, error) {
return nil, err
}
var r Result
// #nosec G115 - Safe conversion because stat.Bsize is always positive and within uint64 range
r.Total = ptr.To(float64(stat.Blocks * uint64(stat.Bsize)))
r.Used = float64(stat.Blocks-stat.Bfree) * float64(stat.Bsize)
r.Unit = "B"
Expand Down
1 change: 1 addition & 0 deletions cli/clitest/golden.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ func TestCommandHelp(t *testing.T, getRoot func(t *testing.T) *serpent.Command,
ExtractCommandPathsLoop:
for _, cp := range extractVisibleCommandPaths(nil, root.Children) {
name := fmt.Sprintf("coder %s --help", strings.Join(cp, " "))
//nolint:gocritic
cmd := append(cp, "--help")
for _, tt := range cases {
if tt.Name == name {
Expand Down
2 changes: 1 addition & 1 deletion cli/cliui/cliui.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
"github.com/coder/pretty"
)

var Canceled = xerrors.New("canceled")
var ErrCanceled = xerrors.New("canceled")

// DefaultStyles compose visual elements of the UI.
var DefaultStyles Styles
Expand Down
7 changes: 4 additions & 3 deletions cli/cliui/parameter.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te

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

Expand All @@ -60,7 +61,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
)
value = string(v)
}
} else if len(templateVersionParameter.Options) > 0 {
case len(templateVersionParameter.Options) > 0:
// Move the cursor up a single line for nicer display!
_, _ = fmt.Fprint(inv.Stdout, "\033[1A")
var richParameterOption *codersdk.TemplateVersionParameterOption
Expand All @@ -74,7 +75,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
pretty.Fprintf(inv.Stdout, DefaultStyles.Prompt, "%s\n", richParameterOption.Name)
value = richParameterOption.Value
}
} else {
default:
text := "Enter a value"
if !templateVersionParameter.Required {
text += fmt.Sprintf(" (default: %q)", defaultValue)
Expand Down
4 changes: 2 additions & 2 deletions cli/cliui/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func Prompt(inv *serpent.Invocation, opts PromptOptions) (string, error) {
return "", err
case line := <-lineCh:
if opts.IsConfirm && line != "yes" && line != "y" {
return line, xerrors.Errorf("got %q: %w", line, Canceled)
return line, xerrors.Errorf("got %q: %w", line, ErrCanceled)
}
if opts.Validate != nil {
err := opts.Validate(line)
Expand All @@ -139,7 +139,7 @@ func Prompt(inv *serpent.Invocation, opts PromptOptions) (string, error) {
case <-interrupt:
// Print a newline so that any further output starts properly on a new line.
_, _ = fmt.Fprintln(inv.Stdout)
return "", Canceled
return "", ErrCanceled
}
}

Expand Down
Loading