From 1f656259a0ab96cad40de9f75ee2b58c0ceff054 Mon Sep 17 00:00:00 2001 From: Denis V <5462781+denisvmedia@users.noreply.github.com> Date: Sat, 30 May 2026 15:38:07 +0200 Subject: [PATCH 1/4] Add errx-migrate: type-aware pkg/errors -> errx migrator 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. --- .github/workflows/ci.yml | 107 ++++++ .github/workflows/go-lint.yml | 45 +++ .github/workflows/release.yml | 61 ++++ .golangci.yml | 293 +++++++++++++++++ .goreleaser.yaml | 82 +++++ Makefile | 52 +++ README.md | 112 ++++++- analyzer.go | 33 ++ analyzer_test.go | 27 ++ apply.go | 65 ++++ build_edits.go | 307 ++++++++++++++++++ cmd/errx-migrate/diff.go | 181 +++++++++++ cmd/errx-migrate/main.go | 177 ++++++++++ cmd/errx-migrate/main_test.go | 99 ++++++ comments.go | 82 +++++ detect.go | 120 +++++++ go.mod | 10 + go.sum | 8 + golden_test.go | 97 ++++++ imports.go | 128 ++++++++ mode.go | 34 ++ pkgview.go | 76 +++++ rewrite.go | 263 +++++++++++++++ stable_test.go | 114 +++++++ testdata/analyzer/src/example/example.go | 9 + .../src/github.com/pkg/errors/errors.go | 40 +++ testdata/go.mod | 10 + testdata/src/aliased/in.go | 7 + testdata/src/aliased/in.lean.golden | 10 + testdata/src/aliased/in.stack.golden | 10 + testdata/src/cause/in.go | 5 + testdata/src/cause/in.lean.golden | 19 ++ testdata/src/cause/in.stack.golden | 19 ++ testdata/src/comment/in.go | 7 + testdata/src/comment/in.lean.golden | 8 + testdata/src/comment/in.stack.golden | 8 + testdata/src/dotimport/in.go | 7 + testdata/src/dotimport/in.lean.golden | 10 + testdata/src/dotimport/in.stack.golden | 9 + testdata/src/errorf/in.go | 7 + testdata/src/errorf/in.lean.golden | 10 + testdata/src/errorf/in.stack.golden | 12 + testdata/src/isasunwrap/in.go | 9 + testdata/src/isasunwrap/in.lean.golden | 11 + testdata/src/isasunwrap/in.stack.golden | 11 + testdata/src/nested/in.go | 5 + testdata/src/nested/in.lean.golden | 8 + testdata/src/nested/in.stack.golden | 7 + testdata/src/nolint/in.go | 7 + testdata/src/nolint/in.lean.golden | 9 + testdata/src/nolint/in.stack.golden | 9 + testdata/src/shadowed/in.go | 18 + testdata/src/shadowed/in.lean.golden | 20 ++ testdata/src/shadowed/in.stack.golden | 20 ++ testdata/src/stdmix/in.go | 13 + testdata/src/stdmix/in.lean.golden | 12 + testdata/src/stdmix/in.stack.golden | 12 + testdata/src/withmessage/in.go | 9 + testdata/src/withmessage/in.lean.golden | 14 + testdata/src/withmessage/in.stack.golden | 14 + testdata/src/withstack/in.go | 5 + testdata/src/withstack/in.lean.golden | 7 + testdata/src/withstack/in.stack.golden | 7 + testdata/src/wrap/in.go | 7 + testdata/src/wrap/in.lean.golden | 10 + testdata/src/wrap/in.stack.golden | 9 + testdata/src/wrapf/in.go | 7 + testdata/src/wrapf/in.lean.golden | 12 + testdata/src/wrapf/in.stack.golden | 12 + testdata/src/wverb/in.go | 5 + testdata/src/wverb/in.lean.golden | 6 + testdata/src/wverb/in.stack.golden | 6 + testdata/stub/errx/errx.go | 29 ++ testdata/stub/errx/go.mod | 3 + testdata/stub/errx/stacktrace/stacktrace.go | 20 ++ testdata/stub/pkgerrors/errors.go | 40 +++ testdata/stub/pkgerrors/go.mod | 3 + 77 files changed, 3175 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/go-lint.yml create mode 100644 .github/workflows/release.yml create mode 100644 .golangci.yml create mode 100644 .goreleaser.yaml create mode 100644 Makefile create mode 100644 analyzer.go create mode 100644 analyzer_test.go create mode 100644 apply.go create mode 100644 build_edits.go create mode 100644 cmd/errx-migrate/diff.go create mode 100644 cmd/errx-migrate/main.go create mode 100644 cmd/errx-migrate/main_test.go create mode 100644 comments.go create mode 100644 detect.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 golden_test.go create mode 100644 imports.go create mode 100644 mode.go create mode 100644 pkgview.go create mode 100644 rewrite.go create mode 100644 stable_test.go create mode 100644 testdata/analyzer/src/example/example.go create mode 100644 testdata/analyzer/src/github.com/pkg/errors/errors.go create mode 100644 testdata/go.mod create mode 100644 testdata/src/aliased/in.go create mode 100644 testdata/src/aliased/in.lean.golden create mode 100644 testdata/src/aliased/in.stack.golden create mode 100644 testdata/src/cause/in.go create mode 100644 testdata/src/cause/in.lean.golden create mode 100644 testdata/src/cause/in.stack.golden create mode 100644 testdata/src/comment/in.go create mode 100644 testdata/src/comment/in.lean.golden create mode 100644 testdata/src/comment/in.stack.golden create mode 100644 testdata/src/dotimport/in.go create mode 100644 testdata/src/dotimport/in.lean.golden create mode 100644 testdata/src/dotimport/in.stack.golden create mode 100644 testdata/src/errorf/in.go create mode 100644 testdata/src/errorf/in.lean.golden create mode 100644 testdata/src/errorf/in.stack.golden create mode 100644 testdata/src/isasunwrap/in.go create mode 100644 testdata/src/isasunwrap/in.lean.golden create mode 100644 testdata/src/isasunwrap/in.stack.golden create mode 100644 testdata/src/nested/in.go create mode 100644 testdata/src/nested/in.lean.golden create mode 100644 testdata/src/nested/in.stack.golden create mode 100644 testdata/src/nolint/in.go create mode 100644 testdata/src/nolint/in.lean.golden create mode 100644 testdata/src/nolint/in.stack.golden create mode 100644 testdata/src/shadowed/in.go create mode 100644 testdata/src/shadowed/in.lean.golden create mode 100644 testdata/src/shadowed/in.stack.golden create mode 100644 testdata/src/stdmix/in.go create mode 100644 testdata/src/stdmix/in.lean.golden create mode 100644 testdata/src/stdmix/in.stack.golden create mode 100644 testdata/src/withmessage/in.go create mode 100644 testdata/src/withmessage/in.lean.golden create mode 100644 testdata/src/withmessage/in.stack.golden create mode 100644 testdata/src/withstack/in.go create mode 100644 testdata/src/withstack/in.lean.golden create mode 100644 testdata/src/withstack/in.stack.golden create mode 100644 testdata/src/wrap/in.go create mode 100644 testdata/src/wrap/in.lean.golden create mode 100644 testdata/src/wrap/in.stack.golden create mode 100644 testdata/src/wrapf/in.go create mode 100644 testdata/src/wrapf/in.lean.golden create mode 100644 testdata/src/wrapf/in.stack.golden create mode 100644 testdata/src/wverb/in.go create mode 100644 testdata/src/wverb/in.lean.golden create mode 100644 testdata/src/wverb/in.stack.golden create mode 100644 testdata/stub/errx/errx.go create mode 100644 testdata/stub/errx/go.mod create mode 100644 testdata/stub/errx/stacktrace/stacktrace.go create mode 100644 testdata/stub/pkgerrors/errors.go create mode 100644 testdata/stub/pkgerrors/go.mod diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..dfbf428 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,107 @@ +name: CI/CD Pipeline + +on: + push: + branches: + - master + pull_request: + +permissions: + contents: read + pull-requests: read + +env: + COVERAGE_THRESHOLD: 50 + +jobs: + # Setup job to expose variables + setup: + name: Setup + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v6 + + # Build verification - ensure the tool compiles + build: + name: Build + runs-on: ubuntu-latest + needs: setup + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - uses: actions/setup-go@v6 + with: + go-version: stable + cache: true + cache-dependency-path: go.sum + + - name: Download dependencies + run: go mod download + + - name: Build library + run: go build -v ./... + + - name: Build standalone binary + run: go build -v -o bin/errx-migrate ./cmd/errx-migrate + + # Unit Tests + unit-tests: + name: Unit Tests + runs-on: ubuntu-latest + strategy: + matrix: + go-version: + - oldstable + - stable + needs: setup + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - uses: actions/setup-go@v6 + with: + go-version: ${{ matrix.go-version }} + cache: true + cache-dependency-path: go.sum + + - name: Download dependencies + run: go mod download + + - name: Run unit tests with race detection + run: | + go test -race -v -coverprofile=coverage.out -covermode=atomic ./... + + - name: Generate coverage report + run: | + go tool cover -html=coverage.out -o coverage.html + go tool cover -func=coverage.out | tail -1 | awk '{print $3}' | sed 's/%//' > coverage.txt + + - name: Check coverage threshold + run: | + COVERAGE=$(cat coverage.txt) + echo "Coverage: ${COVERAGE}%" + if (( $(echo "$COVERAGE < $COVERAGE_THRESHOLD" | bc -l) )); then + echo "Coverage ${COVERAGE}% is below threshold ${COVERAGE_THRESHOLD}%" + exit 1 + fi + + - name: Upload coverage to Codecov + if: matrix.go-version == 'stable' + uses: codecov/codecov-action@v6 + with: + files: ./coverage.out + flags: unittests + name: codecov-umbrella + fail_ci_if_error: false + + - name: Upload coverage artifacts + if: matrix.go-version == 'stable' + uses: actions/upload-artifact@v7 + with: + name: coverage-report + path: | + coverage.out + coverage.html + coverage.txt diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml new file mode 100644 index 0000000..beadd1e --- /dev/null +++ b/.github/workflows/go-lint.yml @@ -0,0 +1,45 @@ +name: Go Lint + +on: + push: + branches: + - master + pull_request: + +permissions: + contents: read + pull-requests: read + +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + # Checkout code + - name: Checkout code + uses: actions/checkout@v6 + + - uses: actions/setup-go@v6 + with: + go-version: stable + cache: true + cache-dependency-path: go.sum + + - name: Download dependencies + run: go mod download + + - name: Check go mod tidy + run: | + go mod tidy + git diff --exit-code go.mod go.sum + + - name: golangci-lint + uses: golangci/golangci-lint-action@v9 + with: + args: --timeout=30m + version: v2.10.1 + + - name: Run govulncheck + run: | + go install golang.org/x/vuln/cmd/govulncheck@latest + govulncheck ./... diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..a248f42 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,61 @@ +name: Release + +on: + push: + tags: + - 'v*' + pull_request: + branches: + - master + +permissions: + contents: write + packages: write + +jobs: + goreleaser: + name: GoReleaser + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Set up Go + uses: actions/setup-go@v6 + with: + go-version: 1.26.0 + cache: true + cache-dependency-path: go.sum + + - name: Run GoReleaser (Snapshot for PRs) + if: github.event_name == 'pull_request' + uses: goreleaser/goreleaser-action@v7 + with: + distribution: goreleaser + version: '~> v2' + args: release --snapshot --clean --skip=publish + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Upload PR artifacts + if: github.event_name == 'pull_request' + uses: actions/upload-artifact@v7 + with: + name: release-artifacts + path: | + dist/*.tar.gz + dist/*.zip + dist/checksums.txt + retention-days: 7 + + - name: Run GoReleaser (Production Release) + if: startsWith(github.ref, 'refs/tags/') + uses: goreleaser/goreleaser-action@v7 + with: + distribution: goreleaser + version: '~> v2' + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..f0635c3 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,293 @@ +version: "2" + +run: + concurrency: 8 + go: "1.25.0" + +linters: + default: none + enable: + - asciicheck + - bidichk + - copyloopvar + - containedctx + - depguard + - dupl + - dupword + - errcheck + - errorlint + - forbidigo + - funlen + - gochecknoinits + - gocognit + - gocritic + - gocyclo + - godot + - gosec + - govet + - importas + - ineffassign + - lll + - misspell + - nakedret + - nestif + - nolintlint + - predeclared + - revive + - staticcheck + - unconvert + - unparam + - unused + - whitespace + settings: + depguard: + rules: + main: + deny: + - pkg: io/ioutil + desc: 'Deprecated: As of Go 1.16, the same functionality is now provided by package `io` or package `os`.' + - pkg: log + desc: 'No use of log for output in this project' + - pkg: math/rand + desc: 'No use of math/rand in this project' + - pkg: unsafe + desc: 'No use of unsafe in this project' + errorlint: + errorf: true + asserts: true + comparison: true + funlen: + lines: 240 + statements: 160 + gocognit: + min-complexity: 30 + gocritic: + enabled-checks: + - badLock + - badRegexp + - badSorting + - badSyncOnceFunc + - deferInLoop + - dynamicFmtString + - emptyDecl + - filepathJoin + gocyclo: + min-complexity: 21 + godot: + scope: declarations + exclude: [] + capital: true + importas: + no-unaliased: true + lll: + line-length: 240 + nakedret: # Discussions on why naked return can be a problem: https://github.com/golang/go/issues/21291 + max-func-lines: 2 # few lines with bare return can be fine for some super short logicless functions + nestif: + min-complexity: 6 + nolintlint: + require-explanation: true + require-specific: true + allow-no-explanation: + # the following linters are allowed without explanations because usually there's nothing to explain + - errcheck + - lll + revive: + severity: error + # See https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md + rules: + - name: atomic + disabled: false + - name: bare-return + disabled: true # covered by nakedret linter + - name: blank-imports + disabled: false + - name: bool-literal-in-expr + disabled: false + - name: confusing-results + disabled: false + - name: constant-logical-expr + disabled: false + - name: context-keys-type + disabled: false + - name: datarace + disabled: false + - name: deep-exit + disabled: false + - name: defer + disabled: false + - name: dot-imports + disabled: false + - name: duplicated-imports + disabled: false + - name: early-return + disabled: false + - name: empty-block + disabled: false + - name: empty-lines + disabled: false + - name: enforce-map-style + arguments: + - make + disabled: false + - name: enforce-repeated-arg-type-style + arguments: + - short + disabled: false + - name: enforce-slice-style + arguments: + - make + disabled: false + - name: error-naming + disabled: false + - name: error-return + disabled: false + - name: error-strings + disabled: false + - name: filename-format + arguments: + - '^[_a-z][_a-z0-9]*.go$' + disabled: false + - name: flag-parameter + disabled: false + - name: function-result-limit + arguments: + - 3 + disabled: false + - name: get-return + disabled: false + - name: identical-branches + disabled: false + - name: import-alias-naming + arguments: + - # require aliases to be lowercased alphanumeric values (the first symbol is always a letter) + allowRegex: '^[a-z][a-z0-9]*$' + # disallow v1 (or vN, where N is a number) prefixes + denyRegex: '^v\d+$' + disabled: false + - name: import-shadowing + disabled: false + - name: increment-decrement + disabled: false + - name: indent-error-flow + arguments: + - preserveScope + disabled: false + - name: modifies-value-receiver + disabled: false + - name: optimize-operands-order + disabled: false + - name: range + disabled: false + - name: receiver-naming + arguments: + - maxLength: 3 + disabled: false + - name: redefines-builtin-id + disabled: false + #- name: redundant-build-tag # not supported in golangci-lint + # disabled: false + - name: redundant-import-alias + disabled: false + - name: string-of-int + disabled: false + - name: struct-tag + disabled: false + - name: superfluous-else + disabled: false + - name: time-equal + disabled: false + - name: unchecked-type-assertion + arguments: + - acceptIgnoredAssertionResult: true + disabled: false + - name: unconditional-recursion + disabled: false + - name: unexported-naming + disabled: false + - name: unexported-return + disabled: false + - name: unnecessary-stmt + disabled: false + - name: unreachable-code + disabled: false + - name: unused-parameter + arguments: + - allowRegex: '^_' + disabled: false + - name: unused-receiver + disabled: false + - name: use-any + disabled: false + - name: useless-break + disabled: false + - name: var-naming + disabled: false + - name: waitgroup-by-value + disabled: false + staticcheck: + checks: + # STxxxx checks in https://staticcheck.io/docs/checks/#ST + - all + - -QF1008 + - -ST1000 + - -ST1003 + - -ST1005 + - -ST1016 + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - path: '_test\.go$' + linters: + - funlen + - gocognit + - gocritic + - gocyclo + - lll + - nestif + - dupl + - path: '_test\.go$' + text: 'function-result-limit:' + - path: '_test\.go$' + text: 'bool-literal-in-expr:' + - path: '_test\.go$' + text: 'unused-parameter:' + - path: '_test\.go$' + text: 'unchecked-type-assertion:' + - path: 'cmd/.*\.go$' + linters: + - gochecknoinits + - depguard + - forbidigo + paths: + - 'third_party$' + - 'builtin$' + - 'examples$' + - 'testdata$' + +issues: + max-issues-per-linter: 0 + max-same-issues: 0 + +formatters: + enable: + - gci + - gofmt + settings: + gci: + sections: + - standard + - default + - prefix(github.com/go-extras/errx-migrate) + exclusions: + generated: lax + paths: + - 'third_party$' + - 'builtin$' + - 'examples$' + - 'testdata$' diff --git a/.goreleaser.yaml b/.goreleaser.yaml new file mode 100644 index 0000000..a372763 --- /dev/null +++ b/.goreleaser.yaml @@ -0,0 +1,82 @@ +version: 2 + +project_name: errx-migrate + +builds: + - binary: errx-migrate + main: ./cmd/errx-migrate/ + flags: + - -trimpath + ldflags: -s -w -X main.version={{.Version}} -X main.commit={{.ShortCommit}} -X main.date={{.Date}} + env: + - CGO_ENABLED=0 + goos: + - darwin + - windows + - linux + - freebsd + goarch: + - amd64 + - arm64 + - arm + - '386' + goarm: + - '6' + - '7' + ignore: + - goos: darwin + goarch: '386' + # Deprecated in go1.25, Removed in go1.26 + # https://go.dev/doc/go1.25#windows + - goos: windows + goarch: arm + +archives: + - formats: [ 'tar.gz' ] + wrap_in_directory: true + format_overrides: + - goos: windows + formats: [ 'zip' ] + name_template: '{{ .ProjectName }}-{{ .Version }}-{{ .Os }}-{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' + files: + - LICENSE + - README.md + +snapshot: + version_template: SNAPSHOT-{{ .Commit }} + +checksum: + disable: false + name_template: '{{ .ProjectName }}-{{ .Version }}-checksums.txt' + +changelog: + sort: asc + filters: + exclude: + - '(?i)^docs?:' + - '(?i)^docs\([^:]+\):' + - '(?i)^docs\[[^:]+\]:' + - '^tests?:' + - '(?i)^dev:' + - '(?i)^chore:' + - Merge pull request + - Merge branch + +release: + github: + owner: go-extras + name: errx-migrate + header: | + ## errx-migrate {{ .Version }} + + Automatic pkg/errors -> errx migrator. + + ### Installation + + ```bash + go install github.com/go-extras/errx-migrate/cmd/errx-migrate@{{ .Tag }} + ``` + +source: + enabled: true + name_template: '{{ .ProjectName }}-{{ .Version }}-source' diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..870a825 --- /dev/null +++ b/Makefile @@ -0,0 +1,52 @@ +.PHONY: build install test lint lint-fix fmt clean help + +# Build the standalone binary +build: + @echo "Building errx-migrate..." + @mkdir -p bin + @go build -o bin/errx-migrate ./cmd/errx-migrate + @echo "Binary built at bin/errx-migrate" + +# Install the binary to GOPATH/bin +install: + @echo "Installing errx-migrate..." + @go install ./cmd/errx-migrate + @echo "Installed to $(shell go env GOPATH)/bin/errx-migrate" + +# Run tests +test: + @echo "Running tests..." + @go test -race ./... + +# Run linter +lint: + @echo "Running golangci-lint..." + @golangci-lint run ./... + +# Run linter and fix issues +lint-fix: + @echo "Running golangci-lint with autofix..." + @golangci-lint run ./... --fix + +# Run formatters +fmt: + @echo "Running formatters..." + @golangci-lint run --fix ./... + +# Clean build artifacts +clean: + @echo "Cleaning..." + @rm -rf bin/ + @echo "Clean complete" + +# Show help +help: + @echo "Available targets:" + @echo " build - Build the standalone binary to bin/errx-migrate" + @echo " install - Install the binary to GOPATH/bin" + @echo " test - Run all tests" + @echo " lint - Run golangci-lint" + @echo " lint-fix - Run golangci-lint with autofix" + @echo " fmt - Run formatters (auto-fix)" + @echo " clean - Remove build artifacts" + @echo " help - Show this help message" diff --git a/README.md b/README.md index 172e6a7..9aca428 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,112 @@ # errx-migrate -Migrate to errx from other libraries (e.g. pkg/errors) + +Automatic [`github.com/pkg/errors`](https://github.com/pkg/errors) → [`github.com/go-extras/errx`](https://github.com/go-extras/errx) migrator. + +`pkg/errors` has been archived (read-only since 2021-12-01). `errx-migrate` is a small, **type-aware AST +rewriter** that converts a `pkg/errors`-based codebase to `errx` **safely and idempotently** — leaving +`gofmt`-clean output and explicit `// TODO(errx-migrate)` markers wherever a conversion cannot be proven safe. + +It is type-aware: it uses [`golang.org/x/tools/go/packages`](https://pkg.go.dev/golang.org/x/tools/go/packages) +to resolve which `errors` identifier is actually `pkg/errors` (handling aliases, dot-imports, and shadowing), +so it never rewrites stdlib `errors` calls by mistake. + +## Install + +```bash +go install github.com/go-extras/errx-migrate/cmd/errx-migrate@latest +``` + +## Usage + +```bash +# Preview a migration as a unified diff (no files written): +errx-migrate -diff ./... + +# Apply the migration in place: +errx-migrate -w ./... + +# Lean mode: map to the zero-dependency errx core + stdlib instead of the stacktrace subpackage: +errx-migrate -w -no-stack ./... +``` + +Flags: + +| Flag | Description | +|---|---| +| `-w` | Write changes back to source files (default: print the result to stdout). | +| `-diff` | Print a unified diff instead of writing or printing the full file. | +| `-no-stack` | **Lean** mode — map to the dependency-free `errx` core + stdlib `errors`/`fmt`, dropping implicit stack capture. The default is **stack-preserving** mode. | +| `-include-generated` | Also rewrite generated files (`// Code generated ... DO NOT EDIT.`). Skipped by default. | + +The tool must be able to type-check the target packages, so run it from the module root with the relevant +build tags/`GOOS` set if you have platform-specific files. + +## Modes + +**Stack-preserving (default).** Stack-capturing `pkg/errors` calls are mapped to the `errx/stacktrace` +subpackage so runtime behavior is unchanged. + +**Lean (`-no-stack`).** Implicit stack capture is dropped and calls map to the zero-dependency `errx` core plus +stdlib `errors`/`fmt`. Explicit `errors.WithStack` is still preserved as `stacktrace.Classify` (an explicit +request for a stack is honored). + +## API mapping + +| `pkg/errors` | stack-preserving (default) | lean (`-no-stack`) | +|---|---|---| +| `errors.New(msg)` | `stacktrace.ClassifyNew(msg)` | `errors.New(msg)` (stdlib) | +| `errors.Errorf(f, a…)` | `stacktrace.ClassifyNew(fmt.Sprintf(f, a…))` | `fmt.Errorf(f, a…)` | +| `errors.Wrap(err, msg)` | `stacktrace.Wrap(msg, err)` | `errx.Wrap(msg, err)` | +| `errors.Wrapf(err, f, a…)` | `stacktrace.Wrap(fmt.Sprintf(f, a…), err)` | `errx.Wrap(fmt.Sprintf(f, a…), err)` | +| `errors.WithMessage(err, msg)` | `errx.Wrap(msg, err)` | `errx.Wrap(msg, err)` | +| `errors.WithMessagef(err, f, a…)` | `errx.Wrap(fmt.Sprintf(f, a…), err)` | same | +| `errors.WithStack(err)` | `stacktrace.Classify(err)` | `stacktrace.Classify(err)` | +| `errors.Is` / `As` / `Unwrap` | stdlib `errors.*` | same | +| `errors.Cause(err)` | inline root-unwrap + `// TODO(errx-migrate)` | same | + +Notes: + +- **Argument order swaps.** `pkg/errors.Wrap(err, msg)` becomes `errx.Wrap(msg, err)` — the cause and message + arguments are reordered. +- **Nil semantics match.** `pkg/errors.Wrap(nil, …)` and `errx.Wrap(…, nil)` both return `nil`. +- **`fmt.Sprintf` injection is flagged.** Where a dynamic message is injected (`Wrapf`, `WithMessagef`, and + stack-mode `Errorf`), a `// TODO(errx-migrate)` notes that a dynamic error message is non-idiomatic and a + constant message string is preferred. +- **`errors.Cause`** is rewritten to an inline root-unwrap loop with a `// TODO(errx-migrate)` recommending you + review it (often `errors.Is`/`As` is the better fit). +- **`%+v`** stack formatting is left untouched; with stack-preserving mode and a recent `errx`, the captured + trace still renders via `%+v`. + +## Limitations + +The migrator is deliberately conservative: when it cannot prove a rewrite safe, it leaves the call in place +with a `// TODO(errx-migrate)` comment for manual review rather than guess. In practice this happens for: + +- a `pkg/errors` call buried inside another (for example inside a closure passed to the call being wrapped); +- a `Wrapf`/`Errorf`/`WithMessagef` whose format string contains `%w` (which `fmt.Sprintf` cannot render); +- a comment sitting between the arguments of a call whose arguments are reordered. + +Other notes: + +- **Build tags / `GOOS`.** Only files that type-check for the current `GOOS`/`GOARCH` are rewritten. Re-run + with `GOOS=windows`, `GOOS=darwin`, etc. to cover platform-specific files. +- **Test files** are migrated too. +- The target packages must type-check (the tool relies on full type information). + +## As a vet/golangci-lint analyzer + +The rewriter is also exposed as a [`go/analysis`](https://pkg.go.dev/golang.org/x/tools/go/analysis) Analyzer +that emits `SuggestedFix`es, so it can run under `go vet`, `gopls`, or golangci-lint. + +## Development + +```bash +make build # build bin/errx-migrate +make test # go test -race ./... +make lint # golangci-lint run ./... +make fmt # golangci-lint run --fix ./... +``` + +## License + +MIT — see [LICENSE](LICENSE). diff --git a/analyzer.go b/analyzer.go new file mode 100644 index 0000000..3043f08 --- /dev/null +++ b/analyzer.go @@ -0,0 +1,33 @@ +package errxmigrate + +import "golang.org/x/tools/go/analysis" + +// NewAnalyzer returns an analysis.Analyzer that rewrites pkg/errors usage to +// errx in the given mode, reporting each change as a diagnostic carrying a +// SuggestedFix. It can be run under go vet, gopls, or golangci-lint. +// +// Note: the suggested fixes include import additions and removals, but import +// grouping is left to a formatter (gofmt/goimports); run organize-imports after +// applying fixes for tidy output. +func NewAnalyzer(mode Mode) *analysis.Analyzer { + name := "errxmigrate" + if mode == ModeLean { + name = "errxmigratelean" + } + return &analysis.Analyzer{ + Name: name, + Doc: "rewrites github.com/pkg/errors usage to github.com/go-extras/errx (" + mode.String() + " mode)", + Run: func(pass *analysis.Pass) (any, error) { + for _, d := range Rewrite(PassView(pass), Options{Mode: mode}) { + pass.Report(d) + } + return nil, nil + }, + } +} + +// AnalyzerStack is the default, stack-preserving analyzer. +var AnalyzerStack = NewAnalyzer(ModeStack) + +// AnalyzerLean is the lean (-no-stack) analyzer. +var AnalyzerLean = NewAnalyzer(ModeLean) diff --git a/analyzer_test.go b/analyzer_test.go new file mode 100644 index 0000000..2460eec --- /dev/null +++ b/analyzer_test.go @@ -0,0 +1,27 @@ +package errxmigrate_test + +import ( + "path/filepath" + "testing" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/analysis/analysistest" + + errxmigrate "github.com/go-extras/errx-migrate" +) + +func TestAnalyzersValidate(t *testing.T) { + if err := analysis.Validate([]*analysis.Analyzer{errxmigrate.AnalyzerStack, errxmigrate.AnalyzerLean}); err != nil { + t.Fatal(err) + } +} + +// TestAnalyzerStack exercises the Analyzer front-end wiring: it confirms the +// expected diagnostics are reported for a fixture package. +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") +} diff --git a/apply.go b/apply.go new file mode 100644 index 0000000..e72e5d5 --- /dev/null +++ b/apply.go @@ -0,0 +1,65 @@ +package errxmigrate + +import ( + "fmt" + "go/token" + "sort" + + "golang.org/x/tools/go/analysis" +) + +// Apply applies the text edits to src and returns the rewritten bytes. The +// edits must be non-overlapping; their positions are resolved against fset. The +// result is not formatted — run gofmt or goimports afterwards. +func Apply(fset *token.FileSet, src []byte, edits []analysis.TextEdit) ([]byte, error) { + type offEdit struct { + start, end int + text []byte + } + resolved := make([]offEdit, 0, len(edits)) + for _, e := range edits { + start := fset.Position(e.Pos).Offset + end := start + if e.End.IsValid() { + end = fset.Position(e.End).Offset + } + if start < 0 || end > len(src) || start > end { + return nil, fmt.Errorf("edit out of bounds: [%d,%d) of %d", start, end, len(src)) + } + resolved = append(resolved, offEdit{start: start, end: end, text: e.NewText}) + } + // Apply from the highest offset down so earlier offsets stay valid. + sort.SliceStable(resolved, func(i, j int) bool { + if resolved[i].start != resolved[j].start { + return resolved[i].start > resolved[j].start + } + return resolved[i].end > resolved[j].end + }) + out := src + prevStart := len(src) + 1 + for _, e := range resolved { + if e.end > prevStart { + return nil, fmt.Errorf("overlapping edits near offset %d", e.start) + } + next := make([]byte, 0, len(out)-(e.end-e.start)+len(e.text)) + next = append(next, out[:e.start]...) + next = append(next, e.text...) + next = append(next, out[e.end:]...) + out = next + prevStart = e.start + } + return out, nil +} + +// EditsFor returns all text edits contained in the diagnostics, grouped by the +// file they apply to (keyed by the file name from fset). +func EditsFor(fset *token.FileSet, diags []analysis.Diagnostic) map[string][]analysis.TextEdit { + byFile := make(map[string][]analysis.TextEdit) + for _, d := range diags { + name := fset.Position(d.Pos).Filename + for _, sf := range d.SuggestedFixes { + byFile[name] = append(byFile[name], sf.TextEdits...) + } + } + return byFile +} diff --git a/build_edits.go b/build_edits.go new file mode 100644 index 0000000..03170b5 --- /dev/null +++ b/build_edits.go @@ -0,0 +1,307 @@ +package errxmigrate + +import ( + "fmt" + "go/ast" + "go/token" + "strconv" + "strings" +) + +// buildCtx carries the state needed to render replacement text for a single +// outermost pkg/errors call (and any nested calls it contains). +type buildCtx struct { + view PkgView + file *ast.File + src []byte + tf *token.File + mode Mode + // addImports collects the import paths the rendered text depends on. + addImports map[string]struct{} +} + +// rewrite is the result of translating one pkg/errors call. +type rewrite struct { + // newText replaces the entire call expression. Empty when leaveInPlace. + newText string + // message is the diagnostic message. + message string + // todo, if non-empty, is a comment (without the leading "// ") inserted on + // its own line(s) above the statement containing the call. + todo string + // leaveInPlace means the call is not rewritten; only the todo is added and + // the pkg/errors import is kept. + leaveInPlace bool +} + +func (c *buildCtx) need(path string) { c.addImports[path] = struct{}{} } + +// text returns the original source text of node n. +func (c *buildCtx) text(n ast.Node) string { + return string(c.src[c.tf.Offset(n.Pos()):c.tf.Offset(n.End())]) +} + +// joinArgs renders call.Args[from:] as comma-separated source text, preserving +// a trailing ellipsis (variadic spread) on the final argument. +func (c *buildCtx) joinArgs(call *ast.CallExpr, from int) string { + parts := make([]string, 0, len(call.Args)-from) + last := len(call.Args) - 1 + for i := from; i < len(call.Args); i++ { + t := c.text(call.Args[i]) + if i == last && call.Ellipsis.IsValid() { + t += "..." + } + parts = append(parts, t) + } + return strings.Join(parts, ", ") +} + +// buildRewrite dispatches to the per-function builder for the matched call. +func buildRewrite(c *buildCtx, m match) (rewrite, bool) { + if commentInCallArgs(c.file, m.call) { + return leaveRewrite(m, "a comment between its arguments would be lost on reordering"), true + } + switch m.fn { + case fnNew: + return c.buildNew(m), true + case fnErrorf: + return c.buildErrorf(m), true + case fnWrap: + return c.buildWrap(m), true + case fnWrapf: + return c.buildWrapf(m), true + case fnWithMessage: + return c.buildWithMessage(m), true + case fnWithMessagef: + return c.buildWithMessagef(m), true + case fnWithStack: + return c.buildWithStack(m), true + case fnCause: + return c.buildCause(m), true + case fnIs, fnAs, fnUnwrap: + return c.buildPassthrough(m), true + default: + return rewrite{}, false + } +} + +// renderCause renders the cause/error argument of a wrapping call, applying +// nested pkg/errors rewrites. The boolean result is false when a nested +// pkg/errors reference could not be rewritten safely, signalling the caller to +// leave its own call untouched. +func (c *buildCtx) renderCause(expr ast.Expr) (string, bool) { + if call, ok := expr.(*ast.CallExpr); ok { + if m, ok := matchCall(call, c.view.TypesInfo()); ok { + rw, handled := buildRewrite(c, m) + if handled && !rw.leaveInPlace && rw.newText != "" { + return rw.newText, true + } + return "", false + } + } + if c.exprHasPkgErrorsRef(expr) { + return "", false + } + return c.text(expr), true +} + +// exprHasPkgErrorsRef reports whether expr contains any reference to pkg/errors. +func (c *buildCtx) exprHasPkgErrorsRef(expr ast.Expr) bool { + found := false + ast.Inspect(expr, func(n ast.Node) bool { + id, ok := n.(*ast.Ident) + if ok && isPkgErrorsRef(id, c.view.TypesInfo()) { + found = true + } + return !found + }) + return found +} + +func (c *buildCtx) buildNew(m match) rewrite { + msg := c.text(m.call.Args[0]) + if c.mode == ModeStack { + c.need(stacktracePath) + return rewrite{newText: "stacktrace.ClassifyNew(" + msg + ")", message: msgFor(m, "stacktrace.ClassifyNew")} + } + c.need(stdErrorsPath) + return rewrite{newText: "errors.New(" + msg + ")", message: msgFor(m, "errors.New")} +} + +func (c *buildCtx) buildErrorf(m match) rewrite { + // No format arguments: equivalent to New. + if len(m.call.Args) == 1 { + msg := c.text(m.call.Args[0]) + if c.mode == ModeStack { + c.need(stacktracePath) + return rewrite{newText: "stacktrace.ClassifyNew(" + msg + ")", message: msgFor(m, "stacktrace.ClassifyNew")} + } + c.need(stdErrorsPath) + return rewrite{newText: "errors.New(" + msg + ")", message: msgFor(m, "errors.New")} + } + if c.mode == ModeLean { + // fmt.Errorf is idiomatic and supports %w; no Sprintf, no TODO. + c.need(fmtPath) + return rewrite{newText: "fmt.Errorf(" + c.joinArgs(m.call, 0) + ")", message: msgFor(m, "fmt.Errorf")} + } + if rw, leave := checkWrapVerb(m); leave { + return rw + } + c.need(stacktracePath) + c.need(fmtPath) + return rewrite{ + newText: "stacktrace.ClassifyNew(fmt.Sprintf(" + c.joinArgs(m.call, 0) + "))", + message: msgFor(m, "stacktrace.ClassifyNew"), + todo: sprintfTODO(m), + } +} + +func (c *buildCtx) buildWrap(m match) rewrite { + cause, ok := c.renderCause(m.call.Args[0]) + if !ok { + return leaveRewrite(m, "it wraps another pkg/errors call that could not be rewritten") + } + msg := c.text(m.call.Args[1]) + return c.wrapCall(m, msg, cause) +} + +func (c *buildCtx) buildWrapf(m match) rewrite { + cause, ok := c.renderCause(m.call.Args[0]) + if !ok { + return leaveRewrite(m, "it wraps another pkg/errors call that could not be rewritten") + } + // No format arguments: equivalent to Wrap. + if len(m.call.Args) == 2 { + return c.wrapCall(m, c.text(m.call.Args[1]), cause) + } + if rw, leave := checkWrapVerb(m); leave { + return rw + } + c.need(fmtPath) + msg := "fmt.Sprintf(" + c.joinArgs(m.call, 1) + ")" + rw := c.wrapCall(m, msg, cause) + rw.todo = sprintfTODO(m) + return rw +} + +func (c *buildCtx) buildWithMessage(m match) rewrite { + cause, ok := c.renderCause(m.call.Args[0]) + if !ok { + return leaveRewrite(m, "it wraps another pkg/errors call that could not be rewritten") + } + c.need(errxPath) + return rewrite{newText: "errx.Wrap(" + c.text(m.call.Args[1]) + ", " + cause + ")", message: msgFor(m, "errx.Wrap")} +} + +func (c *buildCtx) buildWithMessagef(m match) rewrite { + cause, ok := c.renderCause(m.call.Args[0]) + if !ok { + return leaveRewrite(m, "it wraps another pkg/errors call that could not be rewritten") + } + c.need(errxPath) + if len(m.call.Args) == 2 { + return rewrite{newText: "errx.Wrap(" + c.text(m.call.Args[1]) + ", " + cause + ")", message: msgFor(m, "errx.Wrap")} + } + if rw, leave := checkWrapVerb(m); leave { + return rw + } + c.need(fmtPath) + msg := "fmt.Sprintf(" + c.joinArgs(m.call, 1) + ")" + return rewrite{newText: "errx.Wrap(" + msg + ", " + cause + ")", message: msgFor(m, "errx.Wrap"), todo: sprintfTODO(m)} +} + +func (c *buildCtx) buildWithStack(m match) rewrite { + cause, ok := c.renderCause(m.call.Args[0]) + if !ok { + return leaveRewrite(m, "it wraps another pkg/errors call that could not be rewritten") + } + c.need(stacktracePath) + return rewrite{newText: "stacktrace.Classify(" + cause + ")", message: msgFor(m, "stacktrace.Classify")} +} + +func (c *buildCtx) buildCause(m match) rewrite { + arg := c.text(m.call.Args[0]) + c.need(stdErrorsPath) + return rewrite{ + newText: causeIIFE(arg), + message: "errors.Cause has no direct errx equivalent; rewritten to an inline root-unwrap loop", + todo: causeTODO, + } +} + +// buildPassthrough handles Is/As/Unwrap, which map to the standard library. +func (c *buildCtx) buildPassthrough(m match) rewrite { + c.need(stdErrorsPath) + return rewrite{ + newText: "errors." + m.name + "(" + c.joinArgs(m.call, 0) + ")", + message: msgFor(m, "errors."+m.name), + } +} + +// wrapCall builds the swapped-argument wrap call for the current mode. +func (c *buildCtx) wrapCall(m match, msg, cause string) rewrite { + if c.mode == ModeStack { + c.need(stacktracePath) + return rewrite{newText: "stacktrace.Wrap(" + msg + ", " + cause + ")", message: msgFor(m, "stacktrace.Wrap")} + } + c.need(errxPath) + return rewrite{newText: "errx.Wrap(" + msg + ", " + cause + ")", message: msgFor(m, "errx.Wrap")} +} + +// checkWrapVerb returns a leave-in-place rewrite if the format string literal +// contains %w, which fmt.Sprintf cannot handle. +func checkWrapVerb(m match) (rewrite, bool) { + if formatHasWrapVerb(m.call.Args[1]) { + return leaveRewrite(m, "the format string contains %w, which fmt.Sprintf does not support"), true + } + return rewrite{}, false +} + +func leaveRewrite(m match, reason string) rewrite { + return rewrite{ + leaveInPlace: true, + message: fmt.Sprintf("errors.%s left unchanged: %s", m.name, reason), + todo: fmt.Sprintf("TODO(errx-migrate): could not safely rewrite errors.%s — %s. Review and migrate manually.", m.name, reason), + } +} + +func msgFor(m match, target string) string { + return fmt.Sprintf("errors.%s should be %s", m.name, target) +} + +func sprintfTODO(m match) string { + return fmt.Sprintf( + "TODO(errx-migrate): was errors.%s; a dynamic fmt.Sprintf error message is non-idiomatic —\nprefer a constant message string (+ classifications). Review.", + m.name, + ) +} + +const causeTODO = "TODO(errx-migrate): was errors.Cause; pkg/errors unwrapped to the root cause.\n" + + "Review this — consider errors.Is/As, or extract this loop into a named helper." + +// causeIIFE renders the inline root-unwrap function literal for errors.Cause. +func causeIIFE(arg string) string { + return "func(e error) error {\n" + + "\tfor {\n" + + "\t\tu := errors.Unwrap(e)\n" + + "\t\tif u == nil {\n" + + "\t\t\treturn e\n" + + "\t\t}\n" + + "\t\te = u\n" + + "\t}\n" + + "}(" + arg + ")" +} + +// formatHasWrapVerb reports whether a string-literal format argument contains +// the %w verb. +func formatHasWrapVerb(arg ast.Expr) bool { + lit, ok := arg.(*ast.BasicLit) + if !ok || lit.Kind != token.STRING { + return false + } + s, err := strconv.Unquote(lit.Value) + if err != nil { + return false + } + return strings.Contains(s, "%w") +} diff --git a/cmd/errx-migrate/diff.go b/cmd/errx-migrate/diff.go new file mode 100644 index 0000000..069ada5 --- /dev/null +++ b/cmd/errx-migrate/diff.go @@ -0,0 +1,181 @@ +package main + +import ( + "fmt" + "strings" +) + +const diffContext = 3 + +// unifiedDiff returns a unified diff between a and b, labelled with name. +// It returns an empty string when there is no difference. +func unifiedDiff(name string, a, b []byte) string { + if string(a) == string(b) { + return "" + } + al := splitLines(string(a)) + bl := splitLines(string(b)) + ops := diffOps(al, bl) + hunks := groupHunks(ops) + if len(hunks) == 0 { + return "" + } + var out strings.Builder + fmt.Fprintf(&out, "--- a/%s\n+++ b/%s\n", name, name) + for _, h := range hunks { + writeHunk(&out, al, bl, ops[h.from:h.to]) + } + return out.String() +} + +func splitLines(s string) []string { + if s == "" { + return nil + } + lines := strings.SplitAfter(s, "\n") + if lines[len(lines)-1] == "" { + lines = lines[:len(lines)-1] + } + return lines +} + +// op describes one line operation in the diff. +type op struct { + kind byte // ' ' equal, '-' delete, '+' insert + ai, bi int // 0-based line indices in a and b +} + +// diffOps computes a line-level diff via a longest-common-subsequence table. +func diffOps(a, b []string) []op { + n, m := len(a), len(b) + lcs := make([][]int, n+1) + for i := range lcs { + lcs[i] = make([]int, m+1) + } + for i := n - 1; i >= 0; i-- { + for j := m - 1; j >= 0; j-- { + switch { + case a[i] == b[j]: + lcs[i][j] = lcs[i+1][j+1] + 1 + case lcs[i+1][j] >= lcs[i][j+1]: + lcs[i][j] = lcs[i+1][j] + default: + lcs[i][j] = lcs[i][j+1] + } + } + } + return backtrack(a, b, lcs) +} + +func backtrack(a, b []string, lcs [][]int) []op { + n, m := len(a), len(b) + var ops []op + i, j := 0, 0 + for i < n && j < m { + switch { + case a[i] == b[j]: + ops = append(ops, op{kind: ' ', ai: i, bi: j}) + i++ + j++ + case lcs[i+1][j] >= lcs[i][j+1]: + ops = append(ops, op{kind: '-', ai: i, bi: j}) + i++ + default: + ops = append(ops, op{kind: '+', ai: i, bi: j}) + j++ + } + } + for ; i < n; i++ { + ops = append(ops, op{kind: '-', ai: i, bi: j}) + } + for ; j < m; j++ { + ops = append(ops, op{kind: '+', ai: i, bi: j}) + } + return ops +} + +// hunk is a contiguous run of operations to display with surrounding context. +type hunk struct { + from, to int // indices into the ops slice +} + +// groupHunks selects the operation ranges that contain changes, padded by +// diffContext equal lines, merging overlapping ranges. +func groupHunks(ops []op) []hunk { + var hunks []hunk + for i, o := range ops { + if o.kind == ' ' { + continue + } + lo := max(0, i-diffContext) + hi := min(len(ops), i+diffContext+1) + if len(hunks) > 0 && lo <= hunks[len(hunks)-1].to { + if hi > hunks[len(hunks)-1].to { + hunks[len(hunks)-1].to = hi + } + continue + } + hunks = append(hunks, hunk{from: lo, to: hi}) + } + return hunks +} + +// lineRange is the (a, b) span covered by a hunk, in 1-based line numbers. +type lineRange struct { + aStart, aCount, bStart, bCount int +} + +func writeHunk(out *strings.Builder, a, b []string, ops []op) { + r := hunkRanges(ops) + fmt.Fprintf(out, "@@ -%s +%s @@\n", rangeStr(r.aStart, r.aCount), rangeStr(r.bStart, r.bCount)) + for _, o := range ops { + switch o.kind { + case ' ': + out.WriteByte(' ') + out.WriteString(a[o.ai]) + case '-': + out.WriteByte('-') + out.WriteString(a[o.ai]) + case '+': + out.WriteByte('+') + out.WriteString(b[o.bi]) + } + } +} + +func hunkRanges(ops []op) lineRange { + aStart, bStart := -1, -1 + var aCount, bCount int + for _, o := range ops { + if o.kind != '+' { + if aStart < 0 { + aStart = o.ai + } + aCount++ + } + if o.kind != '-' { + if bStart < 0 { + bStart = o.bi + } + bCount++ + } + } + if aStart < 0 { + aStart = 0 + } + if bStart < 0 { + bStart = 0 + } + return lineRange{aStart: aStart + 1, aCount: aCount, bStart: bStart + 1, bCount: bCount} +} + +func rangeStr(start, count int) string { + switch count { + case 0: + return fmt.Sprintf("%d,0", start-1) + case 1: + return fmt.Sprintf("%d", start) + default: + return fmt.Sprintf("%d,%d", start, count) + } +} diff --git a/cmd/errx-migrate/main.go b/cmd/errx-migrate/main.go new file mode 100644 index 0000000..bf65737 --- /dev/null +++ b/cmd/errx-migrate/main.go @@ -0,0 +1,177 @@ +// Command errx-migrate rewrites a github.com/pkg/errors-based codebase to use +// github.com/go-extras/errx. It is the command-line front-end for the +// errxmigrate rewrite core. +package main + +import ( + "flag" + "fmt" + "go/token" + "os" + "sort" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/packages" + "golang.org/x/tools/imports" + + errxmigrate "github.com/go-extras/errx-migrate" +) + +// Build information, set via -ldflags at release time. +var ( + version = "dev" + commit = "none" + date = "unknown" +) + +type options struct { + mode errxmigrate.Mode + diff bool + write bool + includeGenerated bool +} + +func main() { + noStack := flag.Bool("no-stack", false, "lean mode: map to the errx core + stdlib, dropping implicit stacks") + doDiff := flag.Bool("diff", false, "print a unified diff instead of writing or printing files") + write := flag.Bool("w", false, "write the result back to source files") + includeGenerated := flag.Bool("include-generated", false, "also rewrite generated files") + showVersion := flag.Bool("version", false, "print version information and exit") + flag.Parse() + + if *showVersion { + fmt.Printf("errx-migrate %s (%s) %s\n", version, commit, date) + return + } + + patterns := flag.Args() + if len(patterns) == 0 { + patterns = []string{"./..."} + } + mode := errxmigrate.ModeStack + if *noStack { + mode = errxmigrate.ModeLean + } + opts := options{mode: mode, diff: *doDiff, write: *write, includeGenerated: *includeGenerated} + if err := run(opts, patterns); err != nil { + fmt.Fprintln(os.Stderr, "errx-migrate:", err) + os.Exit(1) + } +} + +func run(opts options, patterns []string) error { + fset := token.NewFileSet() + cfg := &packages.Config{ + Fset: fset, + Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | + packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | + packages.NeedImports | packages.NeedDeps, + // Load test files too. A file may then appear in several package + // variants (p, p.test, p_test); gatherEdits deduplicates the edits. + Tests: true, + } + pkgs, err := packages.Load(cfg, patterns...) + if err != nil { + return err + } + reportLoadErrors(pkgs) + + byFile := gatherEdits(fset, pkgs, opts) + return emit(fset, byFile, opts) +} + +// reportLoadErrors warns about packages that failed to type-check; such +// packages are still processed best-effort by go/packages. +func reportLoadErrors(pkgs []*packages.Package) { + packages.Visit(pkgs, nil, func(pkg *packages.Package) { + for _, e := range pkg.Errors { + fmt.Fprintf(os.Stderr, "errx-migrate: warning: %s: %s\n", pkg.PkgPath, e) + } + }) +} + +// gatherEdits runs the rewrite core over each loaded package and groups the +// resulting text edits by file path. +func gatherEdits(fset *token.FileSet, pkgs []*packages.Package, opts options) map[string][]analysis.TextEdit { + byFile := make(map[string][]analysis.TextEdit) + seen := make(map[string]bool) + for _, pkg := range pkgs { + if pkg.TypesInfo == nil || len(pkg.Syntax) == 0 { + continue + } + diags := errxmigrate.Rewrite(errxmigrate.PackageView(pkg), + errxmigrate.Options{Mode: opts.mode, IncludeGenerated: opts.includeGenerated}) + for name, edits := range errxmigrate.EditsFor(fset, diags) { + for _, e := range edits { + // Key on byte offsets, not token.Pos: with Tests:true a file is + // re-parsed per package variant, giving identical edits at + // different token positions but the same byte range. + key := fmt.Sprintf("%s\x00%d\x00%d\x00%s", + name, fset.Position(e.Pos).Offset, fset.Position(e.End).Offset, e.NewText) + if seen[key] { + continue + } + seen[key] = true + byFile[name] = append(byFile[name], e) + } + } + } + return byFile +} + +// emit applies the edits for each file and writes, diffs, or prints the result. +func emit(fset *token.FileSet, byFile map[string][]analysis.TextEdit, opts options) error { + names := make([]string, 0, len(byFile)) + for name := range byFile { + names = append(names, name) + } + sort.Strings(names) + + var failed int + for _, name := range names { + header := "" + if len(names) > 1 { + header = fmt.Sprintf("// === %s ===\n", name) + } + // A failure on one file should not abort the rest of the migration. + if err := emitFile(fset, name, byFile[name], opts, header); err != nil { + fmt.Fprintf(os.Stderr, "errx-migrate: %v\n", err) + failed++ + } + } + if failed > 0 { + return fmt.Errorf("%d file(s) could not be migrated", failed) + } + return nil +} + +func emitFile(fset *token.FileSet, name string, edits []analysis.TextEdit, opts options, header string) error { + src, err := os.ReadFile(name) + if err != nil { + return err + } + edited, err := errxmigrate.Apply(fset, src, edits) + if err != nil { + return fmt.Errorf("%s: %w", name, err) + } + formatted, err := imports.Process(name, edited, &imports.Options{Comments: true, TabIndent: true}) + if err != nil { + return fmt.Errorf("%s: formatting rewritten source: %w", name, err) + } + if string(formatted) == string(src) { + return nil + } + + switch { + case opts.diff: + fmt.Print(unifiedDiff(name, src, formatted)) + case opts.write: + if err := os.WriteFile(name, formatted, 0o600); err != nil { //nolint:gosec // path comes from the loaded package's file set + return err + } + default: + fmt.Print(header) + os.Stdout.Write(formatted) + } + return nil +} diff --git a/cmd/errx-migrate/main_test.go b/cmd/errx-migrate/main_test.go new file mode 100644 index 0000000..da3feec --- /dev/null +++ b/cmd/errx-migrate/main_test.go @@ -0,0 +1,99 @@ +package main + +import ( + "fmt" + "go/format" + "os" + "path/filepath" + "strings" + "testing" + + errxmigrate "github.com/go-extras/errx-migrate" +) + +const e2eSample = `package app + +import "github.com/pkg/errors" + +func New() error { return errors.New("boom") } + +func Wrap(err error) error { return errors.Wrapf(err, "reading %s", "file") } +` + +// TestEndToEnd runs the full CLI pipeline (load, rewrite, goimports) over a +// temporary module that resolves the errx and pkg/errors stubs, then checks the +// result is gofmt-clean, migrated, and idempotent. +func TestEndToEnd(t *testing.T) { + if testing.Short() { + t.Skip("skipping module build in -short mode") + } + dir := setupModule(t) + t.Chdir(dir) + + if err := run(options{mode: errxmigrate.ModeStack, write: true}, []string{"./..."}); err != nil { + t.Fatalf("run: %v", err) + } + + got := readFile(t, filepath.Join(dir, "app.go")) + if formatted, err := format.Source([]byte(got)); err != nil || string(formatted) != got { + t.Errorf("output is not gofmt-clean (err=%v)\n%s", err, got) + } + if strings.Contains(got, "pkg/errors") { + t.Errorf("pkg/errors still imported:\n%s", got) + } + if !strings.Contains(got, "stacktrace.Wrap") || !strings.Contains(got, "stacktrace.ClassifyNew") { + t.Errorf("expected stacktrace calls in output:\n%s", got) + } + + // Idempotent: a second run must not change anything. + if err := run(options{mode: errxmigrate.ModeStack, write: true}, []string{"./..."}); err != nil { + t.Fatalf("second run: %v", err) + } + if again := readFile(t, filepath.Join(dir, "app.go")); again != got { + t.Errorf("second run changed the file (not idempotent):\n--- first ---\n%s\n--- second ---\n%s", got, again) + } +} + +func setupModule(t *testing.T) string { + t.Helper() + testdata, err := filepath.Abs(filepath.Join("..", "..", "testdata")) + if err != nil { + t.Fatal(err) + } + errxStub := filepath.Join(testdata, "stub", "errx") + pkgErrStub := filepath.Join(testdata, "stub", "pkgerrors") + + dir := t.TempDir() + mod := fmt.Sprintf(`module app + +go 1.25 + +require ( + github.com/go-extras/errx v0.0.0 + github.com/pkg/errors v0.0.0 +) + +replace github.com/go-extras/errx => %s + +replace github.com/pkg/errors => %s +`, errxStub, pkgErrStub) + writeFile(t, filepath.Join(dir, "go.mod"), mod) + writeFile(t, filepath.Join(dir, "app.go"), e2eSample) + return dir +} + +func writeFile(t *testing.T, path, content string) { + t.Helper() + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } +} + +func readFile(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) +} diff --git a/comments.go b/comments.go new file mode 100644 index 0000000..37b11b8 --- /dev/null +++ b/comments.go @@ -0,0 +1,82 @@ +package errxmigrate + +import ( + "go/ast" + "go/token" + "strings" + + "golang.org/x/tools/go/analysis" +) + +// migrateTODOMarker is the marker used in injected review comments. It is also +// used to detect already-migrated leave-in-place sites for idempotency. +const migrateTODOMarker = "TODO(errx-migrate)" + +// commentInCallArgs reports whether a comment sits between the call's arguments +// (inside the parentheses but not within a single argument). Such a comment +// would be lost when arguments are reordered or rebuilt from their AST nodes. +func commentInCallArgs(file *ast.File, call *ast.CallExpr) bool { + lo, hi := call.Lparen, call.Rparen + for _, cg := range file.Comments { + for _, cm := range cg.List { + if cm.Pos() <= lo || cm.End() >= hi { + continue + } + if !commentWithinArgs(call, cm) { + return true + } + } + } + return false +} + +func commentWithinArgs(call *ast.CallExpr, cm *ast.Comment) bool { + for _, a := range call.Args { + if a.Pos() <= cm.Pos() && cm.End() <= a.End() { + return true + } + } + return false +} + +// hasAdjacentMigrateTODO reports whether a TODO(errx-migrate) comment already +// sits on one of the few lines immediately above callPos. It guards against +// re-injecting a marker on a leave-in-place site during a second run. +func hasAdjacentMigrateTODO(tf *token.File, file *ast.File, callPos token.Pos) bool { + callLine := tf.Line(callPos) + for _, cg := range file.Comments { + for _, cm := range cg.List { + line := tf.Line(cm.Pos()) + if line < callLine && line >= callLine-3 && strings.Contains(cm.Text, migrateTODOMarker) { + return true + } + } + } + return false +} + +// todoInsertEdit produces an edit that inserts the multi-line todo comment on +// its own line(s) directly above the line containing callPos, matching that +// line's indentation. +func todoInsertEdit(tf *token.File, src []byte, callPos token.Pos, todo string) analysis.TextEdit { + line := tf.Line(callPos) + lineStart := tf.LineStart(line) + indent := leadingIndent(src, tf.Offset(lineStart)) + var b strings.Builder + for _, ln := range strings.Split(todo, "\n") { + b.WriteString(indent) + b.WriteString("// ") + b.WriteString(ln) + b.WriteString("\n") + } + return analysis.TextEdit{Pos: lineStart, End: lineStart, NewText: []byte(b.String())} +} + +// leadingIndent returns the run of spaces and tabs starting at off in src. +func leadingIndent(src []byte, off int) string { + end := off + for end < len(src) && (src[end] == ' ' || src[end] == '\t') { + end++ + } + return string(src[off:end]) +} diff --git a/detect.go b/detect.go new file mode 100644 index 0000000..9563fa8 --- /dev/null +++ b/detect.go @@ -0,0 +1,120 @@ +package errxmigrate + +import ( + "go/ast" + "go/types" +) + +// Import paths involved in the migration. +const ( + pkgErrorsPath = "github.com/pkg/errors" + errxPath = "github.com/go-extras/errx" + stacktracePath = "github.com/go-extras/errx/stacktrace" + stdErrorsPath = "errors" + fmtPath = "fmt" +) + +// errFn enumerates the pkg/errors functions the migrator recognises. +type errFn int + +const ( + fnNew errFn = iota + fnErrorf + fnWrap + fnWrapf + fnWithMessage + fnWithMessagef + fnWithStack + fnCause + fnIs + fnAs + fnUnwrap +) + +// fnByName maps a pkg/errors exported function name to its errFn. +var fnByName = map[string]errFn{ + "New": fnNew, + "Errorf": fnErrorf, + "Wrap": fnWrap, + "Wrapf": fnWrapf, + "WithMessage": fnWithMessage, + "WithMessagef": fnWithMessagef, + "WithStack": fnWithStack, + "Cause": fnCause, + "Is": fnIs, + "As": fnAs, + "Unwrap": fnUnwrap, +} + +// match describes a recognised pkg/errors call. +type match struct { + fn errFn + call *ast.CallExpr + // name is the pkg/errors function name as written (for example "Wrap"). + name string + // qualifier is the local package name used in the source (for example + // "errors" or an alias). It is empty for a dot-imported call. + qualifier string +} + +// matchCall resolves whether call is a recognised pkg/errors function call, +// using type information so that aliases, dot-imports, and shadowed local +// identifiers are handled correctly. +func matchCall(call *ast.CallExpr, info *types.Info) (match, bool) { + switch fun := call.Fun.(type) { + case *ast.SelectorExpr: + id, ok := fun.X.(*ast.Ident) + if !ok || !isPkgErrorsQualifier(id, info) { + return match{}, false + } + fn, ok := fnByName[fun.Sel.Name] + if !ok { + return match{}, false + } + return match{fn: fn, call: call, name: fun.Sel.Name, qualifier: id.Name}, true + case *ast.Ident: + if !isPkgErrorsFunc(fun, info) { + return match{}, false + } + fn, ok := fnByName[fun.Name] + if !ok { + return match{}, false + } + return match{fn: fn, call: call, name: fun.Name, qualifier: ""}, true + default: + return match{}, false + } +} + +// isPkgErrorsQualifier reports whether id refers to the pkg/errors package. +func isPkgErrorsQualifier(id *ast.Ident, info *types.Info) bool { + pkgName, ok := info.Uses[id].(*types.PkgName) + if !ok { + return false + } + return pkgName.Imported().Path() == pkgErrorsPath +} + +// isPkgErrorsFunc reports whether id refers to a function exported by +// pkg/errors (the dot-import case). +func isPkgErrorsFunc(id *ast.Ident, info *types.Info) bool { + fn, ok := info.Uses[id].(*types.Func) + if !ok { + return false + } + return fn.Pkg() != nil && fn.Pkg().Path() == pkgErrorsPath +} + +// isPkgErrorsRef reports whether the identifier refers to the pkg/errors +// package qualifier or to a dot-imported pkg/errors symbol. It is used to count +// references that still depend on the pkg/errors import. +func isPkgErrorsRef(id *ast.Ident, info *types.Info) bool { + switch obj := info.Uses[id].(type) { + case *types.PkgName: + return obj.Imported().Path() == pkgErrorsPath + case *types.Func: + return obj.Pkg() != nil && obj.Pkg().Path() == pkgErrorsPath + default: + return false + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..0fc7db0 --- /dev/null +++ b/go.mod @@ -0,0 +1,10 @@ +module github.com/go-extras/errx-migrate + +go 1.25.0 + +require golang.org/x/tools v0.45.0 + +require ( + golang.org/x/mod v0.36.0 // indirect + golang.org/x/sync v0.20.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..be8b55b --- /dev/null +++ b/go.sum @@ -0,0 +1,8 @@ +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4= +golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= +golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= diff --git a/golden_test.go b/golden_test.go new file mode 100644 index 0000000..7f6a7e7 --- /dev/null +++ b/golden_test.go @@ -0,0 +1,97 @@ +package errxmigrate_test + +import ( + "flag" + "go/format" + "go/token" + "os" + "path/filepath" + "testing" + + "golang.org/x/tools/go/packages" + + errxmigrate "github.com/go-extras/errx-migrate" +) + +var update = flag.Bool("update", false, "update golden files") + +const loadMode = packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | + packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | + packages.NeedImports | packages.NeedDeps + +type modeInfo struct { + mode errxmigrate.Mode + ext string +} + +var modes = []modeInfo{ + {errxmigrate.ModeStack, "stack"}, + {errxmigrate.ModeLean, "lean"}, +} + +// TestGolden runs the rewrite core over every fixture package in both modes, +// applies the resulting edits, gofmt-formats the output, and compares it to the +// committed golden file. Run with -update to regenerate the golden files. +func TestGolden(t *testing.T) { + fset := token.NewFileSet() + dir := testdataDir(t) + cfg := &packages.Config{Dir: dir, Fset: fset, Mode: loadMode} + pkgs, err := packages.Load(cfg, "./src/...") + if err != nil { + t.Fatalf("loading fixtures: %v", err) + } + if n := packages.PrintErrors(pkgs); n > 0 { + t.Fatalf("fixtures have %d load/type errors", n) + } + + for _, pkg := range pkgs { + name := filepath.Base(filepath.Dir(pkg.GoFiles[0])) + for _, mi := range modes { + t.Run(name+"/"+mi.ext, func(t *testing.T) { + checkGolden(t, fset, pkg, mi) + }) + } + } +} + +func checkGolden(t *testing.T, fset *token.FileSet, pkg *packages.Package, mi modeInfo) { + t.Helper() + file := pkg.GoFiles[0] + src, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + diags := errxmigrate.Rewrite(errxmigrate.PackageView(pkg), errxmigrate.Options{Mode: mi.mode}) + edited, err := errxmigrate.Apply(fset, src, errxmigrate.EditsFor(fset, diags)[file]) + if err != nil { + t.Fatalf("applying edits: %v", err) + } + formatted, err := format.Source(edited) + if err != nil { + t.Fatalf("gofmt of rewritten source failed: %v\n--- source ---\n%s", err, edited) + } + + goldenPath := filepath.Join(filepath.Dir(file), "in."+mi.ext+".golden") + if *update { + if err := os.WriteFile(goldenPath, formatted, 0o600); err != nil { //nolint:gosec // goldenPath is under the test's own testdata tree + t.Fatal(err) + } + return + } + want, err := os.ReadFile(goldenPath) + if err != nil { + t.Fatalf("reading golden (run -update to create): %v", err) + } + if string(formatted) != string(want) { + t.Errorf("output mismatch for %s\n--- got ---\n%s\n--- want ---\n%s", goldenPath, formatted, want) + } +} + +func testdataDir(t *testing.T) string { + t.Helper() + abs, err := filepath.Abs("testdata") + if err != nil { + t.Fatal(err) + } + return abs +} diff --git a/imports.go b/imports.go new file mode 100644 index 0000000..180a811 --- /dev/null +++ b/imports.go @@ -0,0 +1,128 @@ +package errxmigrate + +import ( + "go/ast" + "go/token" + "sort" + "strconv" + "strings" + + "golang.org/x/tools/go/analysis" +) + +// importedPaths returns the set of import paths already present in the file. +func importedPaths(file *ast.File) map[string]bool { + out := make(map[string]bool, len(file.Imports)) + for _, spec := range file.Imports { + if p, err := strconv.Unquote(spec.Path.Value); err == nil { + out[p] = true + } + } + return out +} + +// firstImportDecl returns the file's first import declaration, or nil. +func firstImportDecl(file *ast.File) *ast.GenDecl { + for _, decl := range file.Decls { + if gd, ok := decl.(*ast.GenDecl); ok && gd.Tok == token.IMPORT { + return gd + } + } + return nil +} + +// pkgErrorsImport returns the local name pkg/errors is imported under and its +// spec. The name is "errors" for an unnamed import, or the alias/"." otherwise. +func pkgErrorsImport(file *ast.File) (name string, spec *ast.ImportSpec, ok bool) { + for _, s := range file.Imports { + p, err := strconv.Unquote(s.Path.Value) + if err != nil || p != pkgErrorsPath { + continue + } + if s.Name != nil { + return s.Name.Name, s, true + } + return "errors", s, true + } + return "", nil, false +} + +// addImportEdits returns edits that add the given import paths to the file. +// Output is left for gofmt to sort and group. +func addImportEdits(file *ast.File, paths []string) []analysis.TextEdit { + have := importedPaths(file) + missing := make([]string, 0, len(paths)) + for _, p := range paths { + if !have[p] { + missing = append(missing, p) + } + } + if len(missing) == 0 { + return nil + } + sort.Strings(missing) + + decl := firstImportDecl(file) + switch { + case decl != nil && decl.Lparen.IsValid(): + return []analysis.TextEdit{{Pos: decl.Lparen + 1, End: decl.Lparen + 1, NewText: importLines(missing, "\n\t")}} + case decl != nil: + return []analysis.TextEdit{{Pos: decl.End(), End: decl.End(), NewText: importLines(missing, "\nimport ")}} + default: + var b strings.Builder + b.WriteString("\n\nimport (") + b.Write(importLines(missing, "\n\t")) + b.WriteString("\n)") + return []analysis.TextEdit{{Pos: file.Name.End(), End: file.Name.End(), NewText: []byte(b.String())}} + } +} + +// importLines renders each path as prefix+quoted(path). +func importLines(paths []string, prefix string) []byte { + var b strings.Builder + for _, p := range paths { + b.WriteString(prefix) + b.WriteString(strconv.Quote(p)) + } + return []byte(b.String()) +} + +// removeImportEdit returns an edit that removes the import of path, if present. +// When the import lives alone in a parenthesised block, the whole declaration +// is removed; otherwise just its line is removed. +func removeImportEdit(tf *token.File, file *ast.File, path string) (analysis.TextEdit, bool) { + decl := firstImportDecl(file) + if decl == nil { + return analysis.TextEdit{}, false + } + var target *ast.ImportSpec + for _, s := range file.Imports { + if p, err := strconv.Unquote(s.Path.Value); err == nil && p == path { + target = s + break + } + } + if target == nil { + return analysis.TextEdit{}, false + } + // Remove the entire declaration when it holds only this import. + if !decl.Lparen.IsValid() || len(decl.Specs) == 1 { + return wholeLinesEdit(tf, decl.Pos(), decl.End()), true + } + return wholeLinesEdit(tf, target.Pos(), target.End()), true +} + +// wholeLinesEdit returns an edit covering the full lines spanned by [from, to), +// including the trailing newline, so removal leaves no blank line. +func wholeLinesEdit(tf *token.File, from, to token.Pos) analysis.TextEdit { + startLine := tf.Line(from) + endLine := tf.Line(to) + start := tf.LineStart(startLine) + var end token.Pos + if endLine < tf.LineCount() { + end = tf.LineStart(endLine + 1) + } else { + end = to + } + return analysis.TextEdit{Pos: start, End: end} +} diff --git a/mode.go b/mode.go new file mode 100644 index 0000000..4d6f12e --- /dev/null +++ b/mode.go @@ -0,0 +1,34 @@ +// Package errxmigrate rewrites code that uses github.com/pkg/errors so that it +// uses github.com/go-extras/errx instead. The rewrite is type-aware (it relies +// on go/types information to recognise pkg/errors calls) and produces edits as +// golang.org/x/tools/go/analysis text edits, so the same core drives both the +// command-line tool and the analysis.Analyzer. +package errxmigrate + +import "fmt" + +// Mode selects how stack-capturing pkg/errors calls are translated. +type Mode int + +const ( + // ModeStack is the default, stack-preserving mode. Stack-capturing calls + // map to the github.com/go-extras/errx/stacktrace subpackage so runtime + // behaviour is unchanged. + ModeStack Mode = iota + // ModeLean maps to the zero-dependency errx core plus the standard library, + // dropping implicit stack capture. Explicit errors.WithStack is still + // preserved as stacktrace.Classify. + ModeLean +) + +// String returns a human-readable name for the mode. +func (m Mode) String() string { + switch m { + case ModeStack: + return "stack" + case ModeLean: + return "lean" + default: + return fmt.Sprintf("Mode(%d)", int(m)) + } +} diff --git a/pkgview.go b/pkgview.go new file mode 100644 index 0000000..6307124 --- /dev/null +++ b/pkgview.go @@ -0,0 +1,76 @@ +package errxmigrate + +import ( + "go/ast" + "go/token" + "go/types" + "os" + + "golang.org/x/tools/go/analysis" + "golang.org/x/tools/go/packages" +) + +// PkgView is the minimal view of a type-checked package that the rewrite core +// needs. It is implemented by thin adapters over *analysis.Pass (for the +// Analyzer front-end) and *packages.Package (for the CLI front-end), so the +// core never needs to know which driver loaded the package. +type PkgView interface { + // Fset is the file set the package's syntax was parsed with. + Fset() *token.FileSet + // Files are the parsed syntax trees of the package's Go files. + Files() []*ast.File + // TypesInfo carries the resolved type information for the package. + TypesInfo() *types.Info + // Source returns the original source bytes of the file f. + Source(f *ast.File) ([]byte, error) +} + +// passView adapts an *analysis.Pass to PkgView. +type passView struct { + pass *analysis.Pass +} + +// PassView returns a PkgView backed by an *analysis.Pass. +func PassView(pass *analysis.Pass) PkgView { + return &passView{pass: pass} +} + +func (v *passView) Fset() *token.FileSet { return v.pass.Fset } +func (v *passView) Files() []*ast.File { return v.pass.Files } +func (v *passView) TypesInfo() *types.Info { return v.pass.TypesInfo } + +func (v *passView) Source(f *ast.File) ([]byte, error) { + name := v.pass.Fset.File(f.FileStart).Name() + if v.pass.ReadFile != nil { + return v.pass.ReadFile(name) + } + return os.ReadFile(name) +} + +// packageView adapts a *packages.Package to PkgView, caching file source bytes. +type packageView struct { + pkg *packages.Package + cache map[string][]byte +} + +// PackageView returns a PkgView backed by a *packages.Package. +func PackageView(pkg *packages.Package) PkgView { + return &packageView{pkg: pkg, cache: make(map[string][]byte)} +} + +func (v *packageView) Fset() *token.FileSet { return v.pkg.Fset } +func (v *packageView) Files() []*ast.File { return v.pkg.Syntax } +func (v *packageView) TypesInfo() *types.Info { return v.pkg.TypesInfo } + +func (v *packageView) Source(f *ast.File) ([]byte, error) { + name := v.pkg.Fset.File(f.FileStart).Name() + if b, ok := v.cache[name]; ok { + return b, nil + } + b, err := os.ReadFile(name) + if err != nil { + return nil, err + } + v.cache[name] = b + return b, nil +} diff --git a/rewrite.go b/rewrite.go new file mode 100644 index 0000000..ed05bd4 --- /dev/null +++ b/rewrite.go @@ -0,0 +1,263 @@ +package errxmigrate + +import ( + "go/ast" + "go/token" + "go/types" + "regexp" + + "golang.org/x/tools/go/analysis" +) + +// posRange is a half-open source range. +type posRange struct { + lo, hi token.Pos +} + +// Options configures a Rewrite run. +type Options struct { + // Mode selects stack-preserving or lean translation. + Mode Mode + // IncludeGenerated, when true, also rewrites generated files. + IncludeGenerated bool +} + +// Rewrite analyses the package described by view and returns the diagnostics +// (each carrying a SuggestedFix) needed to migrate pkg/errors usage to errx. +// Generated files are skipped unless opts.IncludeGenerated is set. +func Rewrite(view PkgView, opts Options) []analysis.Diagnostic { + var diags []analysis.Diagnostic + info := view.TypesInfo() + for _, file := range view.Files() { + if !opts.IncludeGenerated && isGenerated(file) { + continue + } + diags = append(diags, rewriteFile(view, opts.Mode, info, file)...) + } + return diags +} + +func rewriteFile(view PkgView, mode Mode, info *types.Info, file *ast.File) []analysis.Diagnostic { + src, err := view.Source(file) + if err != nil { + return nil + } + matches := collectOutermostMatches(file, info) + if len(matches) == 0 { + return nil + } + tf := view.Fset().File(file.Pos()) + + fileAdds := make(map[string]struct{}) + covered := make([]posRange, 0, len(matches)) + diags := make([]analysis.Diagnostic, 0, len(matches)+1) + keptPkgErrors := false + + for _, m := range matches { + c := &buildCtx{view: view, file: file, src: src, tf: tf, mode: mode, addImports: make(map[string]struct{})} + rw, ok := buildRewrite(c, m) + if !ok { + continue + } + for p := range c.addImports { + fileAdds[p] = struct{}{} + } + if rw.leaveInPlace { + keptPkgErrors = true + if d, emitted := leaveDiag(tf, src, file, m, rw); emitted { + diags = append(diags, d) + } + continue + } + covered = append(covered, posRange{m.call.Pos(), m.call.End()}) + diags = append(diags, rewriteDiag(tf, src, m, rw)) + } + + if !keptPkgErrors && hasUncoveredPkgErrorsRef(file, info, covered) { + keptPkgErrors = true + } + if d, ok := importDiag(file, tf, importState{adds: fileAdds, keptPkgErrors: keptPkgErrors}); ok { + diags = append(diags, d) + } + return diags +} + +// importState captures what the file-level import adjustment needs to know. +type importState struct { + adds map[string]struct{} + keptPkgErrors bool +} + +// rewriteDiag builds the diagnostic for a successfully rewritten call. +func rewriteDiag(tf *token.File, src []byte, m match, rw rewrite) analysis.Diagnostic { + edits := []analysis.TextEdit{{Pos: m.call.Pos(), End: m.call.End(), NewText: []byte(rw.newText)}} + if rw.todo != "" { + edits = append(edits, todoInsertEdit(tf, src, m.call.Pos(), rw.todo)) + } + return diagWithFix(m.call, rw.message, edits) +} + +// leaveDiag builds the diagnostic for a left-in-place call, guarding against a +// duplicate TODO on re-runs. +func leaveDiag(tf *token.File, src []byte, file *ast.File, m match, rw rewrite) (analysis.Diagnostic, bool) { + if hasAdjacentMigrateTODO(tf, file, m.call.Pos()) { + return analysis.Diagnostic{}, false + } + edit := todoInsertEdit(tf, src, m.call.Pos(), rw.todo) + return diagWithFix(m.call, rw.message, []analysis.TextEdit{edit}), true +} + +func diagWithFix(call ast.Node, msg string, edits []analysis.TextEdit) analysis.Diagnostic { + return analysis.Diagnostic{ + Pos: call.Pos(), + End: call.End(), + Message: msg, + SuggestedFixes: []analysis.SuggestedFix{{Message: "migrate to errx", TextEdits: edits}}, + } +} + +// importDiag builds the diagnostic carrying the file's import adjustments. +func importDiag(file *ast.File, tf *token.File, st importState) (analysis.Diagnostic, bool) { + pkgErrName, _, hasPkgErr := pkgErrorsImport(file) + adds := make([]string, 0, len(st.adds)) + for p := range st.adds { + // A kept pkg/errors imported as "errors" already provides the name, so + // adding stdlib errors would duplicate it. + if p == stdErrorsPath && st.keptPkgErrors && pkgErrName == "errors" { + continue + } + adds = append(adds, p) + } + + var edits []analysis.TextEdit + removePkgErr := hasPkgErr && !st.keptPkgErrors + switch { + case removePkgErr && len(file.Imports) == 1: + edits = soleImportEdits(tf, file, adds) + default: + edits = addImportEdits(file, adds) + if removePkgErr { + if e, ok := removeImportEdit(tf, file, pkgErrorsPath); ok { + edits = append(edits, e) + } + } + } + if len(edits) == 0 { + return analysis.Diagnostic{}, false + } + pos := importPos(file) + return analysis.Diagnostic{ + Pos: pos, + End: pos, + Message: "adjust imports for errx migration", + SuggestedFixes: []analysis.SuggestedFix{{Message: "adjust imports", TextEdits: edits}}, + }, true +} + +// soleImportEdits replaces an import declaration that holds only pkg/errors: +// either with a fresh block of the needed imports, or with nothing. +func soleImportEdits(tf *token.File, file *ast.File, adds []string) []analysis.TextEdit { + decl := firstImportDecl(file) + if decl == nil { + return nil + } + edit := wholeLinesEdit(tf, decl.Pos(), decl.End()) + if len(adds) > 0 { + var b []byte + b = append(b, "import ("...) + b = append(b, importLines(adds, "\n\t")...) + b = append(b, "\n)\n"...) + edit.NewText = b + } + return []analysis.TextEdit{edit} +} + +func importPos(file *ast.File) token.Pos { + if decl := firstImportDecl(file); decl != nil { + return decl.Pos() + } + return file.Name.Pos() +} + +// collectOutermostMatches finds all recognised pkg/errors calls and returns +// only those not nested inside another recognised call. +func collectOutermostMatches(file *ast.File, info *types.Info) []match { + var all []match + ast.Inspect(file, func(n ast.Node) bool { + if call, ok := n.(*ast.CallExpr); ok { + if m, ok := matchCall(call, info); ok { + all = append(all, m) + } + } + return true + }) + out := make([]match, 0, len(all)) + for i := range all { + if !containedInOther(all, i) { + out = append(out, all[i]) + } + } + return out +} + +func containedInOther(all []match, idx int) bool { + m := all[idx] + for j := range all { + if j == idx { + continue + } + o := all[j] + if o.call == m.call { + continue + } + if o.call.Pos() <= m.call.Pos() && m.call.End() <= o.call.End() { + return true + } + } + return false +} + +func hasUncoveredPkgErrorsRef(file *ast.File, info *types.Info, covered []posRange) bool { + found := false + ast.Inspect(file, func(n ast.Node) bool { + if found { + return false + } + id, ok := n.(*ast.Ident) + if !ok || !isPkgErrorsRef(id, info) { + return true + } + if !posCovered(id.Pos(), covered) { + found = true + } + return true + }) + return found +} + +func posCovered(pos token.Pos, covered []posRange) bool { + for _, r := range covered { + if r.lo <= pos && pos < r.hi { + return true + } + } + return false +} + +var generatedRe = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`) + +// isGenerated reports whether the file carries the standard generated-code +// marker before its package clause. +func isGenerated(file *ast.File) bool { + for _, cg := range file.Comments { + if cg.Pos() > file.Package { + break + } + for _, c := range cg.List { + if generatedRe.MatchString(c.Text) { + return true + } + } + } + return false +} diff --git a/stable_test.go b/stable_test.go new file mode 100644 index 0000000..8ed0ef5 --- /dev/null +++ b/stable_test.go @@ -0,0 +1,114 @@ +package errxmigrate_test + +import ( + "fmt" + "go/token" + "os" + "path/filepath" + "testing" + + "golang.org/x/tools/go/packages" + + errxmigrate "github.com/go-extras/errx-migrate" +) + +// TestGoldensStable assembles every golden file into a temporary module that +// resolves the errx and pkg/errors stubs, then asserts two properties: +// - the migrated output type-checks (it compiles against the stubs); and +// - re-running the migrator on it produces no further edits (idempotent). +func TestGoldensStable(t *testing.T) { + if testing.Short() { + t.Skip("skipping module build in -short mode") + } + stubs := stubPaths(t) + tmp := t.TempDir() + writeGenModule(t, tmp, stubs) + + caseModes := layoutGoldens(t, tmp) + + fset := token.NewFileSet() + cfg := &packages.Config{Dir: tmp, Fset: fset, Mode: loadMode} + pkgs, err := packages.Load(cfg, "./...") + if err != nil { + t.Fatalf("loading migrated goldens: %v", err) + } + if n := packages.PrintErrors(pkgs); n > 0 { + t.Fatalf("migrated goldens have %d type errors", n) + } + + for _, pkg := range pkgs { + dir := filepath.Base(filepath.Dir(pkg.GoFiles[0])) + mode, ok := caseModes[dir] + if !ok { + continue + } + diags := errxmigrate.Rewrite(errxmigrate.PackageView(pkg), errxmigrate.Options{Mode: mode}) + if len(diags) != 0 { + t.Errorf("re-running on %s produced %d edits; want 0 (not idempotent)", dir, len(diags)) + } + } +} + +type stubInfo struct{ errx, pkgErrors string } + +func stubPaths(t *testing.T) stubInfo { + t.Helper() + dir := testdataDir(t) + return stubInfo{ + errx: filepath.Join(dir, "stub", "errx"), + pkgErrors: filepath.Join(dir, "stub", "pkgerrors"), + } +} + +func writeGenModule(t *testing.T, dir string, stubs stubInfo) { + t.Helper() + mod := fmt.Sprintf(`module gen + +go 1.25 + +require ( + github.com/go-extras/errx v0.0.0 + github.com/pkg/errors v0.0.0 +) + +replace github.com/go-extras/errx => %s + +replace github.com/pkg/errors => %s +`, stubs.errx, stubs.pkgErrors) + if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(mod), 0o600); err != nil { + t.Fatal(err) + } +} + +// layoutGoldens writes each golden into its own package directory and returns a +// map from directory name to the mode that produced it. +func layoutGoldens(t *testing.T, dir string) map[string]errxmigrate.Mode { + t.Helper() + srcDir := filepath.Join(testdataDir(t), "src") + entries, err := os.ReadDir(srcDir) + if err != nil { + t.Fatal(err) + } + caseModes := make(map[string]errxmigrate.Mode) + for _, e := range entries { + if !e.IsDir() { + continue + } + for _, mi := range modes { + golden := filepath.Join(srcDir, e.Name(), "in."+mi.ext+".golden") + data, err := os.ReadFile(golden) + if err != nil { + t.Fatal(err) + } + pkgDir := e.Name() + "_" + mi.ext + if err := os.Mkdir(filepath.Join(dir, pkgDir), 0o750); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, pkgDir, "p.go"), data, 0o600); err != nil { //nolint:gosec // dir is t.TempDir() + t.Fatal(err) + } + caseModes[pkgDir] = mi.mode + } + } + return caseModes +} diff --git a/testdata/analyzer/src/example/example.go b/testdata/analyzer/src/example/example.go new file mode 100644 index 0000000..c5abc5b --- /dev/null +++ b/testdata/analyzer/src/example/example.go @@ -0,0 +1,9 @@ +package example + +import "github.com/pkg/errors" // want `adjust imports for errx migration` + +func New() error { return errors.New("boom") } // want `errors.New should be stacktrace.ClassifyNew` + +func Wrap(err error) error { + return errors.Wrap(err, "context") // want `errors.Wrap should be stacktrace.Wrap` +} diff --git a/testdata/analyzer/src/github.com/pkg/errors/errors.go b/testdata/analyzer/src/github.com/pkg/errors/errors.go new file mode 100644 index 0000000..6eac758 --- /dev/null +++ b/testdata/analyzer/src/github.com/pkg/errors/errors.go @@ -0,0 +1,40 @@ +// Package errors is a minimal stand-in for github.com/pkg/errors, used only so +// that migrator test fixtures type-check offline. The bodies are irrelevant. +package errors + +// New returns a new error. +func New(message string) error { return &stub{message} } + +// Errorf formats according to a format specifier. +func Errorf(format string, args ...interface{}) error { return &stub{format} } + +// Wrap annotates err with a message. +func Wrap(err error, message string) error { return err } + +// Wrapf annotates err with a formatted message. +func Wrapf(err error, format string, args ...interface{}) error { return err } + +// WithMessage annotates err with a message, without a stack. +func WithMessage(err error, message string) error { return err } + +// WithMessagef annotates err with a formatted message, without a stack. +func WithMessagef(err error, format string, args ...interface{}) error { return err } + +// WithStack annotates err with a stack trace. +func WithStack(err error) error { return err } + +// Cause returns the underlying root cause of err. +func Cause(err error) error { return err } + +// Is reports whether any error in err's chain matches target. +func Is(err, target error) bool { return false } + +// As finds the first error in err's chain that matches target. +func As(err error, target interface{}) bool { return false } + +// Unwrap returns the result of calling the Unwrap method on err. +func Unwrap(err error) error { return nil } + +type stub struct{ msg string } + +func (s *stub) Error() string { return s.msg } diff --git a/testdata/go.mod b/testdata/go.mod new file mode 100644 index 0000000..188260e --- /dev/null +++ b/testdata/go.mod @@ -0,0 +1,10 @@ +// This is a self-contained module of fixtures for the migrator's golden tests. +// pkg/errors is replaced with a local stub so the fixtures type-check offline +// and the parent module never builds them. +module errxmigratetest + +go 1.25 + +require github.com/pkg/errors v0.0.0 + +replace github.com/pkg/errors => ./stub/pkgerrors diff --git a/testdata/src/aliased/in.go b/testdata/src/aliased/in.go new file mode 100644 index 0000000..fa81c78 --- /dev/null +++ b/testdata/src/aliased/in.go @@ -0,0 +1,7 @@ +package p + +import pkgerr "github.com/pkg/errors" + +func WrapIt(err error) error { return pkgerr.Wrap(err, "context") } + +func Check(err, target error) bool { return pkgerr.Is(err, target) } diff --git a/testdata/src/aliased/in.lean.golden b/testdata/src/aliased/in.lean.golden new file mode 100644 index 0000000..b792b29 --- /dev/null +++ b/testdata/src/aliased/in.lean.golden @@ -0,0 +1,10 @@ +package p + +import ( + "errors" + "github.com/go-extras/errx" +) + +func WrapIt(err error) error { return errx.Wrap("context", err) } + +func Check(err, target error) bool { return errors.Is(err, target) } diff --git a/testdata/src/aliased/in.stack.golden b/testdata/src/aliased/in.stack.golden new file mode 100644 index 0000000..fafba3d --- /dev/null +++ b/testdata/src/aliased/in.stack.golden @@ -0,0 +1,10 @@ +package p + +import ( + "errors" + "github.com/go-extras/errx/stacktrace" +) + +func WrapIt(err error) error { return stacktrace.Wrap("context", err) } + +func Check(err, target error) bool { return errors.Is(err, target) } diff --git a/testdata/src/cause/in.go b/testdata/src/cause/in.go new file mode 100644 index 0000000..a8f5dd5 --- /dev/null +++ b/testdata/src/cause/in.go @@ -0,0 +1,5 @@ +package p + +import "github.com/pkg/errors" + +func Root(err error) error { return errors.Cause(err) } diff --git a/testdata/src/cause/in.lean.golden b/testdata/src/cause/in.lean.golden new file mode 100644 index 0000000..e369812 --- /dev/null +++ b/testdata/src/cause/in.lean.golden @@ -0,0 +1,19 @@ +package p + +import ( + "errors" +) + +// TODO(errx-migrate): was errors.Cause; pkg/errors unwrapped to the root cause. +// Review this — consider errors.Is/As, or extract this loop into a named helper. +func Root(err error) error { + return func(e error) error { + for { + u := errors.Unwrap(e) + if u == nil { + return e + } + e = u + } + }(err) +} diff --git a/testdata/src/cause/in.stack.golden b/testdata/src/cause/in.stack.golden new file mode 100644 index 0000000..e369812 --- /dev/null +++ b/testdata/src/cause/in.stack.golden @@ -0,0 +1,19 @@ +package p + +import ( + "errors" +) + +// TODO(errx-migrate): was errors.Cause; pkg/errors unwrapped to the root cause. +// Review this — consider errors.Is/As, or extract this loop into a named helper. +func Root(err error) error { + return func(e error) error { + for { + u := errors.Unwrap(e) + if u == nil { + return e + } + e = u + } + }(err) +} diff --git a/testdata/src/comment/in.go b/testdata/src/comment/in.go new file mode 100644 index 0000000..1a9328c --- /dev/null +++ b/testdata/src/comment/in.go @@ -0,0 +1,7 @@ +package p + +import "github.com/pkg/errors" + +func C(err error) error { + return errors.Wrap(err /* keep me */, "context") +} diff --git a/testdata/src/comment/in.lean.golden b/testdata/src/comment/in.lean.golden new file mode 100644 index 0000000..dd6697e --- /dev/null +++ b/testdata/src/comment/in.lean.golden @@ -0,0 +1,8 @@ +package p + +import "github.com/pkg/errors" + +func C(err error) error { + // TODO(errx-migrate): could not safely rewrite errors.Wrap — a comment between its arguments would be lost on reordering. Review and migrate manually. + return errors.Wrap(err /* keep me */, "context") +} diff --git a/testdata/src/comment/in.stack.golden b/testdata/src/comment/in.stack.golden new file mode 100644 index 0000000..dd6697e --- /dev/null +++ b/testdata/src/comment/in.stack.golden @@ -0,0 +1,8 @@ +package p + +import "github.com/pkg/errors" + +func C(err error) error { + // TODO(errx-migrate): could not safely rewrite errors.Wrap — a comment between its arguments would be lost on reordering. Review and migrate manually. + return errors.Wrap(err /* keep me */, "context") +} diff --git a/testdata/src/dotimport/in.go b/testdata/src/dotimport/in.go new file mode 100644 index 0000000..242b5a4 --- /dev/null +++ b/testdata/src/dotimport/in.go @@ -0,0 +1,7 @@ +package p + +import . "github.com/pkg/errors" + +func Make() error { return New("boom") } + +func WrapIt(err error) error { return Wrap(err, "context") } diff --git a/testdata/src/dotimport/in.lean.golden b/testdata/src/dotimport/in.lean.golden new file mode 100644 index 0000000..6a672ea --- /dev/null +++ b/testdata/src/dotimport/in.lean.golden @@ -0,0 +1,10 @@ +package p + +import ( + "errors" + "github.com/go-extras/errx" +) + +func Make() error { return errors.New("boom") } + +func WrapIt(err error) error { return errx.Wrap("context", err) } diff --git a/testdata/src/dotimport/in.stack.golden b/testdata/src/dotimport/in.stack.golden new file mode 100644 index 0000000..4e7975b --- /dev/null +++ b/testdata/src/dotimport/in.stack.golden @@ -0,0 +1,9 @@ +package p + +import ( + "github.com/go-extras/errx/stacktrace" +) + +func Make() error { return stacktrace.ClassifyNew("boom") } + +func WrapIt(err error) error { return stacktrace.Wrap("context", err) } diff --git a/testdata/src/errorf/in.go b/testdata/src/errorf/in.go new file mode 100644 index 0000000..4a41812 --- /dev/null +++ b/testdata/src/errorf/in.go @@ -0,0 +1,7 @@ +package p + +import "github.com/pkg/errors" + +func Args(name string) error { return errors.Errorf("bad %s", name) } + +func Zero() error { return errors.Errorf("static") } diff --git a/testdata/src/errorf/in.lean.golden b/testdata/src/errorf/in.lean.golden new file mode 100644 index 0000000..5d80e8b --- /dev/null +++ b/testdata/src/errorf/in.lean.golden @@ -0,0 +1,10 @@ +package p + +import ( + "errors" + "fmt" +) + +func Args(name string) error { return fmt.Errorf("bad %s", name) } + +func Zero() error { return errors.New("static") } diff --git a/testdata/src/errorf/in.stack.golden b/testdata/src/errorf/in.stack.golden new file mode 100644 index 0000000..bf2c7c5 --- /dev/null +++ b/testdata/src/errorf/in.stack.golden @@ -0,0 +1,12 @@ +package p + +import ( + "fmt" + "github.com/go-extras/errx/stacktrace" +) + +// TODO(errx-migrate): was errors.Errorf; a dynamic fmt.Sprintf error message is non-idiomatic — +// prefer a constant message string (+ classifications). Review. +func Args(name string) error { return stacktrace.ClassifyNew(fmt.Sprintf("bad %s", name)) } + +func Zero() error { return stacktrace.ClassifyNew("static") } diff --git a/testdata/src/isasunwrap/in.go b/testdata/src/isasunwrap/in.go new file mode 100644 index 0000000..e8866ae --- /dev/null +++ b/testdata/src/isasunwrap/in.go @@ -0,0 +1,9 @@ +package p + +import "github.com/pkg/errors" + +func Is(err, target error) bool { return errors.Is(err, target) } + +func As(err error, target any) bool { return errors.As(err, target) } + +func Unwrap(err error) error { return errors.Unwrap(err) } diff --git a/testdata/src/isasunwrap/in.lean.golden b/testdata/src/isasunwrap/in.lean.golden new file mode 100644 index 0000000..a97f0ed --- /dev/null +++ b/testdata/src/isasunwrap/in.lean.golden @@ -0,0 +1,11 @@ +package p + +import ( + "errors" +) + +func Is(err, target error) bool { return errors.Is(err, target) } + +func As(err error, target any) bool { return errors.As(err, target) } + +func Unwrap(err error) error { return errors.Unwrap(err) } diff --git a/testdata/src/isasunwrap/in.stack.golden b/testdata/src/isasunwrap/in.stack.golden new file mode 100644 index 0000000..a97f0ed --- /dev/null +++ b/testdata/src/isasunwrap/in.stack.golden @@ -0,0 +1,11 @@ +package p + +import ( + "errors" +) + +func Is(err, target error) bool { return errors.Is(err, target) } + +func As(err error, target any) bool { return errors.As(err, target) } + +func Unwrap(err error) error { return errors.Unwrap(err) } diff --git a/testdata/src/nested/in.go b/testdata/src/nested/in.go new file mode 100644 index 0000000..b4ad632 --- /dev/null +++ b/testdata/src/nested/in.go @@ -0,0 +1,5 @@ +package p + +import "github.com/pkg/errors" + +func N(err error) error { return errors.Wrap(errors.WithStack(err), "context") } diff --git a/testdata/src/nested/in.lean.golden b/testdata/src/nested/in.lean.golden new file mode 100644 index 0000000..236afac --- /dev/null +++ b/testdata/src/nested/in.lean.golden @@ -0,0 +1,8 @@ +package p + +import ( + "github.com/go-extras/errx" + "github.com/go-extras/errx/stacktrace" +) + +func N(err error) error { return errx.Wrap("context", stacktrace.Classify(err)) } diff --git a/testdata/src/nested/in.stack.golden b/testdata/src/nested/in.stack.golden new file mode 100644 index 0000000..1bf85a6 --- /dev/null +++ b/testdata/src/nested/in.stack.golden @@ -0,0 +1,7 @@ +package p + +import ( + "github.com/go-extras/errx/stacktrace" +) + +func N(err error) error { return stacktrace.Wrap("context", stacktrace.Classify(err)) } diff --git a/testdata/src/nolint/in.go b/testdata/src/nolint/in.go new file mode 100644 index 0000000..490849e --- /dev/null +++ b/testdata/src/nolint/in.go @@ -0,0 +1,7 @@ +package p + +import "github.com/pkg/errors" + +func NL(err error) error { + return errors.Wrap(err, "context") //nolint:wrapcheck // keep this +} diff --git a/testdata/src/nolint/in.lean.golden b/testdata/src/nolint/in.lean.golden new file mode 100644 index 0000000..c19923c --- /dev/null +++ b/testdata/src/nolint/in.lean.golden @@ -0,0 +1,9 @@ +package p + +import ( + "github.com/go-extras/errx" +) + +func NL(err error) error { + return errx.Wrap("context", err) //nolint:wrapcheck // keep this +} diff --git a/testdata/src/nolint/in.stack.golden b/testdata/src/nolint/in.stack.golden new file mode 100644 index 0000000..2dd1ca9 --- /dev/null +++ b/testdata/src/nolint/in.stack.golden @@ -0,0 +1,9 @@ +package p + +import ( + "github.com/go-extras/errx/stacktrace" +) + +func NL(err error) error { + return stacktrace.Wrap("context", err) //nolint:wrapcheck // keep this +} diff --git a/testdata/src/shadowed/in.go b/testdata/src/shadowed/in.go new file mode 100644 index 0000000..c8a19f3 --- /dev/null +++ b/testdata/src/shadowed/in.go @@ -0,0 +1,18 @@ +package p + +import "github.com/pkg/errors" + +type wrapper struct{} + +func (wrapper) Wrap(err error, msg string) error { return err } + +// Shadowed uses a local variable named errors; its Wrap must not be rewritten. +func Shadowed(err error) error { + errors := wrapper{} + return errors.Wrap(err, "local") +} + +// Real uses the real pkg/errors and must be rewritten. +func Real(err error) error { + return errors.Wrap(err, "real") +} diff --git a/testdata/src/shadowed/in.lean.golden b/testdata/src/shadowed/in.lean.golden new file mode 100644 index 0000000..f0c06e2 --- /dev/null +++ b/testdata/src/shadowed/in.lean.golden @@ -0,0 +1,20 @@ +package p + +import ( + "github.com/go-extras/errx" +) + +type wrapper struct{} + +func (wrapper) Wrap(err error, msg string) error { return err } + +// Shadowed uses a local variable named errors; its Wrap must not be rewritten. +func Shadowed(err error) error { + errors := wrapper{} + return errors.Wrap(err, "local") +} + +// Real uses the real pkg/errors and must be rewritten. +func Real(err error) error { + return errx.Wrap("real", err) +} diff --git a/testdata/src/shadowed/in.stack.golden b/testdata/src/shadowed/in.stack.golden new file mode 100644 index 0000000..e6c8014 --- /dev/null +++ b/testdata/src/shadowed/in.stack.golden @@ -0,0 +1,20 @@ +package p + +import ( + "github.com/go-extras/errx/stacktrace" +) + +type wrapper struct{} + +func (wrapper) Wrap(err error, msg string) error { return err } + +// Shadowed uses a local variable named errors; its Wrap must not be rewritten. +func Shadowed(err error) error { + errors := wrapper{} + return errors.Wrap(err, "local") +} + +// Real uses the real pkg/errors and must be rewritten. +func Real(err error) error { + return stacktrace.Wrap("real", err) +} diff --git a/testdata/src/stdmix/in.go b/testdata/src/stdmix/in.go new file mode 100644 index 0000000..d489310 --- /dev/null +++ b/testdata/src/stdmix/in.go @@ -0,0 +1,13 @@ +package p + +import ( + "errors" + + pkgerr "github.com/pkg/errors" +) + +// Sentinel uses the standard library and must not be rewritten. +func Sentinel() error { return errors.New("sentinel") } + +// Wrap uses pkg/errors and must be rewritten. +func Wrap(err error) error { return pkgerr.Wrap(err, "context") } diff --git a/testdata/src/stdmix/in.lean.golden b/testdata/src/stdmix/in.lean.golden new file mode 100644 index 0000000..216ccca --- /dev/null +++ b/testdata/src/stdmix/in.lean.golden @@ -0,0 +1,12 @@ +package p + +import ( + "errors" + "github.com/go-extras/errx" +) + +// Sentinel uses the standard library and must not be rewritten. +func Sentinel() error { return errors.New("sentinel") } + +// Wrap uses pkg/errors and must be rewritten. +func Wrap(err error) error { return errx.Wrap("context", err) } diff --git a/testdata/src/stdmix/in.stack.golden b/testdata/src/stdmix/in.stack.golden new file mode 100644 index 0000000..df6b40b --- /dev/null +++ b/testdata/src/stdmix/in.stack.golden @@ -0,0 +1,12 @@ +package p + +import ( + "errors" + "github.com/go-extras/errx/stacktrace" +) + +// Sentinel uses the standard library and must not be rewritten. +func Sentinel() error { return errors.New("sentinel") } + +// Wrap uses pkg/errors and must be rewritten. +func Wrap(err error) error { return stacktrace.Wrap("context", err) } diff --git a/testdata/src/withmessage/in.go b/testdata/src/withmessage/in.go new file mode 100644 index 0000000..4bb81e9 --- /dev/null +++ b/testdata/src/withmessage/in.go @@ -0,0 +1,9 @@ +package p + +import "github.com/pkg/errors" + +func Msg(err error) error { return errors.WithMessage(err, "context") } + +func Msgf(err error, n int) error { return errors.WithMessagef(err, "context %d", n) } + +func MsgfZero(err error) error { return errors.WithMessagef(err, "static") } diff --git a/testdata/src/withmessage/in.lean.golden b/testdata/src/withmessage/in.lean.golden new file mode 100644 index 0000000..82d5a27 --- /dev/null +++ b/testdata/src/withmessage/in.lean.golden @@ -0,0 +1,14 @@ +package p + +import ( + "fmt" + "github.com/go-extras/errx" +) + +func Msg(err error) error { return errx.Wrap("context", err) } + +// TODO(errx-migrate): was errors.WithMessagef; a dynamic fmt.Sprintf error message is non-idiomatic — +// prefer a constant message string (+ classifications). Review. +func Msgf(err error, n int) error { return errx.Wrap(fmt.Sprintf("context %d", n), err) } + +func MsgfZero(err error) error { return errx.Wrap("static", err) } diff --git a/testdata/src/withmessage/in.stack.golden b/testdata/src/withmessage/in.stack.golden new file mode 100644 index 0000000..82d5a27 --- /dev/null +++ b/testdata/src/withmessage/in.stack.golden @@ -0,0 +1,14 @@ +package p + +import ( + "fmt" + "github.com/go-extras/errx" +) + +func Msg(err error) error { return errx.Wrap("context", err) } + +// TODO(errx-migrate): was errors.WithMessagef; a dynamic fmt.Sprintf error message is non-idiomatic — +// prefer a constant message string (+ classifications). Review. +func Msgf(err error, n int) error { return errx.Wrap(fmt.Sprintf("context %d", n), err) } + +func MsgfZero(err error) error { return errx.Wrap("static", err) } diff --git a/testdata/src/withstack/in.go b/testdata/src/withstack/in.go new file mode 100644 index 0000000..0545d6b --- /dev/null +++ b/testdata/src/withstack/in.go @@ -0,0 +1,5 @@ +package p + +import "github.com/pkg/errors" + +func S(err error) error { return errors.WithStack(err) } diff --git a/testdata/src/withstack/in.lean.golden b/testdata/src/withstack/in.lean.golden new file mode 100644 index 0000000..4885e17 --- /dev/null +++ b/testdata/src/withstack/in.lean.golden @@ -0,0 +1,7 @@ +package p + +import ( + "github.com/go-extras/errx/stacktrace" +) + +func S(err error) error { return stacktrace.Classify(err) } diff --git a/testdata/src/withstack/in.stack.golden b/testdata/src/withstack/in.stack.golden new file mode 100644 index 0000000..4885e17 --- /dev/null +++ b/testdata/src/withstack/in.stack.golden @@ -0,0 +1,7 @@ +package p + +import ( + "github.com/go-extras/errx/stacktrace" +) + +func S(err error) error { return stacktrace.Classify(err) } diff --git a/testdata/src/wrap/in.go b/testdata/src/wrap/in.go new file mode 100644 index 0000000..6b82a41 --- /dev/null +++ b/testdata/src/wrap/in.go @@ -0,0 +1,7 @@ +package p + +import "github.com/pkg/errors" + +func New() error { return errors.New("boom") } + +func Wrap(err error) error { return errors.Wrap(err, "context") } diff --git a/testdata/src/wrap/in.lean.golden b/testdata/src/wrap/in.lean.golden new file mode 100644 index 0000000..87fe639 --- /dev/null +++ b/testdata/src/wrap/in.lean.golden @@ -0,0 +1,10 @@ +package p + +import ( + "errors" + "github.com/go-extras/errx" +) + +func New() error { return errors.New("boom") } + +func Wrap(err error) error { return errx.Wrap("context", err) } diff --git a/testdata/src/wrap/in.stack.golden b/testdata/src/wrap/in.stack.golden new file mode 100644 index 0000000..9637a22 --- /dev/null +++ b/testdata/src/wrap/in.stack.golden @@ -0,0 +1,9 @@ +package p + +import ( + "github.com/go-extras/errx/stacktrace" +) + +func New() error { return stacktrace.ClassifyNew("boom") } + +func Wrap(err error) error { return stacktrace.Wrap("context", err) } diff --git a/testdata/src/wrapf/in.go b/testdata/src/wrapf/in.go new file mode 100644 index 0000000..3a78a2b --- /dev/null +++ b/testdata/src/wrapf/in.go @@ -0,0 +1,7 @@ +package p + +import "github.com/pkg/errors" + +func Args(err error, name string) error { return errors.Wrapf(err, "reading %s", name) } + +func Zero(err error) error { return errors.Wrapf(err, "static message") } diff --git a/testdata/src/wrapf/in.lean.golden b/testdata/src/wrapf/in.lean.golden new file mode 100644 index 0000000..cfcd6a3 --- /dev/null +++ b/testdata/src/wrapf/in.lean.golden @@ -0,0 +1,12 @@ +package p + +import ( + "fmt" + "github.com/go-extras/errx" +) + +// TODO(errx-migrate): was errors.Wrapf; a dynamic fmt.Sprintf error message is non-idiomatic — +// prefer a constant message string (+ classifications). Review. +func Args(err error, name string) error { return errx.Wrap(fmt.Sprintf("reading %s", name), err) } + +func Zero(err error) error { return errx.Wrap("static message", err) } diff --git a/testdata/src/wrapf/in.stack.golden b/testdata/src/wrapf/in.stack.golden new file mode 100644 index 0000000..311b280 --- /dev/null +++ b/testdata/src/wrapf/in.stack.golden @@ -0,0 +1,12 @@ +package p + +import ( + "fmt" + "github.com/go-extras/errx/stacktrace" +) + +// TODO(errx-migrate): was errors.Wrapf; a dynamic fmt.Sprintf error message is non-idiomatic — +// prefer a constant message string (+ classifications). Review. +func Args(err error, name string) error { return stacktrace.Wrap(fmt.Sprintf("reading %s", name), err) } + +func Zero(err error) error { return stacktrace.Wrap("static message", err) } diff --git a/testdata/src/wverb/in.go b/testdata/src/wverb/in.go new file mode 100644 index 0000000..c6e01fe --- /dev/null +++ b/testdata/src/wverb/in.go @@ -0,0 +1,5 @@ +package p + +import "github.com/pkg/errors" + +func W(err error) error { return errors.Wrapf(err, "wrap: %w", err) } diff --git a/testdata/src/wverb/in.lean.golden b/testdata/src/wverb/in.lean.golden new file mode 100644 index 0000000..8ac033b --- /dev/null +++ b/testdata/src/wverb/in.lean.golden @@ -0,0 +1,6 @@ +package p + +import "github.com/pkg/errors" + +// TODO(errx-migrate): could not safely rewrite errors.Wrapf — the format string contains %w, which fmt.Sprintf does not support. Review and migrate manually. +func W(err error) error { return errors.Wrapf(err, "wrap: %w", err) } diff --git a/testdata/src/wverb/in.stack.golden b/testdata/src/wverb/in.stack.golden new file mode 100644 index 0000000..8ac033b --- /dev/null +++ b/testdata/src/wverb/in.stack.golden @@ -0,0 +1,6 @@ +package p + +import "github.com/pkg/errors" + +// TODO(errx-migrate): could not safely rewrite errors.Wrapf — the format string contains %w, which fmt.Sprintf does not support. Review and migrate manually. +func W(err error) error { return errors.Wrapf(err, "wrap: %w", err) } diff --git a/testdata/stub/errx/errx.go b/testdata/stub/errx/errx.go new file mode 100644 index 0000000..82eb078 --- /dev/null +++ b/testdata/stub/errx/errx.go @@ -0,0 +1,29 @@ +// Package errx is a minimal stand-in for github.com/go-extras/errx, used only +// so that migrator test fixtures type-check offline. +package errx + +// Classified marks an error classification. +type Classified interface { + IsClassified() bool +} + +// Wrap adds context and classifications to cause. +func Wrap(text string, cause error, classifications ...Classified) error { return cause } + +// Classify attaches classifications to cause. +func Classify(cause error, classifications ...Classified) error { return cause } + +// ClassifyNew creates and classifies a new error. +func ClassifyNew(text string, classifications ...Classified) error { return &stub{text} } + +// NewSentinel creates a classified sentinel error. +func NewSentinel(text string, parents ...Classified) Classified { return sentinel{} } + +type stub struct{ msg string } + +func (s *stub) Error() string { return s.msg } + +type sentinel struct{} + +func (sentinel) Error() string { return "" } +func (sentinel) IsClassified() bool { return true } diff --git a/testdata/stub/errx/go.mod b/testdata/stub/errx/go.mod new file mode 100644 index 0000000..145f04c --- /dev/null +++ b/testdata/stub/errx/go.mod @@ -0,0 +1,3 @@ +module github.com/go-extras/errx + +go 1.25 diff --git a/testdata/stub/errx/stacktrace/stacktrace.go b/testdata/stub/errx/stacktrace/stacktrace.go new file mode 100644 index 0000000..43b3525 --- /dev/null +++ b/testdata/stub/errx/stacktrace/stacktrace.go @@ -0,0 +1,20 @@ +// Package stacktrace is a minimal stand-in for +// github.com/go-extras/errx/stacktrace, used only so that migrator test +// fixtures type-check offline. +package stacktrace + +import "github.com/go-extras/errx" + +// Wrap adds context and a captured stack to cause. +func Wrap(text string, cause error, classifications ...errx.Classified) error { return cause } + +// Classify attaches a captured stack (and classifications) to cause. +func Classify(cause error, classifications ...errx.Classified) error { return cause } + +// ClassifyNew creates a new error with a captured stack. +func ClassifyNew(text string, classifications ...errx.Classified) error { + return errx.ClassifyNew(text) +} + +// Here captures a stack trace at the call site. +func Here() errx.Classified { return errx.NewSentinel("") } diff --git a/testdata/stub/pkgerrors/errors.go b/testdata/stub/pkgerrors/errors.go new file mode 100644 index 0000000..6eac758 --- /dev/null +++ b/testdata/stub/pkgerrors/errors.go @@ -0,0 +1,40 @@ +// Package errors is a minimal stand-in for github.com/pkg/errors, used only so +// that migrator test fixtures type-check offline. The bodies are irrelevant. +package errors + +// New returns a new error. +func New(message string) error { return &stub{message} } + +// Errorf formats according to a format specifier. +func Errorf(format string, args ...interface{}) error { return &stub{format} } + +// Wrap annotates err with a message. +func Wrap(err error, message string) error { return err } + +// Wrapf annotates err with a formatted message. +func Wrapf(err error, format string, args ...interface{}) error { return err } + +// WithMessage annotates err with a message, without a stack. +func WithMessage(err error, message string) error { return err } + +// WithMessagef annotates err with a formatted message, without a stack. +func WithMessagef(err error, format string, args ...interface{}) error { return err } + +// WithStack annotates err with a stack trace. +func WithStack(err error) error { return err } + +// Cause returns the underlying root cause of err. +func Cause(err error) error { return err } + +// Is reports whether any error in err's chain matches target. +func Is(err, target error) bool { return false } + +// As finds the first error in err's chain that matches target. +func As(err error, target interface{}) bool { return false } + +// Unwrap returns the result of calling the Unwrap method on err. +func Unwrap(err error) error { return nil } + +type stub struct{ msg string } + +func (s *stub) Error() string { return s.msg } diff --git a/testdata/stub/pkgerrors/go.mod b/testdata/stub/pkgerrors/go.mod new file mode 100644 index 0000000..acc5788 --- /dev/null +++ b/testdata/stub/pkgerrors/go.mod @@ -0,0 +1,3 @@ +module github.com/pkg/errors + +go 1.25 From 139cc0d823681a218e6b3a76ced43f3579c90b2f Mon Sep 17 00:00:00 2001 From: Denis V <5462781+denisvmedia@users.noreply.github.com> Date: Sat, 30 May 2026 15:58:24 +0200 Subject: [PATCH 2/4] Address CodeRabbit review - 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. --- cmd/errx-migrate/main.go | 6 ++++-- golden_test.go | 2 +- imports.go | 27 +++++++++++++++++++----- stable_test.go | 2 +- testdata/src/multiimport/in.go | 9 ++++++++ testdata/src/multiimport/in.lean.golden | 8 +++++++ testdata/src/multiimport/in.stack.golden | 8 +++++++ 7 files changed, 53 insertions(+), 9 deletions(-) create mode 100644 testdata/src/multiimport/in.go create mode 100644 testdata/src/multiimport/in.lean.golden create mode 100644 testdata/src/multiimport/in.stack.golden diff --git a/cmd/errx-migrate/main.go b/cmd/errx-migrate/main.go index bf65737..a166637 100644 --- a/cmd/errx-migrate/main.go +++ b/cmd/errx-migrate/main.go @@ -166,12 +166,14 @@ func emitFile(fset *token.FileSet, name string, edits []analysis.TextEdit, opts case opts.diff: fmt.Print(unifiedDiff(name, src, formatted)) case opts.write: - if err := os.WriteFile(name, formatted, 0o600); err != nil { //nolint:gosec // path comes from the loaded package's file set + if err := os.WriteFile(name, formatted, 0o600); err != nil { return err } default: fmt.Print(header) - os.Stdout.Write(formatted) + if _, err := os.Stdout.Write(formatted); err != nil { + return fmt.Errorf("writing %s to stdout: %w", name, err) + } } return nil } diff --git a/golden_test.go b/golden_test.go index 7f6a7e7..ed6a552 100644 --- a/golden_test.go +++ b/golden_test.go @@ -73,7 +73,7 @@ func checkGolden(t *testing.T, fset *token.FileSet, pkg *packages.Package, mi mo goldenPath := filepath.Join(filepath.Dir(file), "in."+mi.ext+".golden") if *update { - if err := os.WriteFile(goldenPath, formatted, 0o600); err != nil { //nolint:gosec // goldenPath is under the test's own testdata tree + if err := os.WriteFile(goldenPath, formatted, 0o600); err != nil { t.Fatal(err) } return diff --git a/imports.go b/imports.go index 180a811..498b88d 100644 --- a/imports.go +++ b/imports.go @@ -89,12 +89,9 @@ func importLines(paths []string, prefix string) []byte { // removeImportEdit returns an edit that removes the import of path, if present. // When the import lives alone in a parenthesised block, the whole declaration -// is removed; otherwise just its line is removed. +// is removed; otherwise just its line is removed. The declaration consulted is +// the one that actually owns the target spec, not merely the first import block. func removeImportEdit(tf *token.File, file *ast.File, path string) (analysis.TextEdit, bool) { - decl := firstImportDecl(file) - if decl == nil { - return analysis.TextEdit{}, false - } var target *ast.ImportSpec for _, s := range file.Imports { if p, err := strconv.Unquote(s.Path.Value); err == nil && p == path { @@ -105,6 +102,10 @@ func removeImportEdit(tf *token.File, file *ast.File, path string) (analysis.Tex if target == nil { return analysis.TextEdit{}, false } + decl := owningImportDecl(file, target) + if decl == nil { + return analysis.TextEdit{}, false + } // Remove the entire declaration when it holds only this import. if !decl.Lparen.IsValid() || len(decl.Specs) == 1 { return wholeLinesEdit(tf, decl.Pos(), decl.End()), true @@ -112,6 +113,22 @@ func removeImportEdit(tf *token.File, file *ast.File, path string) (analysis.Tex return wholeLinesEdit(tf, target.Pos(), target.End()), true } +// owningImportDecl returns the import GenDecl whose Specs contain spec. +func owningImportDecl(file *ast.File, spec *ast.ImportSpec) *ast.GenDecl { + for _, decl := range file.Decls { + gd, ok := decl.(*ast.GenDecl) + if !ok || gd.Tok != token.IMPORT { + continue + } + for _, s := range gd.Specs { + if s == spec { + return gd + } + } + } + return nil +} + // wholeLinesEdit returns an edit covering the full lines spanned by [from, to), // including the trailing newline, so removal leaves no blank line. func wholeLinesEdit(tf *token.File, from, to token.Pos) analysis.TextEdit { diff --git a/stable_test.go b/stable_test.go index 8ed0ef5..cb8254a 100644 --- a/stable_test.go +++ b/stable_test.go @@ -104,7 +104,7 @@ func layoutGoldens(t *testing.T, dir string) map[string]errxmigrate.Mode { if err := os.Mkdir(filepath.Join(dir, pkgDir), 0o750); err != nil { t.Fatal(err) } - if err := os.WriteFile(filepath.Join(dir, pkgDir, "p.go"), data, 0o600); err != nil { //nolint:gosec // dir is t.TempDir() + if err := os.WriteFile(filepath.Join(dir, pkgDir, "p.go"), data, 0o600); err != nil { t.Fatal(err) } caseModes[pkgDir] = mi.mode diff --git a/testdata/src/multiimport/in.go b/testdata/src/multiimport/in.go new file mode 100644 index 0000000..f5b019c --- /dev/null +++ b/testdata/src/multiimport/in.go @@ -0,0 +1,9 @@ +package p + +import "fmt" + +import "github.com/pkg/errors" + +func New() error { return errors.New("boom") } + +func Format(v any) string { return fmt.Sprintf("%v", v) } diff --git a/testdata/src/multiimport/in.lean.golden b/testdata/src/multiimport/in.lean.golden new file mode 100644 index 0000000..0f9e959 --- /dev/null +++ b/testdata/src/multiimport/in.lean.golden @@ -0,0 +1,8 @@ +package p + +import "fmt" +import "errors" + +func New() error { return errors.New("boom") } + +func Format(v any) string { return fmt.Sprintf("%v", v) } diff --git a/testdata/src/multiimport/in.stack.golden b/testdata/src/multiimport/in.stack.golden new file mode 100644 index 0000000..e1dd36d --- /dev/null +++ b/testdata/src/multiimport/in.stack.golden @@ -0,0 +1,8 @@ +package p + +import "fmt" +import "github.com/go-extras/errx/stacktrace" + +func New() error { return stacktrace.ClassifyNew("boom") } + +func Format(v any) string { return fmt.Sprintf("%v", v) } From 93ed4e1c4c791f9266976b443fb035cd4f9d083d Mon Sep 17 00:00:00 2001 From: Denis V <5462781+denisvmedia@users.noreply.github.com> Date: Sat, 30 May 2026 16:10:46 +0200 Subject: [PATCH 3/4] Bump golangci-lint to v2.12.2 and exclude gosec G703 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. --- .github/workflows/go-lint.yml | 2 +- .golangci.yml | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index beadd1e..561c40b 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -37,7 +37,7 @@ jobs: uses: golangci/golangci-lint-action@v9 with: args: --timeout=30m - version: v2.10.1 + version: v2.12.2 - name: Run govulncheck run: | diff --git a/.golangci.yml b/.golangci.yml index f0635c3..969bca3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -77,6 +77,13 @@ linters: scope: declarations exclude: [] capital: true + gosec: + excludes: + # G703 (path traversal via taint analysis) fires on file paths that + # come from the Go type checker's own file set and from t.TempDir() in + # tests, which are trusted. Other gosec rules stay enabled. (Ignored by + # gosec versions that predate the rule.) + - G703 importas: no-unaliased: true lll: From 69de7babc8ce870b9a186af3e8e9f945cd4eee11 Mon Sep 17 00:00:00 2001 From: Denis V <5462781+denisvmedia@users.noreply.github.com> Date: Sat, 30 May 2026 16:36:33 +0200 Subject: [PATCH 4/4] Harden CI/release workflows and Makefile (CodeRabbit follow-ups) - 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. --- .github/workflows/ci.yml | 26 +++++++++++---- .github/workflows/go-lint.yml | 10 ++++-- .github/workflows/release.yml | 60 ++++++++++++++++++++++++----------- Makefile | 3 ++ 4 files changed, 71 insertions(+), 28 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dfbf428..c8e5df1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,20 +18,28 @@ jobs: setup: name: Setup runs-on: ubuntu-latest + permissions: + contents: read steps: - name: Checkout code - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false # Build verification - ensure the tool compiles build: name: Build runs-on: ubuntu-latest needs: setup + permissions: + contents: read steps: - name: Checkout code - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false - - uses: actions/setup-go@v6 + - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: go-version: stable cache: true @@ -50,6 +58,8 @@ jobs: unit-tests: name: Unit Tests runs-on: ubuntu-latest + permissions: + contents: read strategy: matrix: go-version: @@ -58,9 +68,11 @@ jobs: needs: setup steps: - name: Checkout code - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false - - uses: actions/setup-go@v6 + - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: go-version: ${{ matrix.go-version }} cache: true @@ -89,7 +101,7 @@ jobs: - name: Upload coverage to Codecov if: matrix.go-version == 'stable' - uses: codecov/codecov-action@v6 + uses: codecov/codecov-action@e79a6962e0d4c0c17b229090214935d2e33f8354 # v6.0.1 with: files: ./coverage.out flags: unittests @@ -98,7 +110,7 @@ jobs: - name: Upload coverage artifacts if: matrix.go-version == 'stable' - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: coverage-report path: | diff --git a/.github/workflows/go-lint.yml b/.github/workflows/go-lint.yml index 561c40b..ccf1611 100644 --- a/.github/workflows/go-lint.yml +++ b/.github/workflows/go-lint.yml @@ -14,12 +14,16 @@ jobs: golangci: name: lint runs-on: ubuntu-latest + permissions: + contents: read steps: # Checkout code - name: Checkout code - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false - - uses: actions/setup-go@v6 + - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: go-version: stable cache: true @@ -34,7 +38,7 @@ jobs: git diff --exit-code go.mod go.sum - name: golangci-lint - uses: golangci/golangci-lint-action@v9 + uses: golangci/golangci-lint-action@82606bf257cbaff209d206a39f5134f0cfbfd2ee # v9.2.1 with: args: --timeout=30m version: v2.12.2 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a248f42..96e68e8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -8,40 +8,42 @@ on: branches: - master +# Least privilege by default; the release job opts into write below. permissions: - contents: write - packages: write + contents: read jobs: - goreleaser: - name: GoReleaser + # PR path: build a snapshot to validate the GoReleaser config. Read-only + # permissions and caching disabled so an untrusted PR cannot publish or + # poison caches used by the trusted (tag) release job. + snapshot: + name: GoReleaser Snapshot + if: github.event_name == 'pull_request' runs-on: ubuntu-latest + permissions: + contents: read steps: - name: Checkout code - uses: actions/checkout@v6 + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: fetch-depth: 0 + persist-credentials: false - name: Set up Go - uses: actions/setup-go@v6 + uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: go-version: 1.26.0 - cache: true - cache-dependency-path: go.sum + cache: false - - name: Run GoReleaser (Snapshot for PRs) - if: github.event_name == 'pull_request' - uses: goreleaser/goreleaser-action@v7 + - name: Run GoReleaser (snapshot) + uses: goreleaser/goreleaser-action@5daf1e915a5f0af01ddbcd89a43b8061ff4f1a89 # v7.2.2 with: distribution: goreleaser version: '~> v2' args: release --snapshot --clean --skip=publish - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - name: Upload PR artifacts - if: github.event_name == 'pull_request' - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: name: release-artifacts path: | @@ -50,9 +52,31 @@ jobs: dist/checksums.txt retention-days: 7 - - name: Run GoReleaser (Production Release) - if: startsWith(github.ref, 'refs/tags/') - uses: goreleaser/goreleaser-action@v7 + # Tag path: the real release. Runs only on tag pushes (a trusted ref) and is + # the only job granted write permissions. + release: + name: GoReleaser Release + if: startsWith(github.ref, 'refs/tags/') + runs-on: ubuntu-latest + permissions: + contents: write + packages: write + steps: + - name: Checkout code + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 + with: + go-version: 1.26.0 + cache: true + cache-dependency-path: go.sum + + - name: Run GoReleaser (production release) + uses: goreleaser/goreleaser-action@5daf1e915a5f0af01ddbcd89a43b8061ff4f1a89 # v7.2.2 with: distribution: goreleaser version: '~> v2' diff --git a/Makefile b/Makefile index 870a825..ddb1c21 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,6 @@ +# Show help when make is run with no target. +.DEFAULT_GOAL := help + .PHONY: build install test lint lint-fix fmt clean help # Build the standalone binary