Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 25 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ errx-migrate -w ./...

# Lean mode: map to the zero-dependency errx core + stdlib instead of the stacktrace subpackage:
errx-migrate -w -no-stack ./...

# Compat mode: route through the errx compat package (errxc), which accepts plain error classifications:
errx-migrate -w -compat ./...
```

Flags:
Expand All @@ -36,33 +39,42 @@ Flags:
| `-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. |
| `-compat` | **Compat** mode — route the message/wrap family through the [`errx/compat`](https://pkg.go.dev/github.com/go-extras/errx/compat) package (imported as `errxc`), whose functions accept plain `error` classifications. Like lean it drops implicit stacks, but an explicit `errors.WithStack` is still preserved as `errxtrace.Classify`. Mutually exclusive with `-no-stack`. |
| `-include-generated` | Also rewrite generated files (`// Code generated ... DO NOT EDIT.`). Skipped by default. |

When they are imported, `errx/stacktrace` is aliased as **`errxtrace`** and `errx/compat` as **`errxc`**. (`errx/stacktrace` may not appear at all in a lean or compat run if no `errors.WithStack` rewrite needs it.)

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.
subpackage (imported as `errxtrace`) 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
stdlib `errors`/`fmt`. Explicit `errors.WithStack` is still preserved as `errxtrace.Classify` (an explicit
request for a stack is honored).

**Compat (`-compat`).** The message/wrap family is routed through the `errx/compat` package (imported as
`errxc`), whose functions accept plain `error` classifications rather than `errx.Classified` — handy when you
also classify with third-party error values. Like lean it carries no implicit stack; an explicit
`errors.WithStack` is still preserved as `errxtrace.Classify`. The migrator always prefers `errx`/`errxtrace`
where possible and only routes through `compat` in this mode.

## 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 |
| `pkg/errors` | stack-preserving (default) | lean (`-no-stack`) | compat (`-compat`) |
|---|---|---|---|
| `errors.New(msg)` | `errxtrace.ClassifyNew(msg)` | `errors.New(msg)` (stdlib) | `errxc.ClassifyNew(msg)` |
| `errors.Errorf(f, a…)` | `errxtrace.ClassifyNew(fmt.Sprintf(f, a…))` | `fmt.Errorf(f, a…)` | `errxc.ClassifyNew(fmt.Sprintf(f, a…))` |
| `errors.Wrap(err, msg)` | `errxtrace.Wrap(msg, err)` | `errx.Wrap(msg, err)` | `errxc.Wrap(msg, err)` |
| `errors.Wrapf(err, f, a…)` | `errxtrace.Wrap(fmt.Sprintf(f, a…), err)` | `errx.Wrap(fmt.Sprintf(f, a…), err)` | `errxc.Wrap(fmt.Sprintf(f, a…), err)` |
| `errors.WithMessage(err, msg)` | `errx.Wrap(msg, err)` | `errx.Wrap(msg, err)` | `errxc.Wrap(msg, err)` |
| `errors.WithMessagef(err, f, a…)` | `errx.Wrap(fmt.Sprintf(f, a…), err)` | same | `errxc.Wrap(fmt.Sprintf(f, a…), err)` |
| `errors.WithStack(err)` | `errxtrace.Classify(err)` | `errxtrace.Classify(err)` | `errxtrace.Classify(err)` |
| `errors.Is` / `As` / `Unwrap` | stdlib `errors.*` | same | same |
| `errors.Cause(err)` | inline root-unwrap + `// TODO(errx-migrate)` | same | same |

Notes:

Expand Down
8 changes: 7 additions & 1 deletion analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,11 @@ import "golang.org/x/tools/go/analysis"
// applying fixes for tidy output.
func NewAnalyzer(mode Mode) *analysis.Analyzer {
name := "errxmigrate"
if mode == ModeLean {
switch mode {
case ModeLean:
name = "errxmigratelean"
case ModeCompat:
name = "errxmigratecompat"
}
return &analysis.Analyzer{
Name: name,
Expand All @@ -31,3 +34,6 @@ var AnalyzerStack = NewAnalyzer(ModeStack)

// AnalyzerLean is the lean (-no-stack) analyzer.
var AnalyzerLean = NewAnalyzer(ModeLean)

// AnalyzerCompat is the compat (-compat) analyzer.
var AnalyzerCompat = NewAnalyzer(ModeCompat)
2 changes: 1 addition & 1 deletion analyzer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
)

func TestAnalyzersValidate(t *testing.T) {
if err := analysis.Validate([]*analysis.Analyzer{errxmigrate.AnalyzerStack, errxmigrate.AnalyzerLean}); err != nil {
if err := analysis.Validate([]*analysis.Analyzer{errxmigrate.AnalyzerStack, errxmigrate.AnalyzerLean, errxmigrate.AnalyzerCompat}); err != nil {
t.Fatal(err)
}
}
Expand Down
98 changes: 50 additions & 48 deletions build_edits.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type buildCtx struct {
file *ast.File
src []byte
tf *token.File
mode Mode
dl dialect
// addImports collects the import paths the rendered text depends on.
addImports map[string]struct{}
}
Expand Down Expand Up @@ -118,105 +118,107 @@ func (c *buildCtx) exprHasPkgErrorsRef(expr ast.Expr) bool {
return found
}

// buildNew translates errors.New into the dialect's stack-capturing constructor.
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")}
return c.newCall(c.dl.stackNew, m, c.text(m.call.Args[0]))
}

// buildErrorf translates errors.Errorf. With no format arguments it collapses
// to New; in lean mode it becomes fmt.Errorf; otherwise it becomes the dialect
// constructor wrapping fmt.Sprintf, with a review TODO.
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")}
return c.newCall(c.dl.stackNew, m, c.text(m.call.Args[0]))
}
if c.mode == ModeLean {
if c.dl.leanErrorf {
// 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")}
return rewrite{newText: qualFmt + ".Errorf(" + c.joinArgs(m.call, 0) + ")", message: msgFor(m, qualFmt+".Errorf")}
}
if rw, leave := checkWrapVerb(m); leave {
return rw
// Errorf's format string is its first argument (unlike Wrapf/WithMessagef,
// where it is the second). A %w there cannot survive fmt.Sprintf, so leave
// the call untouched. The lean path above already returned via fmt.Errorf,
// which does support %w.
if formatHasWrapVerb(m.call.Args[0]) {
return leaveRewrite(m, "the format string contains %w, which fmt.Sprintf does not support")
}
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),
}
rw := c.newCall(c.dl.stackNew, m, qualFmt+".Sprintf("+c.joinArgs(m.call, 0)+")")
rw.todo = sprintfTODO(m)
return rw
}

// buildWrap translates errors.Wrap into the dialect's stack-capturing wrap,
// swapping the (cause, msg) argument order to (msg, cause).
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)
return c.wrapCall(c.dl.stackWrap, m, c.text(m.call.Args[1]), cause)
}

// buildWrapf translates errors.Wrapf, mirroring buildWrap but rendering the
// formatted message via fmt.Sprintf (with a TODO) unless it is the zero-format
// case, which collapses to a plain wrap.
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)
return c.wrapCall(c.dl.stackWrap, 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)
msg := qualFmt + ".Sprintf(" + c.joinArgs(m.call, 1) + ")"
rw := c.wrapCall(c.dl.stackWrap, m, msg, cause)
rw.todo = sprintfTODO(m)
return rw
}

// buildWithMessage translates errors.WithMessage into the dialect's plain
// (no stack) wrap, since WithMessage never captures a stack.
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")}
return c.wrapCall(c.dl.plainWrap, m, c.text(m.call.Args[1]), cause)
}

// buildWithMessagef translates errors.WithMessagef, mirroring buildWithMessage
// but rendering the formatted message via fmt.Sprintf (with a TODO).
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")}
return c.wrapCall(c.dl.plainWrap, 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) + ")"
return rewrite{newText: "errx.Wrap(" + msg + ", " + cause + ")", message: msgFor(m, "errx.Wrap"), todo: sprintfTODO(m)}
msg := qualFmt + ".Sprintf(" + c.joinArgs(m.call, 1) + ")"
rw := c.wrapCall(c.dl.plainWrap, m, msg, cause)
rw.todo = sprintfTODO(m)
return rw
}

// buildWithStack translates errors.WithStack into the dialect's classify call
// (errxtrace.Classify in every mode — an explicit stack request is honored).
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")}
return rewrite{newText: c.render(c.dl.classify, cause), message: msgFor(m, c.dl.classify.name())}
}

func (c *buildCtx) buildCause(m match) rewrite {
Expand All @@ -233,19 +235,19 @@ func (c *buildCtx) buildCause(m match) rewrite {
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),
newText: qualErrors + "." + m.name + "(" + c.joinArgs(m.call, 0) + ")",
message: msgFor(m, qualErrors+"."+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")}
// newCall builds a constructor call (New/Errorf) for the dialect's target.
func (c *buildCtx) newCall(t targetCall, m match, msg string) rewrite {
return rewrite{newText: c.render(t, msg), message: msgFor(m, t.name())}
}

// wrapCall builds the swapped-argument wrap call for the dialect's target.
func (c *buildCtx) wrapCall(t targetCall, m match, msg, cause string) rewrite {
return rewrite{newText: c.render(t, msg+", "+cause), message: msgFor(m, t.name())}
}

// checkWrapVerb returns a leave-in-place rewrite if the format string literal
Expand Down
11 changes: 10 additions & 1 deletion cmd/errx-migrate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type options struct {

func main() {
noStack := flag.Bool("no-stack", false, "lean mode: map to the errx core + stdlib, dropping implicit stacks")
compat := flag.Bool("compat", false, "compat mode: map to the errx compat package (errxc), which accepts plain error classifications")
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")
Expand All @@ -44,12 +45,20 @@ func main() {
return
}

if *noStack && *compat {
fmt.Fprintln(os.Stderr, "errx-migrate: -no-stack and -compat are mutually exclusive")
os.Exit(2)
}

patterns := flag.Args()
if len(patterns) == 0 {
patterns = []string{"./..."}
}
mode := errxmigrate.ModeStack
if *noStack {
switch {
case *compat:
mode = errxmigrate.ModeCompat
case *noStack:
mode = errxmigrate.ModeLean
}
opts := options{mode: mode, diff: *doDiff, write: *write, includeGenerated: *includeGenerated}
Expand Down
44 changes: 42 additions & 2 deletions cmd/errx-migrate/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,11 @@ func TestEndToEnd(t *testing.T) {
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)
if !strings.Contains(got, "errxtrace.Wrap") || !strings.Contains(got, "errxtrace.ClassifyNew") {
t.Errorf("expected errxtrace calls in output:\n%s", got)
}
if !strings.Contains(got, `errxtrace "github.com/go-extras/errx/stacktrace"`) {
t.Errorf("expected stacktrace imported as errxtrace:\n%s", got)
}

// Idempotent: a second run must not change anything.
Expand All @@ -54,6 +57,43 @@ func TestEndToEnd(t *testing.T) {
}
}

// TestEndToEndCompat runs the full CLI pipeline in compat mode and checks the
// output routes through the errx compat package under its errxc alias, stays
// gofmt-clean, and is idempotent.
func TestEndToEndCompat(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.ModeCompat, 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, "errxc.Wrap") || !strings.Contains(got, "errxc.ClassifyNew") {
t.Errorf("expected compat (errxc) calls in output:\n%s", got)
}
if !strings.Contains(got, `errxc "github.com/go-extras/errx/compat"`) {
t.Errorf("expected compat imported as errxc:\n%s", got)
}

// Idempotent: a second run must not change anything.
if err := run(options{mode: errxmigrate.ModeCompat, 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"))
Expand Down
17 changes: 9 additions & 8 deletions detect.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ import (
"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"
)
// detect.go is the "source" half of the migrator: it recognizes which calls in
// the input belong to the library being migrated and maps them onto the shared
// errFn operations that the target dialects (target.go) know how to render.
// Today the only source library is github.com/pkg/errors; an additional library
// would add its own path and name→errFn mapping here without touching the
// rendering side.

// pkgErrorsPath is the import path of the source library.
const pkgErrorsPath = "github.com/pkg/errors"

// errFn enumerates the pkg/errors functions the migrator recognises.
type errFn int
Expand Down
1 change: 1 addition & 0 deletions golden_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ type modeInfo struct {
var modes = []modeInfo{
{errxmigrate.ModeStack, "stack"},
{errxmigrate.ModeLean, "lean"},
{errxmigrate.ModeCompat, "compat"},
}

// TestGolden runs the rewrite core over every fixture package in both modes,
Expand Down
Loading