Repository navigation
Add errx-migrate: type-aware pkg/errors → errx migrator - #1
Conversation
Implements cmd/errx-migrate plus a reusable go/analysis Analyzer that rewrites github.com/pkg/errors usage to github.com/go-extras/errx. - Two modes: stack-preserving (default) and lean (-no-stack). - Type-aware via golang.org/x/tools/go/packages: resolves aliases, dot-imports, and shadowing, and never rewrites stdlib errors. - Safe and idempotent: argument order is swapped correctly, fmt.Sprintf is injected for Wrapf/Errorf/WithMessagef, errors.Cause becomes an inline root-unwrap loop, and anything ambiguous is left untouched with a // TODO(errx-migrate) marker. Output is gofmt/goimports-clean. - Golden tests (both modes), a compile + idempotency check, an analysistest for the Analyzer, and a CLI end-to-end test. - golangci-lint config, Makefile, CI workflows, and GoReleaser mirroring the go-extras tooling. Implements go-extras/errx#44.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds errx-migrate: an AST- and type-aware migrator (library, CLI, and go/analysis analyzer) that rewrites usages of github.com/pkg/errors to github.com/go-extras/errx, plus import/comment/edit helpers, unified diff output, CI/lint/release infra, and extensive golden, stability, and analyzer tests. ChangesInfrastructure and Configuration
Core Migration Engine
Command-Line Tool and Output
Testing and Fixtures
Estimated code review effort 🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Poem
✨ Finishing Touches🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Actionable comments posted: 12
🧹 Nitpick comments (4)
.github/workflows/go-lint.yml (1)
44-44: ⚡ Quick winPin
govulncheckto a specific version instead of@latest.At Line 44,
@latestmakes CI behavior drift over time. Pin to an explicit version for reproducible lint/security runs.Suggested fix
- go install golang.org/x/vuln/cmd/govulncheck@latest + go install golang.org/x/vuln/cmd/govulncheck@<pinned-version>🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/workflows/go-lint.yml at line 44, Replace the floating install of govulncheck by pinning the version: locate the line that runs "go install golang.org/x/vuln/cmd/govulncheck@latest" and change the `@latest` suffix to an explicit release tag (for example `@v0.9.0` or whatever current stable tag you choose) so CI runs a reproducible, fixed version; update the pinned tag when you intentionally bump the tool version.apply.go (1)
38-50: ⚖️ Poor tradeoffConsider pre-allocating output buffer for better performance.
The current implementation allocates a new byte slice for each edit. For files with many edits, this could be optimized by pre-calculating the final size or using
bytes.Buffer. However, this is a minor optimization given typical usage patterns.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apply.go` around lines 38 - 50, The loop that builds the patched output (variables out, prevStart, resolved and fields e.start/e.end/e.text) currently allocates a new byte slice per edit; instead compute the final output length by summing len(src) minus total removed bytes plus total inserted bytes, allocate a single []byte of that capacity and then sequentially copy slices and e.text into it (or use a single bytes.Buffer with Grow(finalLen)), updating write offsets as you go to avoid per-edit reallocation and the repeated make/append pattern.rewrite.go (1)
40-48: 💤 Low valueSilent error suppression when reading source.
If
view.Source(file)fails,rewriteFilesilently returnsnil, hiding the error. Consider logging or propagating this error so users know when files are skipped due to read failures.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@rewrite.go` around lines 40 - 48, rewriteFile currently swallows errors from view.Source(file); instead of returning nil, create and return a descriptive analysis.Diagnostic when view.Source(file) returns an error: construct a diagnostic that includes err.Error() in the Message, set the Pos (or Start/End) to file.Pos() (or the file token range) and an appropriate Category/Severity so callers see the failure; update the early-return branch in rewriteFile (the view.Source(file) error handling) to return that diagnostic (or if project conventions prefer, change rewriteFile to return ([]analysis.Diagnostic, error) and propagate the error) and ensure callers handle the new return form if you choose propagation.analyzer_test.go (1)
21-27: ⚡ Quick winAdd a lean analyzer integration test.
Only stack mode is executed via
analysistest.Run(Line 26). Add the same wiring test forAnalyzerLeanto cover both analyzer front-ends.Proposed patch
func TestAnalyzerStack(t *testing.T) { dir, err := filepath.Abs(filepath.Join("testdata", "analyzer")) if err != nil { t.Fatal(err) } analysistest.Run(t, dir, errxmigrate.AnalyzerStack, "example") } + +func TestAnalyzerLean(t *testing.T) { + dir, err := filepath.Abs(filepath.Join("testdata", "analyzer")) + if err != nil { + t.Fatal(err) + } + analysistest.Run(t, dir, errxmigrate.AnalyzerLean, "example") +}🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@analyzer_test.go` around lines 21 - 27, The test only runs the stack-mode analyzer; add a parallel call to run the lean-mode analyzer by extending TestAnalyzerStack (or creating a new TestAnalyzerLean) to invoke analysistest.Run with errxmigrate.AnalyzerLean and the same "example" package/dir; ensure you resolve dir and err the same way and call analysistest.Run(t, dir, errxmigrate.AnalyzerLean, "example") so both AnalyzerStack and AnalyzerLean are exercised.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.github/workflows/ci.yml:
- Line 23: The CI workflow uses mutable action tags; replace each mutable tag
(e.g. actions/checkout@v6, actions/setup-go@v6, codecov/codecov-action@v6,
actions/upload-artifact@v7) with their corresponding pinned commit SHAs and add
"with: persist-credentials: false" to every checkout step (the actions/checkout
usage) to avoid token exposure; update the workflow entries where
actions/checkout is used to include the persist-credentials: false key and
change all other uses to the exact commit SHA instead of the `@vN` tag.
In @.github/workflows/go-lint.yml:
- Line 20: The workflow uses mutable action tags and leaves checkout credentials
enabled: replace uses: actions/checkout@v6, uses: actions/setup-go@v6, and uses:
golangci/golangci-lint-action@v9 with their respective pinned commit SHAs, and
add persist-credentials: false to the actions/checkout step to harden token
exposure; also replace the mutable go install .../govulncheck@latest invocation
with a pinned version (specific tag or version) so the installed tool is
immutable. Ensure you update the three uses entries and the govulncheck install
command and verify the exact commit SHAs/tags you pin.
In @.github/workflows/release.yml:
- Line 21: Update the workflow actions to use immutable commit SHAs and harden
checkout credentials: replace action tags actions/checkout@v6,
actions/setup-go@v6, goreleaser/goreleaser-action@v7, and
actions/upload-artifact@v7 with their corresponding full commit SHAs, and in the
actions/checkout step add with: persist-credentials: false (unless a later job
requires pushing with repo credentials) so the checkout does not expose tokens;
ensure you update the action refs for the steps that reference those identifiers
accordingly.
- Around line 11-14: The workflow currently sets broad workflow-level
permissions (permissions: contents: write, packages: write) and shares
actions/setup-go caching (cache: true with dependency path go.sum) across both
PR snapshot and tag release paths, exposing PR runs to unnecessary privileges
and shared cache; split the logic into two separate jobs (e.g., a "pr-snapshot"
job gated by if: github.event_name == 'pull_request' and a "tag-release" job for
tags), move minimal required permissions into each job (remove or tighten the
top-level permissions and set job-level permissions like contents: read for PR
and contents/packages: write only for tag-release), and configure
actions/setup-go cache keys so PR-snapshot uses an isolated PR-only cache key
(include github.event_number or pull_request id) while tag-release uses its own
cache key (e.g., based on ref), ensuring caching and permissions are scoped to
each job.
In `@cmd/errx-migrate/main.go`:
- Line 169: The inline nolint directive attached to the os.WriteFile call
(os.WriteFile(name, formatted, 0o600)) is unused and causing nolintlint
failures; remove the trailing //nolint:gosec comment on that line so the linter
no longer reports an invalid suppression, keeping the rest of the call unchanged
(use the existing variables name and formatted and the 0o600 permission).
- Around line 173-175: The stdout write in the default output path currently
ignores errors (os.Stdout.Write(formatted)), so detect and handle the returned
(n, err) and fail the command on error; after printing the header
(fmt.Print(header)) check the write result from os.Stdout.Write(formatted),
surface the error (return it, log it, or call os.Exit(1) as the surrounding
function requires) so broken/closed stdout causes the process to exit non‑zero
instead of appearing successful.
In `@golden_test.go`:
- Line 76: Remove the stale nolint:gosec suppression on the os.WriteFile call:
in the line calling os.WriteFile(goldenPath, formatted, 0o600) (references:
function os.WriteFile, variables goldenPath and formatted), delete the trailing
"//nolint:gosec" comment so the linter no longer reports an unused suppression.
In `@imports.go`:
- Around line 94-113: The code currently uses decl := firstImportDecl(file) then
later removes decl even when target (the matching *ast.ImportSpec) belongs to a
different import block; fix by finding the actual owning *ast.GenDecl for target
instead of reusing decl: iterate file.Decls (or import declarations) to locate
the GenDecl whose Specs contains target, assign it to a variable like
owningDecl, and then use owningDecl (not decl) when deciding whether to remove
the whole declaration (calling wholeLinesEdit(tf, owningDecl.Pos(),
owningDecl.End())) or to remove only the target import (wholeLinesEdit(tf,
target.Pos(), target.End())); keep existing logic for paren/singleton checks but
reference owningDecl when checking Lparen and Specs length.
In `@Makefile`:
- Line 1: The Makefile currently lists .PHONY first which can cause all phony
prerequisites (build, install, test, lint, lint-fix, fmt, clean, help) to run on
a bare `make`; add an explicit default goal by setting .DEFAULT_GOAL (e.g.,
`.DEFAULT_GOAL := help`) near the top of the file so `make` runs only the
intended default target instead of all .PHONY prerequisites, keeping the
existing .PHONY declaration intact and referencing the `help` target as the
default.
In `@stable_test.go`:
- Line 107: The test contains an unused gosec suppression on the os.WriteFile
call (the expression os.WriteFile(filepath.Join(dir, pkgDir, "p.go"), data,
0o600) //nolint:gosec); remove the trailing "//nolint:gosec" from that line in
stable_test.go so the linter no longer reports an unused suppression while
leaving the rest of the call unchanged.
In `@testdata/src/nested/in.lean.golden`:
- Around line 3-8: The golden fixture imports the external package
"github.com/go-extras/errx/stacktrace" and calls stacktrace.Classify(err), which
violates the -no-stack contract; remove the stacktrace import from the import
block and update the call site in function N to use the core API instead
(replace stacktrace.Classify(err) with errx.Classify(err) or plain err if
Classify is not available in core) so the file only depends on
"github.com/go-extras/errx".
In `@testdata/src/withstack/in.lean.golden`:
- Around line 3-7: The golden fixture currently asserts stack-mode output
because S uses stacktrace.Classify(err) and the file only contains the
stack-mode result; update the test fixture so it also validates the -no-stack
mapping: either replace or extend the content in the testdata with a variant
that exercises the no-stack mapping (e.g. remove or avoid calling
stacktrace.Classify in a separate case) or add a second golden case for the same
symbol S that expects the -no-stack output; locate the usage of
stacktrace.Classify in function S and ensure the fixture contains both
stack-mode and no-stack-mode expectations so regressions in lean mapping are
detected.
---
Nitpick comments:
In @.github/workflows/go-lint.yml:
- Line 44: Replace the floating install of govulncheck by pinning the version:
locate the line that runs "go install golang.org/x/vuln/cmd/govulncheck@latest"
and change the `@latest` suffix to an explicit release tag (for example `@v0.9.0` or
whatever current stable tag you choose) so CI runs a reproducible, fixed
version; update the pinned tag when you intentionally bump the tool version.
In `@analyzer_test.go`:
- Around line 21-27: The test only runs the stack-mode analyzer; add a parallel
call to run the lean-mode analyzer by extending TestAnalyzerStack (or creating a
new TestAnalyzerLean) to invoke analysistest.Run with errxmigrate.AnalyzerLean
and the same "example" package/dir; ensure you resolve dir and err the same way
and call analysistest.Run(t, dir, errxmigrate.AnalyzerLean, "example") so both
AnalyzerStack and AnalyzerLean are exercised.
In `@apply.go`:
- Around line 38-50: The loop that builds the patched output (variables out,
prevStart, resolved and fields e.start/e.end/e.text) currently allocates a new
byte slice per edit; instead compute the final output length by summing len(src)
minus total removed bytes plus total inserted bytes, allocate a single []byte of
that capacity and then sequentially copy slices and e.text into it (or use a
single bytes.Buffer with Grow(finalLen)), updating write offsets as you go to
avoid per-edit reallocation and the repeated make/append pattern.
In `@rewrite.go`:
- Around line 40-48: rewriteFile currently swallows errors from
view.Source(file); instead of returning nil, create and return a descriptive
analysis.Diagnostic when view.Source(file) returns an error: construct a
diagnostic that includes err.Error() in the Message, set the Pos (or Start/End)
to file.Pos() (or the file token range) and an appropriate Category/Severity so
callers see the failure; update the early-return branch in rewriteFile (the
view.Source(file) error handling) to return that diagnostic (or if project
conventions prefer, change rewriteFile to return ([]analysis.Diagnostic, error)
and propagate the error) and ensure callers handle the new return form if you
choose propagation.
🪄 Autofix (Beta)
❌ Autofix failed (check again to retry)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 77a0c122-e3a6-4eda-b589-bcc84146b39f
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (76)
.github/workflows/ci.yml.github/workflows/go-lint.yml.github/workflows/release.yml.golangci.yml.goreleaser.yamlMakefileREADME.mdanalyzer.goanalyzer_test.goapply.gobuild_edits.gocmd/errx-migrate/diff.gocmd/errx-migrate/main.gocmd/errx-migrate/main_test.gocomments.godetect.gogo.modgolden_test.goimports.gomode.gopkgview.gorewrite.gostable_test.gotestdata/analyzer/src/example/example.gotestdata/analyzer/src/github.com/pkg/errors/errors.gotestdata/go.modtestdata/src/aliased/in.gotestdata/src/aliased/in.lean.goldentestdata/src/aliased/in.stack.goldentestdata/src/cause/in.gotestdata/src/cause/in.lean.goldentestdata/src/cause/in.stack.goldentestdata/src/comment/in.gotestdata/src/comment/in.lean.goldentestdata/src/comment/in.stack.goldentestdata/src/dotimport/in.gotestdata/src/dotimport/in.lean.goldentestdata/src/dotimport/in.stack.goldentestdata/src/errorf/in.gotestdata/src/errorf/in.lean.goldentestdata/src/errorf/in.stack.goldentestdata/src/isasunwrap/in.gotestdata/src/isasunwrap/in.lean.goldentestdata/src/isasunwrap/in.stack.goldentestdata/src/nested/in.gotestdata/src/nested/in.lean.goldentestdata/src/nested/in.stack.goldentestdata/src/nolint/in.gotestdata/src/nolint/in.lean.goldentestdata/src/nolint/in.stack.goldentestdata/src/shadowed/in.gotestdata/src/shadowed/in.lean.goldentestdata/src/shadowed/in.stack.goldentestdata/src/stdmix/in.gotestdata/src/stdmix/in.lean.goldentestdata/src/stdmix/in.stack.goldentestdata/src/withmessage/in.gotestdata/src/withmessage/in.lean.goldentestdata/src/withmessage/in.stack.goldentestdata/src/withstack/in.gotestdata/src/withstack/in.lean.goldentestdata/src/withstack/in.stack.goldentestdata/src/wrap/in.gotestdata/src/wrap/in.lean.goldentestdata/src/wrap/in.stack.goldentestdata/src/wrapf/in.gotestdata/src/wrapf/in.lean.goldentestdata/src/wrapf/in.stack.goldentestdata/src/wverb/in.gotestdata/src/wverb/in.lean.goldentestdata/src/wverb/in.stack.goldentestdata/stub/errx/errx.gotestdata/stub/errx/go.modtestdata/stub/errx/stacktrace/stacktrace.gotestdata/stub/pkgerrors/errors.gotestdata/stub/pkgerrors/go.mod
- imports.go: remove an import via its owning declaration rather than the first import block, so a github.com/pkg/errors import that lives in a second import decl is removed correctly instead of deleting the wrong one. Add a multiimport regression fixture (two import decls). - main.go: handle the os.Stdout write error in default (stdout) mode. - main.go, golden_test.go, stable_test.go: drop //nolint:gosec directives. They are unused under the pinned golangci-lint v2.10.1 (its gosec has no G703 rule), which nolintlint reports as a build failure; a newer local gosec was masking it.
The lint job now pins golangci-lint v2.12.2 (was v2.10.1). Its newer gosec bundles the G703 path-traversal-via-taint rule, which fires on file paths taken from the type checker's own file set and from t.TempDir() in tests. Those paths are trusted, so G703 is excluded in .golangci.yml (every other gosec rule stays enabled; the exclude is a no-op on gosec versions that predate the rule). This keeps `make lint` green on both the pinned toolchain and newer local installs, without per-line suppressions.
- Pin every GitHub Action to a commit SHA (with a version comment) across ci.yml, go-lint.yml, and release.yml. - Add persist-credentials: false to all checkout steps. - Add explicit least-privilege permissions (contents: read) to each job. - Split release.yml into separate snapshot (PR; read-only, caching disabled) and release (tag; write) jobs, so the PR path cannot publish or share caches across the trust boundary. - Makefile: set an explicit .DEFAULT_GOAL := help. Validated with actionlint.
|
Note Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it. Autofix skipped. No unresolved CodeRabbit review comments with fix instructions found. |
Implements go-extras/errx#44: a small, type-aware AST rewriter that converts a
github.com/pkg/errors-based codebase togithub.com/go-extras/errx, safely and idempotently.What it does
cmd/errx-migrateCLI and a reusablego/analysisAnalyzer (AnalyzerStack/AnalyzerLean) share one rewrite core via a smallPkgViewabstraction over*packages.Package/*analysis.Pass.stacktracesubpackage) and lean (-no-stack, maps to the errx core + stdlib).golang.org/x/tools/go/packages: resolves whicherrorsidentifier is reallypkg/errors(aliases, dot-imports, shadowing) and never touches stdliberrors.fmt.Sprintfis injected forWrapf/Errorf/WithMessagef,errors.Causebecomes an inline root-unwrap loop, and anything ambiguous is left untouched with a// TODO(errx-migrate)marker. Output is gofmt/goimports-clean; re-running is a no-op.Mapping
pkg/errors-no-stack)Newstacktrace.ClassifyNewerrors.NewErrorfstacktrace.ClassifyNew(fmt.Sprintf(...))fmt.ErrorfWrap(err,msg)stacktrace.Wrap(msg,err)errx.Wrap(msg,err)Wrapfstacktrace.Wrap(fmt.Sprintf(...),err)errx.Wrap(fmt.Sprintf(...),err)WithMessage[f]errx.Wrap(...)errx.Wrap(...)WithStackstacktrace.Classifystacktrace.ClassifyIs/As/Unwraperrors.*CauseFlags
-w(write),-diff(unified diff),-no-stack(lean),-include-generated.Tests
Golden tests for every mapping row in both modes (offline, against local stubs), a compile + idempotency check, an
analysistestfor the Analyzer, and a CLI end-to-end test.golangci-lint(go-extras config) is clean;go mod tidyis a no-op.Real-world verification (kopia/kopia)
Ran against
kopia/kopia(427 files, ~2,700pkg/errorscall sites): 365 files migrated in ~5s,go build ./...andgo vet ./...both pass, gofmt-clean, idempotent on re-run, zero crashes/warnings. Remaining sites are correctly left with// TODO(errx-migrate)(apkg/errorscall nested inside a closure,%win a format string) or are build-tagged for anotherGOOS(re-run perGOOS).Notes
%+vstack rendering after migration depends on a companion fix in errx itself (the carrier needs to forward%+vto its captured trace) — filed separately.Summary by CodeRabbit
New Features
Documentation
Tests
Chores