From 18a238d85e0352f35df73d5ba879a79987d688b2 Mon Sep 17 00:00:00 2001 From: Tonis Tiigi Date: Sat, 7 Mar 2026 22:21:45 -0800 Subject: [PATCH 1/7] chore: add basic dev tools targets Add go.mod, targets to build, test and lint. Signed-off-by: Tonis Tiigi --- .golangci.yml | 27 +++++++++++++++ Dockerfile | 31 +++++++++++++++++ Makefile | 41 +---------------------- docker-bake.hcl | 57 ++++++++++++++++++++++++++++++++ go.mod | 3 ++ hack/dockerfiles/lint.Dockerfile | 28 ++++++++++++++++ 6 files changed, 147 insertions(+), 40 deletions(-) create mode 100644 .golangci.yml create mode 100644 Dockerfile create mode 100644 docker-bake.hcl create mode 100644 go.mod create mode 100644 hack/dockerfiles/lint.Dockerfile diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 00000000..2a6826bf --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,27 @@ +version: "2" + +run: + timeout: 10m + +formatters: + enable: + - gofmt + - goimports + +linters: + default: standard + enable: + - bodyclose + - errname + - forbidigo + - gocritic + - gosec + - importas + - makezero + - misspell + - noctx + - nolintlint + - revive + - unconvert + - unparam + - whitespace diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..6f434d9a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,31 @@ +#syntax=docker/dockerfile:1 +#check=error=true + +ARG GO_VERSION=1.26 +ARG XX_VERSION=1.9.0 + +ARG COVER_FILENAME="cover.out" + +FROM --platform=${BUILDPLATFORM} tonistiigi/xx:${XX_VERSION} AS xx + +FROM --platform=${BUILDPLATFORM} golang:${GO_VERSION}-alpine AS golang +COPY --link --from=xx / / +WORKDIR /src +ARG TARGETPLATFORM + +FROM golang AS build +RUN --mount=target=/root/.cache,type=cache \ + --mount=type=bind xx-go build ./... + +FROM golang AS runtest +ARG TESTFLAGS="-v" +ARG COVER_FILENAME +RUN --mount=target=/root/.cache,type=cache \ + --mount=type=bind \ + xx-go test -coverprofile=/tmp/${COVER_FILENAME} $TESTFLAGS ./... + +FROM scratch AS test +ARG COVER_FILENAME +COPY --from=runtest /tmp/${COVER_FILENAME} / + +FROM build diff --git a/Makefile b/Makefile index ce9d7cde..51ae1770 100644 --- a/Makefile +++ b/Makefile @@ -1,44 +1,5 @@ PKGS := github.com/pkg/errors -SRCDIRS := $(shell go list -f '{{.Dir}}' $(PKGS)) GO := go -check: test vet gofmt misspell unconvert staticcheck ineffassign unparam - -test: +test: $(GO) test $(PKGS) - -vet: | test - $(GO) vet $(PKGS) - -staticcheck: - $(GO) get honnef.co/go/tools/cmd/staticcheck - staticcheck -checks all $(PKGS) - -misspell: - $(GO) get github.com/client9/misspell/cmd/misspell - misspell \ - -locale GB \ - -error \ - *.md *.go - -unconvert: - $(GO) get github.com/mdempsky/unconvert - unconvert -v $(PKGS) - -ineffassign: - $(GO) get github.com/gordonklaus/ineffassign - find $(SRCDIRS) -name '*.go' | xargs ineffassign - -pedantic: check errcheck - -unparam: - $(GO) get mvdan.cc/unparam - unparam ./... - -errcheck: - $(GO) get github.com/kisielk/errcheck - errcheck $(PKGS) - -gofmt: - @echo Checking code is gofmted - @test -z "$(shell gofmt -s -l -d -e $(SRCDIRS) | tee /dev/stderr)" diff --git a/docker-bake.hcl b/docker-bake.hcl new file mode 100644 index 00000000..491d338d --- /dev/null +++ b/docker-bake.hcl @@ -0,0 +1,57 @@ +variable "COVER_FILENAME" { + default = null +} + +variable "GO_VERSION" { + default = null +} + +target "default" { + targets = ["build"] +} + +target "_all_platforms" { + platforms = [ + "linux/amd64", + "linux/arm64", + "linux/arm/v7", + "linux/arm/v6", + "linux/386", + "linux/ppc64le", + "linux/s390x", + "linux/riscv64", + "darwin/amd64", + "darwin/arm64", + "windows/amd64", + "windows/arm64", + ] +} + +target "build" { + output = ["type=cacheonly"] + args = { + GO_VERSION = GO_VERSION + } +} + +target "build-all" { + inherits = ["build", "_all_platforms"] +} + +target "test" { + target = "test" + args = { + COVER_FILENAME = COVER_FILENAME + GO_VERSION = GO_VERSION + } + output = [COVER_FILENAME != null ? "." : "type=cacheonly"] +} + +target "lint" { + dockerfile = "hack/dockerfiles/lint.Dockerfile" + output = ["type=cacheonly"] +} + +target "lint-all" { + inherits = ["lint", "_all_platforms"] +} diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..b44ef6f4 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/pkg/errors + +go 1.20 diff --git a/hack/dockerfiles/lint.Dockerfile b/hack/dockerfiles/lint.Dockerfile new file mode 100644 index 00000000..865c9242 --- /dev/null +++ b/hack/dockerfiles/lint.Dockerfile @@ -0,0 +1,28 @@ +#syntax=docker/dockerfile:1 +#check=error=true + +ARG GO_VERSION=1.26 +ARG ALPINE_VERSION=3.23 +ARG XX_VERSION=1.9.0 +ARG GOLANGCI_LINT_VERSION=2.11.2 + +FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine${ALPINE_VERSION} AS golang-base +FROM --platform=$BUILDPLATFORM tonistiigi/xx:${XX_VERSION} AS xx + +FROM golang-base AS base +ENV GOFLAGS="-buildvcs=false" +ARG GOLANGCI_LINT_VERSION +RUN wget -O- -nv https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s v${GOLANGCI_LINT_VERSION} +COPY --link --from=xx / / +WORKDIR /go/src/github.com/pkg/errors + +FROM base AS golangci-lint +ARG TARGETPLATFORM +RUN --mount=type=bind \ + --mount=target=/root/.cache,type=cache \ + xx-go --wrap && \ + golangci-lint run && \ + touch /golangci-lint.done + +FROM scratch +COPY --link --from=golangci-lint /golangci-lint.done / From bcc7d34ca5b79bfd66a2d162575c0d31a3af6a94 Mon Sep 17 00:00:00 2001 From: Tonis Tiigi Date: Sat, 7 Mar 2026 22:42:08 -0800 Subject: [PATCH 2/7] lint: fix all golangci-lint issues and test failures Fix gofmt formatting, simplify code patterns flagged by gocritic/staticcheck/revive, update test path expectations to not assume GOPATH layout. Signed-off-by: Tonis Tiigi --- .golangci.yml | 15 ++++- bench_test.go | 3 +- errors.go | 79 ++++++++++++++------------ errors_test.go | 2 +- format_test.go | 96 +++++++++++++++----------------- go113.go | 1 + go113_test.go | 1 + hack/dockerfiles/lint.Dockerfile | 4 +- json_test.go | 4 +- stack.go | 32 +++++------ stack_test.go | 28 +++++----- 11 files changed, 139 insertions(+), 126 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 2a6826bf..3bf8ed45 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -12,7 +12,6 @@ linters: default: standard enable: - bodyclose - - errname - forbidigo - gocritic - gosec @@ -25,3 +24,17 @@ linters: - unconvert - unparam - whitespace + settings: + errcheck: + exclude-functions: + - io.WriteString + exclusions: + presets: + - std-error-handling + rules: + - linters: + - gosec + text: "G104" + - linters: + - staticcheck + text: "QF1008" diff --git a/bench_test.go b/bench_test.go index c906870e..73520e9d 100644 --- a/bench_test.go +++ b/bench_test.go @@ -1,3 +1,4 @@ +//go:build go1.7 // +build go1.7 package errors @@ -97,7 +98,7 @@ func BenchmarkStackFormatting(b *testing.B) { name := fmt.Sprintf("%s-stacktrace-%d", r.format, r.stack) b.Run(name, func(b *testing.B) { err := yesErrors(0, r.stack) - st := err.(*fundamental).stack.StackTrace() + st := err.(*fundamental).StackTrace() b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { diff --git a/errors.go b/errors.go index 161aea25..bf3e3699 100644 --- a/errors.go +++ b/errors.go @@ -2,89 +2,89 @@ // // The traditional error handling idiom in Go is roughly akin to // -// if err != nil { -// return err -// } +// if err != nil { +// return err +// } // // which when applied recursively up the call stack results in error reports // without context or debugging information. The errors package allows // programmers to add context to the failure path in their code in a way // that does not destroy the original value of the error. // -// Adding context to an error +// # Adding context to an error // // The errors.Wrap function returns a new error that adds context to the // original error by recording a stack trace at the point Wrap is called, // together with the supplied message. For example // -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } +// _, err := io.ReadAll(r) +// if err != nil { +// return errors.Wrap(err, "read failed") +// } // // If additional control is required, the errors.WithStack and // errors.WithMessage functions destructure errors.Wrap into its component // operations: annotating an error with a stack trace and with a message, // respectively. // -// Retrieving the cause of an error +// # Retrieving the cause of an error // // Using errors.Wrap constructs a stack of errors, adding context to the // preceding error. Depending on the nature of the error it may be necessary // to reverse the operation of errors.Wrap to retrieve the original error // for inspection. Any error value which implements this interface // -// type causer interface { -// Cause() error -// } +// type causer interface { +// Cause() error +// } // // can be inspected by errors.Cause. errors.Cause will recursively retrieve // the topmost error that does not implement causer, which is assumed to be // the original cause. For example: // -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } +// switch err := errors.Cause(err).(type) { +// case *MyError: +// // handle specifically +// default: +// // unknown error +// } // // Although the causer interface is not exported by this package, it is // considered a part of its stable public interface. // -// Formatted printing of errors +// # Formatted printing of errors // // All error values returned from this package implement fmt.Formatter and can // be formatted by the fmt package. The following verbs are supported: // -// %s print the error. If the error has a Cause it will be -// printed recursively. -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. +// %s print the error. If the error has a Cause it will be +// printed recursively. +// %v see %s +// %+v extended format. Each Frame of the error's StackTrace will +// be printed in detail. // -// Retrieving the stack trace of an error or wrapper +// # Retrieving the stack trace of an error or wrapper // // New, Errorf, Wrap, and Wrapf record a stack trace at the point they are // invoked. This information can be retrieved with the following interface: // -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } +// type stackTracer interface { +// StackTrace() errors.StackTrace +// } // // The returned errors.StackTrace type is defined as // -// type StackTrace []Frame +// type StackTrace []Frame // // The Frame type represents a call site in the stack trace. Frame supports // the fmt.Formatter interface that can be used for printing information about // the stack trace of this error. For example: // -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d\n", f, f) -// } -// } +// if err, ok := err.(stackTracer); ok { +// for _, f := range err.StackTrace() { +// fmt.Printf("%+s:%d\n", f, f) +// } +// } // // Although the stackTracer interface is not exported by this package, it is // considered a part of its stable public interface. @@ -265,13 +265,18 @@ func (w *withMessage) Format(s fmt.State, verb rune) { // An error value has a cause if it implements the following // interface: // -// type causer interface { -// Cause() error -// } +// type causer interface { +// Cause() error +// } // // If the error does not implement Cause, the original error will // be returned. If the error is nil, nil will be returned without further // investigation. +// +// Note: Cause only traverses errors implementing the causer interface. +// It does not traverse errors wrapped with fmt.Errorf("%w", err) or +// other standard library mechanisms. Prefer errors.Is or errors.As +// for matching errors across mixed wrapping styles. func Cause(err error) error { type causer interface { Cause() error diff --git a/errors_test.go b/errors_test.go index 2089b2f7..8a1b02e2 100644 --- a/errors_test.go +++ b/errors_test.go @@ -228,7 +228,7 @@ func TestWithMessagef(t *testing.T) { // but the change in errors#27 made them incomparable. Assert that // various kinds of errors have a functional equality operator, even // if the result of that equality is always false. -func TestErrorEquality(t *testing.T) { +func TestErrorEquality(_ *testing.T) { vals := []error{ nil, io.EOF, diff --git a/format_test.go b/format_test.go index cb1df821..04a9bebe 100644 --- a/format_test.go +++ b/format_test.go @@ -27,7 +27,7 @@ func TestFormatNew(t *testing.T) { "%+v", "error\n" + "github.com/pkg/errors.TestFormatNew\n" + - "\t.+/github.com/pkg/errors/format_test.go:26", + "\t.+/format_test.go:26", }, { New("error"), "%q", @@ -57,7 +57,7 @@ func TestFormatErrorf(t *testing.T) { "%+v", "error\n" + "github.com/pkg/errors.TestFormatErrorf\n" + - "\t.+/github.com/pkg/errors/format_test.go:56", + "\t.+/format_test.go:56", }} for i, tt := range tests { @@ -83,7 +83,7 @@ func TestFormatWrap(t *testing.T) { "%+v", "error\n" + "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:82", + "\t.+/format_test.go:82", }, { Wrap(io.EOF, "error"), "%s", @@ -98,14 +98,14 @@ func TestFormatWrap(t *testing.T) { "EOF\n" + "error\n" + "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:96", + "\t.+/format_test.go:96", }, { Wrap(Wrap(io.EOF, "error1"), "error2"), "%+v", "EOF\n" + "error1\n" + "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:103\n", + "\t.+/format_test.go:103\n", }, { Wrap(New("error with space"), "context"), "%q", @@ -136,7 +136,7 @@ func TestFormatWrapf(t *testing.T) { "EOF\n" + "error2\n" + "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:134", + "\t.+/format_test.go:134", }, { Wrapf(New("error"), "error%d", 2), "%s", @@ -150,7 +150,7 @@ func TestFormatWrapf(t *testing.T) { "%+v", "error\n" + "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:149", + "\t.+/format_test.go:149", }} for i, tt := range tests { @@ -176,7 +176,7 @@ func TestFormatWithStack(t *testing.T) { "%+v", []string{"EOF", "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:175"}, + "\t.+/format_test.go:175"}, }, { WithStack(New("error")), "%s", @@ -190,36 +190,36 @@ func TestFormatWithStack(t *testing.T) { "%+v", []string{"error", "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189", + "\t.+/format_test.go:189", "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189"}, + "\t.+/format_test.go:189"}, }, { WithStack(WithStack(io.EOF)), "%+v", []string{"EOF", "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197", + "\t.+/format_test.go:197", "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197"}, + "\t.+/format_test.go:197"}, }, { WithStack(WithStack(Wrapf(io.EOF, "message"))), "%+v", []string{"EOF", "message", "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", + "\t.+/format_test.go:205", "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", + "\t.+/format_test.go:205", "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205"}, + "\t.+/format_test.go:205"}, }, { WithStack(Errorf("error%d", 1)), "%+v", []string{"error1", "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216", + "\t.+/format_test.go:216", "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216"}, + "\t.+/format_test.go:216"}, }} for i, tt := range tests { @@ -246,7 +246,7 @@ func TestFormatWithMessage(t *testing.T) { []string{ "error", "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:244", + "\t.+/format_test.go:244", "error2"}, }, { WithMessage(io.EOF, "addition1"), @@ -273,13 +273,13 @@ func TestFormatWithMessage(t *testing.T) { "%+v", []string{"EOF", "error1", "error2", "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:272"}, + "\t.+/format_test.go:272"}, }, { WithMessage(Errorf("error%d", 1), "error2"), "%+v", []string{"error1", "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:278", + "\t.+/format_test.go:278", "error2"}, }, { WithMessage(WithStack(io.EOF), "error"), @@ -287,7 +287,7 @@ func TestFormatWithMessage(t *testing.T) { []string{ "EOF", "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:285", + "\t.+/format_test.go:285", "error"}, }, { WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"), @@ -295,10 +295,10 @@ func TestFormatWithMessage(t *testing.T) { []string{ "EOF", "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", + "\t.+/format_test.go:293", "inside-error", "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", + "\t.+/format_test.go:293", "outside-error"}, }} @@ -315,11 +315,11 @@ func TestFormatGeneric(t *testing.T) { {New("new-error"), []string{ "new-error", "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:315"}, + "\t.+/format_test.go:315"}, }, {Errorf("errorf-error"), []string{ "errorf-error", "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:319"}, + "\t.+/format_test.go:319"}, }, {errors.New("errors-new-error"), []string{ "errors-new-error"}, }, @@ -330,24 +330,24 @@ func TestFormatGeneric(t *testing.T) { func(err error) error { return WithMessage(err, "with-message") }, []string{"with-message"}, }, { - func(err error) error { return WithStack(err) }, + func(err error) error { return WithStack(err) }, //nolint:gocritic // unlambda: closure needed for correct stack trace location []string{ "github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" + - ".+/github.com/pkg/errors/format_test.go:333", + ".+/format_test.go:333", }, }, { func(err error) error { return Wrap(err, "wrap-error") }, []string{ "wrap-error", "github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" + - ".+/github.com/pkg/errors/format_test.go:339", + ".+/format_test.go:339", }, }, { func(err error) error { return Wrapf(err, "wrapf-error%d", 1) }, []string{ "wrapf-error1", "github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" + - ".+/github.com/pkg/errors/format_test.go:346", + ".+/format_test.go:346", }, }, } @@ -374,9 +374,9 @@ func TestFormatWrappedNew(t *testing.T) { "%+v", "error\n" + "github.com/pkg/errors.wrappedNew\n" + - "\t.+/github.com/pkg/errors/format_test.go:364\n" + + "\t.+/format_test.go:364\n" + "github.com/pkg/errors.TestFormatWrappedNew\n" + - "\t.+/github.com/pkg/errors/format_test.go:373", + "\t.+/format_test.go:373", }} for i, tt := range tests { @@ -387,8 +387,8 @@ func TestFormatWrappedNew(t *testing.T) { func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) { t.Helper() got := fmt.Sprintf(format, arg) - gotLines := strings.SplitN(got, "\n", -1) - wantLines := strings.SplitN(want, "\n", -1) + gotLines := strings.Split(got, "\n") + wantLines := strings.Split(want, "\n") if len(wantLines) > len(gotLines) { t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want) @@ -409,22 +409,21 @@ func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) var stackLineR = regexp.MustCompile(`\.`) // parseBlocks parses input into a slice, where: -// - incase entry contains a newline, its a stacktrace -// - incase entry contains no newline, its a solo line. +// - incase entry contains a newline, its a stacktrace +// - incase entry contains no newline, its a solo line. // // Detecting stack boundaries only works incase the WithStack-calls are // to be found on the same line, thats why it is optionally here. // // Example use: // -// for _, e := range blocks { -// if strings.ContainsAny(e, "\n") { -// // Match as stack -// } else { -// // Match as line -// } -// } -// +// for _, e := range blocks { +// if strings.ContainsAny(e, "\n") { +// // Match as stack +// } else { +// // Match as line +// } +// } func parseBlocks(input string, detectStackboundaries bool) ([]string, error) { var blocks []string @@ -502,11 +501,8 @@ func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format stri t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n", n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want)) } - } else { - // Match as message - if got[i] != want[i] { - t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i]) - } + } else if got[i] != want[i] { + t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i]) } } } @@ -547,9 +543,9 @@ func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, li // Merge two stacks behind each other. if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") { - want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...) + want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...) //nolint:gocritic // appendAssign: intentionally assigning to want, not beforeWant } else { - want = append(beforeWant, w.want...) + want = append(beforeWant, w.want...) //nolint:gocritic // appendAssign: intentionally assigning to want, not beforeWant } testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false) diff --git a/go113.go b/go113.go index be0d10d0..2c83c724 100644 --- a/go113.go +++ b/go113.go @@ -1,3 +1,4 @@ +//go:build go1.13 // +build go1.13 package errors diff --git a/go113_test.go b/go113_test.go index 4ea37e61..d637cb2d 100644 --- a/go113_test.go +++ b/go113_test.go @@ -1,3 +1,4 @@ +//go:build go1.13 // +build go1.13 package errors diff --git a/hack/dockerfiles/lint.Dockerfile b/hack/dockerfiles/lint.Dockerfile index 865c9242..ee1cce9d 100644 --- a/hack/dockerfiles/lint.Dockerfile +++ b/hack/dockerfiles/lint.Dockerfile @@ -4,7 +4,7 @@ ARG GO_VERSION=1.26 ARG ALPINE_VERSION=3.23 ARG XX_VERSION=1.9.0 -ARG GOLANGCI_LINT_VERSION=2.11.2 +ARG GOLANGCI_LINT_VERSION=2.11.4 FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}-alpine${ALPINE_VERSION} AS golang-base FROM --platform=$BUILDPLATFORM tonistiigi/xx:${XX_VERSION} AS xx @@ -21,7 +21,7 @@ ARG TARGETPLATFORM RUN --mount=type=bind \ --mount=target=/root/.cache,type=cache \ xx-go --wrap && \ - golangci-lint run && \ + GOROOT=$(xx-go env GOROOT) golangci-lint run && \ touch /golangci-lint.done FROM scratch diff --git a/json_test.go b/json_test.go index ad1adec9..dfdc2cfb 100644 --- a/json_test.go +++ b/json_test.go @@ -12,7 +12,7 @@ func TestFrameMarshalText(t *testing.T) { want string }{{ initpc, - `^github.com/pkg/errors\.init(\.ializers)? .+/github\.com/pkg/errors/stack_test.go:\d+$`, + `^github.com/pkg/errors\.init(\.ializers)? .+/stack_test.go:\d+$`, }, { 0, `^unknown$`, @@ -34,7 +34,7 @@ func TestFrameMarshalJSON(t *testing.T) { want string }{{ initpc, - `^"github\.com/pkg/errors\.init(\.ializers)? .+/github\.com/pkg/errors/stack_test.go:\d+"$`, + `^"github\.com/pkg/errors\.init(\.ializers)? .+/stack_test.go:\d+"$`, }, { 0, `^"unknown"$`, diff --git a/stack.go b/stack.go index 779a8348..e3fd21f6 100644 --- a/stack.go +++ b/stack.go @@ -51,16 +51,16 @@ func (f Frame) name() string { // Format formats the frame according to the fmt.Formatter interface. // -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d +// %s source file +// %d source line +// %n function name +// %v equivalent to %s:%d // // Format accepts flags that alter the printing of some verbs, as follows: // -// %+s function name and path of source file relative to the compile time -// GOPATH separated by \n\t (\n\t) -// %+v equivalent to %+s:%d +// %+s function name and path of source file relative to the compile time +// GOPATH separated by \n\t (\n\t) +// %+v equivalent to %+s:%d func (f Frame) Format(s fmt.State, verb rune) { switch verb { case 's': @@ -98,12 +98,12 @@ type StackTrace []Frame // Format formats the stack of Frames according to the fmt.Formatter interface. // -// %s lists source files for each Frame in the stack -// %v lists the source file and line number for each Frame in the stack +// %s lists source files for each Frame in the stack +// %v lists the source file and line number for each Frame in the stack // // Format accepts flags that alter the printing of some verbs, as follows: // -// %+v Prints filename, function, and line number for each Frame in the stack. +// %+v Prints filename, function, and line number for each Frame in the stack. func (st StackTrace) Format(s fmt.State, verb rune) { switch verb { case 'v': @@ -140,14 +140,10 @@ func (st StackTrace) formatSlice(s fmt.State, verb rune) { type stack []uintptr func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } + if verb == 'v' && st.Flag('+') { + for _, pc := range *s { + f := Frame(pc) + fmt.Fprintf(st, "\n%+v", f) } } } diff --git a/stack_test.go b/stack_test.go index aa10a72e..af8d9da0 100644 --- a/stack_test.go +++ b/stack_test.go @@ -33,7 +33,7 @@ func TestFrameFormat(t *testing.T) { initpc, "%+s", "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go", + "\t.+/stack_test.go", }, { 0, "%s", @@ -80,7 +80,7 @@ func TestFrameFormat(t *testing.T) { initpc, "%+v", "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go:9", + "\t.+/stack_test.go:9", }, { 0, "%v", @@ -120,24 +120,24 @@ func TestStackTrace(t *testing.T) { }{{ New("ooh"), []string{ "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:121", + "\t.+/stack_test.go:121", }, }, { Wrap(New("ooh"), "ahh"), []string{ "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:126", // this is the stack of Wrap, not New + "\t.+/stack_test.go:126", // this is the stack of Wrap, not New }, }, { Cause(Wrap(New("ooh"), "ahh")), []string{ "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:131", // this is the stack of New + "\t.+/stack_test.go:131", // this is the stack of New }, }, { func() error { return New("ooh") }(), []string{ `github.com/pkg/errors.TestStackTrace.func1` + - "\n\t.+/github.com/pkg/errors/stack_test.go:136", // this is the stack of New + "\n\t.+/stack_test.go:136", // this is the stack of New "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:136", // this is the stack of New's caller + "\t.+/stack_test.go:136", // this is the stack of New's caller }, }, { Cause(func() error { @@ -145,12 +145,12 @@ func TestStackTrace(t *testing.T) { return Errorf("hello %s", fmt.Sprintf("world: %s", "ooh")) }() }()), []string{ - `github.com/pkg/errors.TestStackTrace.func2.1` + - "\n\t.+/github.com/pkg/errors/stack_test.go:145", // this is the stack of Errorf - `github.com/pkg/errors.TestStackTrace.func2` + - "\n\t.+/github.com/pkg/errors/stack_test.go:146", // this is the stack of Errorf's caller + `github.com/pkg/errors.TestStackTrace(.TestStackTrace)?.func2(.1|.func3)` + + "\n\t.+/stack_test.go:145", // this is the stack of Errorf + `github.com/pkg/errors.TestStackTrace(.TestStackTrace)?.func2` + + "\n\t.+/stack_test.go:146", // this is the stack of Errorf's caller "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:147", // this is the stack of Errorf's caller's caller + "\t.+/stack_test.go:147", // this is the stack of Errorf's caller's caller }, }} for i, tt := range tests { @@ -226,9 +226,9 @@ func TestStackTraceFormat(t *testing.T) { "%+v", "\n" + "github.com/pkg/errors.stackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:174\n" + + "\t.+/stack_test.go:174\n" + "github.com/pkg/errors.TestStackTraceFormat\n" + - "\t.+/github.com/pkg/errors/stack_test.go:225", + "\t.+/stack_test.go:225", }, { stackTrace()[:2], "%#v", From 720bdaba10516cf9822ac11166d77abf015ad7f1 Mon Sep 17 00:00:00 2001 From: Tonis Tiigi Date: Sat, 7 Mar 2026 22:47:32 -0800 Subject: [PATCH 3/7] cleanup: remove go1.13 build tags Remove go1.13 build constraints from unwrap functions since go.mod minimum is go1.20. Rename go113.go and go113_test.go to unwrap.go and unwrap_test.go. Delete Makefile as build/test/lint are now handled by Docker Bake targets. Signed-off-by: Tonis Tiigi --- bench_test.go | 3 --- errors.go | 4 ++-- go113.go => unwrap.go | 3 --- go113_test.go => unwrap_test.go | 3 --- 4 files changed, 2 insertions(+), 11 deletions(-) rename go113.go => unwrap.go (97%) rename go113_test.go => unwrap_test.go (98%) diff --git a/bench_test.go b/bench_test.go index 73520e9d..b95f6495 100644 --- a/bench_test.go +++ b/bench_test.go @@ -1,6 +1,3 @@ -//go:build go1.7 -// +build go1.7 - package errors import ( diff --git a/errors.go b/errors.go index bf3e3699..a9f0128e 100644 --- a/errors.go +++ b/errors.go @@ -159,7 +159,7 @@ type withStack struct { func (w *withStack) Cause() error { return w.error } -// Unwrap provides compatibility for Go 1.13 error chains. +// Unwrap provides compatibility for errors.Is and errors.As. func (w *withStack) Unwrap() error { return w.error } func (w *withStack) Format(s fmt.State, verb rune) { @@ -244,7 +244,7 @@ type withMessage struct { func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } func (w *withMessage) Cause() error { return w.cause } -// Unwrap provides compatibility for Go 1.13 error chains. +// Unwrap provides compatibility for errors.Is and errors.As. func (w *withMessage) Unwrap() error { return w.cause } func (w *withMessage) Format(s fmt.State, verb rune) { diff --git a/go113.go b/unwrap.go similarity index 97% rename from go113.go rename to unwrap.go index 2c83c724..65480a8d 100644 --- a/go113.go +++ b/unwrap.go @@ -1,6 +1,3 @@ -//go:build go1.13 -// +build go1.13 - package errors import ( diff --git a/go113_test.go b/unwrap_test.go similarity index 98% rename from go113_test.go rename to unwrap_test.go index d637cb2d..9cc14ba0 100644 --- a/go113_test.go +++ b/unwrap_test.go @@ -1,6 +1,3 @@ -//go:build go1.13 -// +build go1.13 - package errors import ( From e13c6456f09c21ea51fc3ada6d7914cb7b6902fc Mon Sep 17 00:00:00 2001 From: Tonis Tiigi Date: Sat, 7 Mar 2026 22:58:45 -0800 Subject: [PATCH 4/7] modernize: replace interface{} with any and fix deepequalerrors Signed-off-by: Tonis Tiigi --- bench_test.go | 2 +- errors.go | 6 +++--- errors_test.go | 3 +-- format_test.go | 4 ++-- unwrap.go | 4 ++-- unwrap_test.go | 7 +++---- 6 files changed, 12 insertions(+), 14 deletions(-) diff --git a/bench_test.go b/bench_test.go index b95f6495..6eef3a99 100644 --- a/bench_test.go +++ b/bench_test.go @@ -23,7 +23,7 @@ func yesErrors(at, depth int) error { // GlobalE is an exported global to store the result of benchmark results, // preventing the compiler from optimising the benchmark functions away. -var GlobalE interface{} +var GlobalE any func BenchmarkErrors(b *testing.B) { type run struct { diff --git a/errors.go b/errors.go index a9f0128e..765f86d0 100644 --- a/errors.go +++ b/errors.go @@ -109,7 +109,7 @@ func New(message string) error { // Errorf formats according to a format specifier and returns the string // as a value that satisfies error. // Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { +func Errorf(format string, args ...any) error { return &fundamental{ msg: fmt.Sprintf(format, args...), stack: callers(), @@ -198,7 +198,7 @@ func Wrap(err error, message string) error { // Wrapf returns an error annotating err with a stack trace // at the point Wrapf is called, and the format specifier. // If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { +func Wrapf(err error, format string, args ...any) error { if err == nil { return nil } @@ -226,7 +226,7 @@ func WithMessage(err error, message string) error { // WithMessagef annotates err with the format specifier. // If err is nil, WithMessagef returns nil. -func WithMessagef(err error, format string, args ...interface{}) error { +func WithMessagef(err error, format string, args ...any) error { if err == nil { return nil } diff --git a/errors_test.go b/errors_test.go index 8a1b02e2..e74fdd3d 100644 --- a/errors_test.go +++ b/errors_test.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "io" - "reflect" "testing" ) @@ -100,7 +99,7 @@ func TestCause(t *testing.T) { for i, tt := range tests { got := Cause(tt.err) - if !reflect.DeepEqual(got, tt.want) { + if got != tt.want { t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want) } } diff --git a/format_test.go b/format_test.go index 04a9bebe..23f42e32 100644 --- a/format_test.go +++ b/format_test.go @@ -384,7 +384,7 @@ func TestFormatWrappedNew(t *testing.T) { } } -func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) { +func testFormatRegexp(t *testing.T, n int, arg any, format, want string) { t.Helper() got := fmt.Sprintf(format, arg) gotLines := strings.Split(got, "\n") @@ -477,7 +477,7 @@ func parseBlocks(input string, detectStackboundaries bool) ([]string, error) { return blocks, nil } -func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) { +func testFormatCompleteCompare(t *testing.T, n int, arg any, format string, want []string, detectStackBoundaries bool) { gotStr := fmt.Sprintf(format, arg) got, err := parseBlocks(gotStr, detectStackBoundaries) diff --git a/unwrap.go b/unwrap.go index 65480a8d..61c03513 100644 --- a/unwrap.go +++ b/unwrap.go @@ -20,13 +20,13 @@ func Is(err, target error) bool { return stderrors.Is(err, target) } // repeatedly calling Unwrap. // // An error matches target if the error's concrete value is assignable to the value -// pointed to by target, or if the error has a method As(interface{}) bool such that +// pointed to by target, or if the error has a method As(any) bool such that // As(target) returns true. In the latter case, the As method is responsible for // setting target. // // As will panic if target is not a non-nil pointer to either a type that implements // error, or to any interface type. As returns false if err is nil. -func As(err error, target interface{}) bool { return stderrors.As(err, target) } +func As(err error, target any) bool { return stderrors.As(err, target) } // Unwrap returns the result of calling the Unwrap method on err, if err's // type contains an Unwrap method returning error. diff --git a/unwrap_test.go b/unwrap_test.go index 9cc14ba0..687c4f84 100644 --- a/unwrap_test.go +++ b/unwrap_test.go @@ -3,7 +3,6 @@ package errors import ( stderrors "errors" "fmt" - "reflect" "testing" ) @@ -80,7 +79,7 @@ func TestAs(t *testing.T) { type args struct { err error - target interface{} + target any } tests := []struct { name string @@ -127,7 +126,7 @@ func TestAs(t *testing.T) { } ce := tt.args.target.(*customErr) - if !reflect.DeepEqual(err, *ce) { + if err != *ce { t.Errorf("set target error failed, target error is %v", *ce) } }) @@ -168,7 +167,7 @@ func TestUnwrap(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if err := Unwrap(tt.args.err); !reflect.DeepEqual(err, tt.want) { + if err := Unwrap(tt.args.err); err != tt.want { t.Errorf("Unwrap() error = %v, want %v", err, tt.want) } }) From 05d44500c495eb57e1bbf2dabd9048b888d4f413 Mon Sep 17 00:00:00 2001 From: Tonis Tiigi Date: Sat, 7 Mar 2026 23:05:13 -0800 Subject: [PATCH 5/7] ci: replace Travis/AppVeyor with GitHub Actions Signed-off-by: Tonis Tiigi --- .github/workflows/ci.yml | 60 ++++++++++++++++++++++++++++++++++++---- .travis.yml | 12 -------- Makefile | 5 ---- appveyor.yml | 32 --------------------- 4 files changed, 54 insertions(+), 55 deletions(-) delete mode 100644 .travis.yml delete mode 100644 Makefile delete mode 100644 appveyor.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f6fc4468..f23597fc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,14 +1,62 @@ name: ci +permissions: + contents: read +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + on: - workflow_dispatch: push: + branches: + - master pull_request: jobs: - dummy: - runs-on: ubuntu-latest + build: + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + goversion: ["1.20", "1.21", "1.22", "1.23", "1.24", "1.25", "1.26"] + steps: + - uses: docker/setup-buildx-action@v3 + - uses: docker/bake-action@v7 + with: + targets: build-all + env: + GO_VERSION: ${{ matrix.goversion }} + test: + runs-on: ubuntu-24.04 + steps: + - uses: docker/setup-buildx-action@v3 + - uses: docker/bake-action@v7 + with: + targets: test + env: + COVER_FILENAME: "cover.out" + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v4 + with: + disable_file_fixes: true + files: ./cover.out + token: ${{ secrets.CODECOV_TOKEN }} + test-os: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [macos-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: stable + - run: go test -v ./... + lint: + runs-on: ubuntu-24.04 steps: - - - name: Checkout - uses: actions/checkout@v2 \ No newline at end of file + - uses: docker/setup-buildx-action@v3 + - uses: docker/bake-action@v7 + with: + targets: lint-all diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 81e650b9..00000000 --- a/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -arch: - - amd64 - -language: go -go_import_path: github.com/pkg/errors -go: - - 1.14 - - 1.15 - - tip - -script: - - make check diff --git a/Makefile b/Makefile deleted file mode 100644 index 51ae1770..00000000 --- a/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -PKGS := github.com/pkg/errors -GO := go - -test: - $(GO) test $(PKGS) diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index a932eade..00000000 --- a/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off From a6e40abbc432fe6c751878f5513bc390bdfd42c8 Mon Sep 17 00:00:00 2001 From: Tonis Tiigi Date: Sun, 8 Mar 2026 21:31:31 -0700 Subject: [PATCH 6/7] docs: update README for maintenance mode Remove defunct Travis-CI and AppVeyor badges. Replace the outdated Roadmap section with a comparison to the standard library's errors package. Update Contributing section to reflect current maintenance-mode policy. Signed-off-by: Tonis Tiigi --- README.md | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 54dfdcb1..cb08fcac 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) +# errors [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](https://pkg.go.dev/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge) Package errors provides simple error handling primitives. @@ -41,18 +41,13 @@ default: [Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). -## Roadmap +## Compared to the standard library's `errors` package -With the upcoming [Go2 error proposals](https://go.googlesource.com/proposal/+/master/design/go2draft.md) this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows: - -- 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible) -- 1.0. Final release. +This package was initially built to manage chains of typed errors. Support for this was later added to the standard library's `errors` package via `Unwrap` methods. Unfortunately, the standard library's `errors` package does not support stack traces, so it cannot be used as a drop-in replacement for the features this package provides. This package will mostly work interoperably with the standard library's `errors` package; typed errors added in `pkg/errors` work fine in `errors.Is` and `errors.As`, and you can wrap them with other typed errors. ## Contributing -Because of the Go2 errors changes, this package is not accepting proposals for new functionality. With that said, we welcome pull requests, bug fixes and issue reports. - -Before sending a PR, please discuss your change by raising an issue. +This package is in maintenance mode. New features that extend the scope of the package are not being accepted and should be implemented in other modules. Exceptions would be features that improve interoperability with the standard library's `errors` package when it receives new features, as `pkg/errors` should mostly be able to act as a drop-in replacement. Bug fixes and reports are welcome. CI will be maintained to make sure the package is tested against new versions of Go and Go linting tools. ## License From 279ed80a1222426fc3ba68c3386c170a927dbc15 Mon Sep 17 00:00:00 2001 From: Tonis Tiigi Date: Sat, 7 Mar 2026 22:53:07 -0800 Subject: [PATCH 7/7] feat: add Join and AsType standard library shortcuts Signed-off-by: Tonis Tiigi --- astype.go | 10 ++++++ astype_go126.go | 13 +++++++ unwrap.go | 8 +++++ unwrap_test.go | 91 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 122 insertions(+) create mode 100644 astype.go create mode 100644 astype_go126.go diff --git a/astype.go b/astype.go new file mode 100644 index 00000000..52d5e169 --- /dev/null +++ b/astype.go @@ -0,0 +1,10 @@ +//go:build !go1.26 + +package errors + +// AsType finds the first error in err's chain that matches type E, +// and if so, returns that error value and true. +func AsType[E error](err error) (E, bool) { + var target E + return target, As(err, &target) +} diff --git a/astype_go126.go b/astype_go126.go new file mode 100644 index 00000000..8a2eccbd --- /dev/null +++ b/astype_go126.go @@ -0,0 +1,13 @@ +//go:build go1.26 + +package errors + +import ( + stderrors "errors" +) + +// AsType finds the first error in err's chain that matches type E, +// and if so, returns that error value and true. +func AsType[E error](err error) (E, bool) { + return stderrors.AsType[E](err) +} diff --git a/unwrap.go b/unwrap.go index 61c03513..0351b7ce 100644 --- a/unwrap.go +++ b/unwrap.go @@ -34,3 +34,11 @@ func As(err error, target any) bool { return stderrors.As(err, target) } func Unwrap(err error) error { return stderrors.Unwrap(err) } + +// Join returns an error that wraps the given errors. +// Any nil error values are discarded. +// Join returns nil if every value in errs is nil. +// The error formats each wrapped error, separated by newlines. +func Join(errs ...error) error { + return stderrors.Join(errs...) +} diff --git a/unwrap_test.go b/unwrap_test.go index 687c4f84..e70f4bf8 100644 --- a/unwrap_test.go +++ b/unwrap_test.go @@ -3,6 +3,7 @@ package errors import ( stderrors "errors" "fmt" + "io" "testing" ) @@ -173,3 +174,93 @@ func TestUnwrap(t *testing.T) { }) } } + +func TestJoin(t *testing.T) { + err1 := New("err1") + err2 := New("err2") + + tests := []struct { + name string + errs []error + want string + }{ + { + name: "two errors", + errs: []error{err1, err2}, + want: "err1\nerr2", + }, + { + name: "nil filtered", + errs: []error{err1, nil, err2}, + want: "err1\nerr2", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := Join(tt.errs...) + if err == nil { + t.Fatal("Join() = nil, want non-nil") + } + if got := err.Error(); got != tt.want { + t.Errorf("Join().Error() = %q, want %q", got, tt.want) + } + }) + } +} + +func TestJoinNil(t *testing.T) { + if err := Join(); err != nil { + t.Errorf("Join() = %v, want nil", err) + } + if err := Join(nil, nil); err != nil { + t.Errorf("Join(nil, nil) = %v, want nil", err) + } +} + +func TestWrapAsType(t *testing.T) { + err := customErr{msg: "test"} + wrapped := Wrap(err, "wrapped") + + tests := []struct { + name string + fn func(error) (customErr, bool) + }{ + {name: "AsType", fn: AsType[customErr]}, + {name: "stderrors.AsType", fn: stderrors.AsType[customErr]}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, ok := tt.fn(wrapped) + if !ok { + t.Fatalf("%s[customErr]() = false, want true", tt.name) + } + if got != err { + t.Errorf("%s[customErr]() = %v, want %v", tt.name, got, err) + } + }) + } +} + +func TestAsTypeNotFound(t *testing.T) { + err := io.EOF + assertNotFound := func(name string, ok bool) { + t.Helper() + if ok { + t.Errorf("%s[customErr](io.EOF) = true, want false", name) + } + } + + tests := []struct { + name string + fn func(error) (customErr, bool) + }{ + {name: "AsType", fn: AsType[customErr]}, + {name: "stderrors.AsType", fn: stderrors.AsType[customErr]}, + } + + for _, tt := range tests { + _, ok := tt.fn(err) + assertNotFound(tt.name, ok) + } +}