dev: replace pkg/errors with native error wrapping (#3604)

Co-authored-by: Fernandez Ludovic <ldez@users.noreply.github.com>
This commit is contained in:
Oleksandr Redko 2023-02-22 02:35:43 +02:00 committed by GitHub
parent 6c21f049c3
commit b673c5c1af
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 106 additions and 126 deletions

2
go.mod
View File

@ -75,7 +75,6 @@ require (
github.com/nishanths/exhaustive v0.9.5
github.com/nishanths/predeclared v0.2.2
github.com/nunnatsa/ginkgolinter v0.8.1
github.com/pkg/errors v0.9.1
github.com/polyfloyd/go-errorlint v1.1.0
github.com/quasilyte/go-ruleguard/dsl v0.3.22
github.com/ryancurrah/gomodguard v1.3.0
@ -154,6 +153,7 @@ require (
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c // indirect
github.com/prometheus/client_golang v1.12.1 // indirect

View File

@ -12,6 +12,7 @@ import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
@ -20,8 +21,6 @@ import (
"strings"
"time"
"github.com/pkg/errors"
"github.com/golangci/golangci-lint/internal/renameio"
"github.com/golangci/golangci-lint/internal/robustio"
)
@ -80,7 +79,7 @@ func (c *Cache) fileName(id [HashSize]byte, key string) string {
var errMissing = errors.New("cache entry not found")
func IsErrMissing(err error) bool {
return errors.Cause(err) == errMissing
return errors.Is(err, errMissing)
}
const (
@ -169,10 +168,10 @@ func (c *Cache) get(id ActionID) (Entry, error) {
etime := entry[1 : 1+20]
var buf [HashSize]byte
if _, err = hex.Decode(buf[:], eid); err != nil || buf != id {
return failed(errors.Wrapf(err, "failed to hex decode eid data in %s", fileName))
return failed(fmt.Errorf("failed to hex decode eid data in %s: %w", fileName, err))
}
if _, err = hex.Decode(buf[:], eout); err != nil {
return failed(errors.Wrapf(err, "failed to hex decode eout data in %s", fileName))
return failed(fmt.Errorf("failed to hex decode eout data in %s: %w", fileName, err))
}
i := 0
for i < len(esize) && esize[i] == ' ' {
@ -192,7 +191,7 @@ func (c *Cache) get(id ActionID) (Entry, error) {
}
if err = c.used(fileName); err != nil {
return failed(errors.Wrapf(err, "failed to mark %s as used", fileName))
return failed(fmt.Errorf("failed to mark %s as used: %w", fileName, err))
}
return Entry{buf, size, time.Unix(0, tm)}, nil
@ -264,7 +263,7 @@ func (c *Cache) used(file string) error {
if os.IsNotExist(err) {
return errMissing
}
return errors.Wrapf(err, "failed to stat file %s", file)
return fmt.Errorf("failed to stat file %s: %w", file, err)
}
if c.now().Sub(info.ModTime()) < mtimeInterval {
@ -272,7 +271,7 @@ func (c *Cache) used(file string) error {
}
if err := os.Chtimes(file, c.now(), c.now()); err != nil {
return errors.Wrapf(err, "failed to change time of file %s", file)
return fmt.Errorf("failed to change time of file %s: %w", file, err)
}
return nil
@ -385,7 +384,7 @@ func (c *Cache) putIndexEntry(id ActionID, out OutputID, size int64, allowVerify
return err
}
if err = os.Chtimes(file, c.now(), c.now()); err != nil { // mainly for tests
return errors.Wrapf(err, "failed to change time of file %s", file)
return fmt.Errorf("failed to change time of file %s: %w", file, err)
}
return nil
@ -443,7 +442,7 @@ func (c *Cache) copyFile(file io.ReadSeeker, out OutputID, size int64) error {
if f, openErr := os.Open(name); openErr == nil {
h := sha256.New()
if _, copyErr := io.Copy(h, f); copyErr != nil {
return errors.Wrap(copyErr, "failed to copy to sha256")
return fmt.Errorf("failed to copy to sha256: %w", copyErr)
}
f.Close()
@ -519,7 +518,7 @@ func (c *Cache) copyFile(file io.ReadSeeker, out OutputID, size int64) error {
return err
}
if err = os.Chtimes(name, c.now(), c.now()); err != nil { // mainly for tests
return errors.Wrapf(err, "failed to change time of file %s", name)
return fmt.Errorf("failed to change time of file %s: %w", name, err)
}
return nil

View File

@ -4,12 +4,12 @@ import (
"bytes"
"encoding/gob"
"encoding/hex"
"errors"
"fmt"
"runtime"
"sort"
"sync"
"github.com/pkg/errors"
"golang.org/x/tools/go/packages"
"github.com/golangci/golangci-lint/internal/cache"
@ -61,7 +61,7 @@ func (c *Cache) Put(pkg *packages.Package, mode HashMode, key string, data inter
err = gob.NewEncoder(buf).Encode(data)
})
if err != nil {
return errors.Wrap(err, "failed to gob encode")
return fmt.Errorf("failed to gob encode: %w", err)
}
var aID cache.ActionID
@ -71,13 +71,13 @@ func (c *Cache) Put(pkg *packages.Package, mode HashMode, key string, data inter
if err == nil {
subkey, subkeyErr := cache.Subkey(aID, key)
if subkeyErr != nil {
err = errors.Wrap(subkeyErr, "failed to build subkey")
err = fmt.Errorf("failed to build subkey: %w", subkeyErr)
}
aID = subkey
}
})
if err != nil {
return errors.Wrapf(err, "failed to calculate package %s action id", pkg.Name)
return fmt.Errorf("failed to calculate package %s action id: %w", pkg.Name, err)
}
c.ioSem <- struct{}{}
c.sw.TrackStage("cache io", func() {
@ -85,7 +85,7 @@ func (c *Cache) Put(pkg *packages.Package, mode HashMode, key string, data inter
})
<-c.ioSem
if err != nil {
return errors.Wrapf(err, "failed to save data to low-level cache by key %s for package %s", key, pkg.Name)
return fmt.Errorf("failed to save data to low-level cache by key %s for package %s: %w", key, pkg.Name, err)
}
return nil
@ -101,13 +101,13 @@ func (c *Cache) Get(pkg *packages.Package, mode HashMode, key string, data inter
if err == nil {
subkey, subkeyErr := cache.Subkey(aID, key)
if subkeyErr != nil {
err = errors.Wrap(subkeyErr, "failed to build subkey")
err = fmt.Errorf("failed to build subkey: %w", subkeyErr)
}
aID = subkey
}
})
if err != nil {
return errors.Wrapf(err, "failed to calculate package %s action id", pkg.Name)
return fmt.Errorf("failed to calculate package %s action id: %w", pkg.Name, err)
}
var b []byte
@ -120,14 +120,14 @@ func (c *Cache) Get(pkg *packages.Package, mode HashMode, key string, data inter
if cache.IsErrMissing(err) {
return ErrMissing
}
return errors.Wrapf(err, "failed to get data from low-level cache by key %s for package %s", key, pkg.Name)
return fmt.Errorf("failed to get data from low-level cache by key %s for package %s: %w", key, pkg.Name, err)
}
c.sw.TrackStage("gob", func() {
err = gob.NewDecoder(bytes.NewReader(b)).Decode(data)
})
if err != nil {
return errors.Wrap(err, "failed to gob decode")
return fmt.Errorf("failed to gob decode: %w", err)
}
return nil
@ -136,12 +136,12 @@ func (c *Cache) Get(pkg *packages.Package, mode HashMode, key string, data inter
func (c *Cache) pkgActionID(pkg *packages.Package, mode HashMode) (cache.ActionID, error) {
hash, err := c.packageHash(pkg, mode)
if err != nil {
return cache.ActionID{}, errors.Wrap(err, "failed to get package hash")
return cache.ActionID{}, fmt.Errorf("failed to get package hash: %w", err)
}
key, err := cache.NewHash("action ID")
if err != nil {
return cache.ActionID{}, errors.Wrap(err, "failed to make a hash")
return cache.ActionID{}, fmt.Errorf("failed to make a hash: %w", err)
}
fmt.Fprintf(key, "pkgpath %s\n", pkg.PkgPath)
fmt.Fprintf(key, "pkghash %s\n", hash)
@ -167,7 +167,7 @@ func (c *Cache) packageHash(pkg *packages.Package, mode HashMode) (string, error
key, err := cache.NewHash("package hash")
if err != nil {
return "", errors.Wrap(err, "failed to make a hash")
return "", fmt.Errorf("failed to make a hash: %w", err)
}
fmt.Fprintf(key, "pkgpath %s\n", pkg.PkgPath)
@ -176,7 +176,7 @@ func (c *Cache) packageHash(pkg *packages.Package, mode HashMode) (string, error
h, fErr := cache.FileHash(f)
<-c.ioSem
if fErr != nil {
return "", errors.Wrapf(fErr, "failed to calculate file %s hash", f)
return "", fmt.Errorf("failed to calculate file %s hash: %w", f, fErr)
}
fmt.Fprintf(key, "file %s %x\n", f, h)
}
@ -199,7 +199,7 @@ func (c *Cache) packageHash(pkg *packages.Package, mode HashMode) (string, error
depHash, depErr := c.packageHash(dep, depMode)
if depErr != nil {
return errors.Wrapf(depErr, "failed to calculate hash for dependency %s with mode %d", dep.Name, depMode)
return fmt.Errorf("failed to calculate hash for dependency %s with mode %d: %w", dep.Name, depMode, depErr)
}
fmt.Fprintf(key, "import %s %s\n", dep.PkgPath, depHash)

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"crypto/sha256"
"fmt"
"io"
"os"
"path/filepath"
@ -12,7 +13,6 @@ import (
"github.com/fatih/color"
"github.com/gofrs/flock"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"gopkg.in/yaml.v3"
@ -149,12 +149,12 @@ func (e *Executor) Execute() error {
func (e *Executor) initHashSalt(version string) error {
binSalt, err := computeBinarySalt(version)
if err != nil {
return errors.Wrap(err, "failed to calculate binary salt")
return fmt.Errorf("failed to calculate binary salt: %w", err)
}
configSalt, err := computeConfigSalt(e.cfg)
if err != nil {
return errors.Wrap(err, "failed to calculate config salt")
return fmt.Errorf("failed to calculate config salt: %w", err)
}
var b bytes.Buffer
@ -195,7 +195,7 @@ func computeConfigSalt(cfg *config.Config) ([]byte, error) {
lintersSettingsBytes, err := yaml.Marshal(cfg.LintersSettings)
if err != nil {
return nil, errors.Wrap(err, "failed to json marshal config linter settings")
return nil, fmt.Errorf("failed to json marshal config linter settings: %w", err)
}
var configData bytes.Buffer

View File

@ -2,6 +2,7 @@ package commands
import (
"context"
"errors"
"fmt"
"io"
"log"
@ -11,7 +12,6 @@ import (
"time"
"github.com/fatih/color"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
@ -355,7 +355,7 @@ func (e *Executor) runAnalysis(ctx context.Context, args []string) ([]result.Iss
lintCtx, err := e.contextLoader.Load(ctx, lintersToRun)
if err != nil {
return nil, errors.Wrap(err, "context loading failed")
return nil, fmt.Errorf("context loading failed: %w", err)
}
lintCtx.Log = e.log.Child(logutils.DebugKeyLintersContext)
@ -522,7 +522,8 @@ func (e *Executor) executeRun(_ *cobra.Command, args []string) {
if err := e.runAndPrint(ctx, args); err != nil {
e.log.Errorf("Running error: %s", err)
if e.exitCode == exitcodes.Success {
if exitErr, ok := errors.Cause(err).(*exitcodes.ExitError); ok {
var exitErr *exitcodes.ExitError
if errors.As(err, &exitErr) {
e.exitCode = exitErr.Code
} else {
e.exitCode = exitcodes.Failure

View File

@ -1,9 +1,8 @@
package config
import (
"errors"
"runtime"
"github.com/pkg/errors"
)
var defaultLintersSettings = LintersSettings{

View File

@ -5,8 +5,6 @@ import (
"os"
"sync"
"github.com/pkg/errors"
"github.com/golangci/golangci-lint/pkg/logutils"
)
@ -26,7 +24,7 @@ func (fc *FileCache) GetFileBytes(filePath string) ([]byte, error) {
fileBytes, err := os.ReadFile(filePath)
if err != nil {
return nil, errors.Wrapf(err, "can't read file %s", filePath)
return nil, fmt.Errorf("can't read file %s: %w", filePath, err)
}
fc.files.Store(filePath, fileBytes)

View File

@ -4,8 +4,6 @@ import (
"bytes"
"fmt"
"sync"
"github.com/pkg/errors"
)
type fileLinesCache [][]byte
@ -39,7 +37,7 @@ func (lc *LineCache) GetLine(filePath string, index1 int) (string, error) {
func (lc *LineCache) getRawLine(filePath string, index0 int) ([]byte, error) {
fc, err := lc.getFileCache(filePath)
if err != nil {
return nil, errors.Wrapf(err, "failed to get file %s lines cache", filePath)
return nil, fmt.Errorf("failed to get file %s lines cache: %w", filePath, err)
}
if index0 < 0 {
@ -61,7 +59,7 @@ func (lc *LineCache) getFileCache(filePath string) (fileLinesCache, error) {
fileBytes, err := lc.fileCache.GetFileBytes(filePath)
if err != nil {
return nil, errors.Wrapf(err, "can't get file %s bytes from cache", filePath)
return nil, fmt.Errorf("can't get file %s bytes from cache: %w", filePath, err)
}
fc := bytes.Split(fileBytes, []byte("\n"))

View File

@ -6,7 +6,6 @@ import (
"sync"
duplAPI "github.com/golangci/dupl"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/config"
@ -71,7 +70,7 @@ func runDupl(pass *analysis.Pass, settings *config.DuplSettings) ([]goanalysis.I
for _, i := range issues {
toFilename, err := fsutils.ShortestRelPath(i.To.Filename(), "")
if err != nil {
return nil, errors.Wrapf(err, "failed to get shortest rel path for %q", i.To.Filename())
return nil, fmt.Errorf("failed to get shortest rel path for %q: %w", i.To.Filename(), err)
}
dupl := fmt.Sprintf("%s:%d-%d", toFilename, i.To.LineStart(), i.To.LineEnd())

View File

@ -11,7 +11,6 @@ import (
"sync"
"github.com/kisielk/errcheck/errcheck"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/packages"
@ -143,7 +142,7 @@ func parseIgnoreConfig(s string) (map[string]*regexp.Regexp, error) {
func getChecker(errCfg *config.ErrcheckSettings) (*errcheck.Checker, error) {
ignoreConfig, err := parseIgnoreConfig(errCfg.Ignore)
if err != nil {
return nil, errors.Wrap(err, "failed to parse 'ignore' directive")
return nil, fmt.Errorf("failed to parse 'ignore' directive: %w", err)
}
checker := errcheck.Checker{
@ -252,7 +251,7 @@ func readExcludeFile(name string) ([]string, error) {
}
if fh == nil {
return nil, errors.Wrapf(err, "failed reading exclude file: %s", name)
return nil, fmt.Errorf("failed reading exclude file: %s: %w", name, err)
}
scanner := bufio.NewScanner(fh)
@ -263,7 +262,7 @@ func readExcludeFile(name string) ([]string, error) {
}
if err := scanner.Err(); err != nil {
return nil, errors.Wrapf(err, "failed scanning file: %s", name)
return nil, fmt.Errorf("failed scanning file: %s: %w", name, err)
}
return excludes, nil

View File

@ -1,10 +1,10 @@
package golinters
import (
"fmt"
"sync"
"github.com/ashanbrown/forbidigo/forbidigo"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/config"
@ -59,14 +59,14 @@ func runForbidigo(pass *analysis.Pass, settings *config.ForbidigoSettings) ([]go
forbid, err := forbidigo.NewLinter(settings.Forbid, options...)
if err != nil {
return nil, errors.Wrapf(err, "failed to create linter %q", forbidigoName)
return nil, fmt.Errorf("failed to create linter %q: %w", forbidigoName, err)
}
var issues []goanalysis.Issue
for _, file := range pass.Files {
hints, err := forbid.RunWithConfig(forbidigo.RunConfig{Fset: pass.Fset}, file)
if err != nil {
return nil, errors.Wrapf(err, "forbidigo linter failed on file %q", file.Name.String())
return nil, fmt.Errorf("forbidigo linter failed on file %q: %w", file.Name.String(), err)
}
for _, hint := range hints {

View File

@ -12,7 +12,6 @@ import (
"github.com/hexops/gotextdiff"
"github.com/hexops/gotextdiff/myers"
"github.com/hexops/gotextdiff/span"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/config"
@ -101,7 +100,7 @@ func runGci(pass *analysis.Pass, lintCtx *linter.Context, cfg *gcicfg.Config, lo
is, err := extractIssuesFromPatch(diff, lintCtx, gciName)
if err != nil {
return nil, errors.Wrapf(err, "can't extract issues from gci diff output %s", diff)
return nil, fmt.Errorf("can't extract issues from gci diff output %s: %w", diff, err)
}
for i := range is {

View File

@ -1,9 +1,9 @@
package goanalysis
import (
"errors"
"fmt"
"github.com/pkg/errors"
"golang.org/x/tools/go/packages"
"github.com/golangci/golangci-lint/pkg/lint/linter"

View File

@ -2,11 +2,11 @@ package goanalysis
import (
"context"
"errors"
"flag"
"fmt"
"strings"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/lint/linter"
@ -116,7 +116,7 @@ func (lnt *Linter) configureAnalyzer(a *analysis.Analyzer, cfg map[string]interf
}
if err := f.Value.Set(valueToString(v)); err != nil {
return errors.Wrapf(err, "failed to set analyzer setting %q with value %v", k, v)
return fmt.Errorf("failed to set analyzer setting %q with value %v: %w", k, v, err)
}
}
@ -137,7 +137,7 @@ func (lnt *Linter) configure() error {
}
if err := lnt.configureAnalyzer(a, analyzerSettings); err != nil {
return errors.Wrapf(err, "failed to configure analyzer %s", analyzerName)
return fmt.Errorf("failed to configure analyzer %s: %w", analyzerName, err)
}
}
@ -146,11 +146,11 @@ func (lnt *Linter) configure() error {
func (lnt *Linter) preRun(lintCtx *linter.Context) error {
if err := analysis.Validate(lnt.analyzers); err != nil {
return errors.Wrap(err, "failed to validate analyzers")
return fmt.Errorf("failed to validate analyzers: %w", err)
}
if err := lnt.configure(); err != nil {
return errors.Wrap(err, "failed to configure analyzers")
return fmt.Errorf("failed to configure analyzers: %w", err)
}
if lnt.contextSetter != nil {

View File

@ -2,8 +2,8 @@ package goanalysis
import (
"context"
"fmt"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/lint/linter"
@ -24,7 +24,7 @@ func NewMetaLinter(linters []*Linter) *MetaLinter {
func (ml MetaLinter) Run(_ context.Context, lintCtx *linter.Context) ([]result.Issue, error) {
for _, l := range ml.linters {
if err := l.preRun(lintCtx); err != nil {
return nil, errors.Wrapf(err, "failed to pre-run %s", l.Name())
return nil, fmt.Errorf("failed to pre-run %s: %w", l.Name(), err)
}
}

View File

@ -11,12 +11,12 @@ package goanalysis
import (
"encoding/gob"
"fmt"
"go/token"
"runtime"
"sort"
"sync"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/packages"
@ -311,7 +311,7 @@ func extractDiagnostics(roots []*action) (retDiags []Diagnostic, retErrors []err
if pe, ok := act.err.(*errorutil.PanicError); ok {
panic(pe)
}
retErrors = append(retErrors, errors.Wrap(act.err, act.a.Name))
retErrors = append(retErrors, fmt.Errorf("%s: %w", act.a.Name, act.err))
return
}

View File

@ -1,6 +1,7 @@
package goanalysis
import (
"errors"
"fmt"
"go/types"
"io"
@ -9,7 +10,6 @@ import (
"time"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/packages"
"golang.org/x/tools/go/types/objectpath"
@ -125,7 +125,7 @@ func (act *action) analyze() {
continue
}
depErrors = multierror.Append(depErrors, errors.Cause(dep.err))
depErrors = multierror.Append(depErrors, errors.Unwrap(dep.err))
}
if depErrors != nil {
depErrors.ErrorFormat = func(e []error) string {
@ -182,7 +182,7 @@ func (act *action) analyze() {
// It looks like there should be !pass.Analyzer.RunDespiteErrors
// but govet's cgocall crashes on it. Govet itself contains !pass.Analyzer.RunDespiteErrors condition here,
// but it exits before it if packages.Load have failed.
act.err = errors.Wrap(&IllTypedError{Pkg: act.pkg}, "analysis skipped")
act.err = fmt.Errorf("analysis skipped: %w", &IllTypedError{Pkg: act.pkg})
} else {
startedAt = time.Now()
act.result, act.err = pass.Analyzer.Run(pass)

View File

@ -1,6 +1,7 @@
package goanalysis
import (
"errors"
"fmt"
"go/ast"
"go/parser"
@ -11,7 +12,6 @@ import (
"sync"
"sync/atomic"
"github.com/pkg/errors"
"golang.org/x/tools/go/gcexportdata"
"golang.org/x/tools/go/packages"
@ -59,7 +59,7 @@ func (lp *loadingPackage) analyze(loadMode LoadMode, loadSem chan struct{}) {
defer lp.decUse(loadMode < LoadModeWholeProgram)
if err := lp.loadWithFacts(loadMode); err != nil {
werr := errors.Wrapf(err, "failed to load package %s", lp.pkg.Name)
werr := fmt.Errorf("failed to load package %s: %w", lp.pkg.Name, err)
// Don't need to write error to errCh, it will be extracted and reported on another layer.
// Unblock depending on actions and propagate error.
for _, act := range lp.actions {
@ -290,7 +290,7 @@ func (lp *loadingPackage) loadImportedPackageWithFacts(loadMode LoadMode) error
Msg: fmt.Sprintf("could not load export data: %s", err),
Kind: packages.ParseError,
})
return errors.Wrap(err, "could not load export data")
return fmt.Errorf("could not load export data: %w", err)
}
}

View File

@ -1,6 +1,7 @@
package golinters
import (
"errors"
"fmt"
"go/ast"
"go/types"
@ -13,7 +14,6 @@ import (
"github.com/go-critic/go-critic/checkers"
gocriticlinter "github.com/go-critic/go-critic/framework/linter"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/config"
@ -425,7 +425,7 @@ func (s *goCriticSettingsWrapper) validate() error {
}
} else {
if err := validateStringsUniq(s.EnabledTags); err != nil {
return errors.Wrap(err, "validate enabled tags")
return fmt.Errorf("validate enabled tags: %w", err)
}
tagToCheckers := s.buildTagToCheckersMap()
@ -447,15 +447,15 @@ func (s *goCriticSettingsWrapper) validate() error {
}
if err := validateStringsUniq(s.EnabledChecks); err != nil {
return errors.Wrap(err, "validate enabled checks")
return fmt.Errorf("validate enabled checks: %w", err)
}
if err := validateStringsUniq(s.DisabledChecks); err != nil {
return errors.Wrap(err, "validate disabled checks")
return fmt.Errorf("validate disabled checks: %w", err)
}
if err := s.validateCheckerNames(); err != nil {
return errors.Wrap(err, "validation failed")
return fmt.Errorf("validation failed: %w", err)
}
return nil

View File

@ -1,10 +1,10 @@
package golinters
import (
"fmt"
"sync"
gofmtAPI "github.com/golangci/gofmt/gofmt"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/config"
@ -73,7 +73,7 @@ func runGofmt(lintCtx *linter.Context, pass *analysis.Pass, settings *config.GoF
is, err := extractIssuesFromPatch(string(diff), lintCtx, gofmtName)
if err != nil {
return nil, errors.Wrapf(err, "can't extract issues from gofmt diff output %q", string(diff))
return nil, fmt.Errorf("can't extract issues from gofmt diff output %q: %w", string(diff), err)
}
for i := range is {

View File

@ -6,7 +6,6 @@ import (
"go/token"
"strings"
"github.com/pkg/errors"
diffpkg "github.com/sourcegraph/go-diff/diff"
"github.com/golangci/golangci-lint/pkg/config"
@ -238,7 +237,7 @@ func getErrorTextForLinter(settings *config.LintersSettings, linterName string)
func extractIssuesFromPatch(patch string, lintCtx *linter.Context, linterName string) ([]result.Issue, error) {
diffs, err := diffpkg.ParseMultiFileDiff([]byte(patch))
if err != nil {
return nil, errors.Wrap(err, "can't parse patch")
return nil, fmt.Errorf("can't parse patch: %w", err)
}
if len(diffs) == 0 {

View File

@ -7,7 +7,6 @@ import (
"os"
"sync"
"github.com/pkg/errors"
"github.com/shazow/go-diff/difflib"
"golang.org/x/tools/go/analysis"
"mvdan.cc/gofumpt/format"
@ -103,7 +102,7 @@ func runGofumpt(lintCtx *linter.Context, pass *analysis.Pass, diff differ, optio
diff := out.String()
is, err := extractIssuesFromPatch(diff, lintCtx, gofumptName)
if err != nil {
return nil, errors.Wrapf(err, "can't extract issues from gofumpt diff output %q", diff)
return nil, fmt.Errorf("can't extract issues from gofumpt diff output %q: %w", diff, err)
}
for i := range is {

View File

@ -1,10 +1,10 @@
package golinters
import (
"fmt"
"sync"
goimportsAPI "github.com/golangci/gofmt/goimports"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/imports"
@ -71,7 +71,7 @@ func runGoImports(lintCtx *linter.Context, pass *analysis.Pass) ([]goanalysis.Is
is, err := extractIssuesFromPatch(string(diff), lintCtx, goimportsName)
if err != nil {
return nil, errors.Wrapf(err, "can't extract issues from gofmt diff output %q", string(diff))
return nil, fmt.Errorf("can't extract issues from gofmt diff output %q: %w", string(diff), err)
}
for i := range is {

View File

@ -9,7 +9,6 @@ import (
"strings"
"sync"
"github.com/pkg/errors"
"github.com/securego/gosec/v2"
"github.com/securego/gosec/v2/rules"
"golang.org/x/tools/go/analysis"
@ -167,7 +166,7 @@ func convertToScore(str string) (gosec.Score, error) {
case "high":
return gosec.High, nil
default:
return gosec.Low, errors.Errorf("'%s' is invalid, use low instead. Valid options: low, medium, high", str)
return gosec.Low, fmt.Errorf("'%s' is invalid, use low instead. Valid options: low, medium, high", str)
}
}

View File

@ -1,10 +1,10 @@
package golinters
import (
"fmt"
"sync"
"github.com/ashanbrown/makezero/makezero"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/config"
@ -59,7 +59,7 @@ func runMakeZero(pass *analysis.Pass, settings *config.MakezeroSettings) ([]goan
for _, file := range pass.Files {
hints, err := zero.Run(pass.Fset, pass.TypesInfo, file)
if err != nil {
return nil, errors.Wrapf(err, "makezero linter failed on file %q", file.Name.String())
return nil, fmt.Errorf("makezero linter failed on file %q: %w", file.Name.String(), err)
}
for _, hint := range hints {

View File

@ -13,7 +13,6 @@ import (
reviveConfig "github.com/mgechev/revive/config"
"github.com/mgechev/revive/lint"
"github.com/mgechev/revive/rule"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"
"github.com/golangci/golangci-lint/pkg/config"
@ -171,13 +170,13 @@ func getReviveConfig(cfg *config.ReviveSettings) (*lint.Config, error) {
err := toml.NewEncoder(buf).Encode(rawRoot)
if err != nil {
return nil, errors.Wrap(err, "failed to encode configuration")
return nil, fmt.Errorf("failed to encode configuration: %w", err)
}
conf = &lint.Config{}
_, err = toml.NewDecoder(buf).Decode(conf)
if err != nil {
return nil, errors.Wrap(err, "failed to decode configuration")
return nil, fmt.Errorf("failed to decode configuration: %w", err)
}
}

View File

@ -1,10 +1,10 @@
package golinters
import (
"fmt"
"go/token"
"sync"
"github.com/pkg/errors"
"github.com/ultraware/whitespace"
"golang.org/x/tools/go/analysis"
@ -87,7 +87,7 @@ func runWhitespace(lintCtx *linter.Context, pass *analysis.Pass, wsSettings whit
bracketLine, err := lintCtx.LineCache.GetLine(issue.Pos.Filename, issue.Pos.Line)
if err != nil {
return nil, errors.Wrapf(err, "failed to get line %s:%d", issue.Pos.Filename, issue.Pos.Line)
return nil, fmt.Errorf("failed to get line %s:%d: %w", issue.Pos.Filename, issue.Pos.Line, err)
}
switch i.Type {

View File

@ -3,13 +3,12 @@ package goutil
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/pkg/errors"
"github.com/golangci/golangci-lint/pkg/logutils"
)
@ -40,11 +39,11 @@ func (e *Env) Discover(ctx context.Context) error {
args = append(args, string(EnvGoCache), string(EnvGoRoot))
out, err := exec.CommandContext(ctx, "go", args...).Output()
if err != nil {
return errors.Wrap(err, "failed to run 'go env'")
return fmt.Errorf("failed to run 'go env': %w", err)
}
if err = json.Unmarshal(out, &e.vars); err != nil {
return errors.Wrapf(err, "failed to parse 'go %s' json", strings.Join(args, " "))
return fmt.Errorf("failed to parse 'go %s' json: %w", strings.Join(args, " "), err)
}
e.debugf("Read go env for %s: %#v", time.Since(startedAt), e.vars)

View File

@ -11,7 +11,6 @@ import (
"strings"
"time"
"github.com/pkg/errors"
"golang.org/x/tools/go/packages"
"github.com/golangci/golangci-lint/internal/pkgcache"
@ -172,11 +171,11 @@ func (cl *ContextLoader) parseLoadedPackagesErrors(pkgs []*packages.Package) err
errs = append(errs, err)
if strings.Contains(err.Msg, "no Go files") {
return errors.Wrapf(exitcodes.ErrNoGoFiles, "package %s", pkg.PkgPath)
return fmt.Errorf("package %s: %w", pkg.PkgPath, exitcodes.ErrNoGoFiles)
}
if strings.Contains(err.Msg, "cannot find package") {
// when analyzing not existing directory
return errors.Wrap(exitcodes.ErrFailure, err.Msg)
return fmt.Errorf("%v: %w", err.Msg, exitcodes.ErrFailure)
}
}
@ -195,7 +194,7 @@ func (cl *ContextLoader) loadPackages(ctx context.Context, loadMode packages.Loa
buildFlags, err := cl.makeBuildFlags()
if err != nil {
return nil, errors.Wrap(err, "failed to make build flags for go list")
return nil, fmt.Errorf("failed to make build flags for go list: %w", err)
}
conf := &packages.Config{
@ -211,14 +210,14 @@ func (cl *ContextLoader) loadPackages(ctx context.Context, loadMode packages.Loa
cl.debugf("Built loader args are %s", args)
pkgs, err := packages.Load(conf, args...)
if err != nil {
return nil, errors.Wrap(err, "failed to load with go/packages")
return nil, fmt.Errorf("failed to load with go/packages: %w", err)
}
// Currently, go/packages doesn't guarantee that error will be returned
// if context was canceled. See
// https://github.com/golang/tools/commit/c5cec6710e927457c3c29d6c156415e8539a5111#r39261855
if ctx.Err() != nil {
return nil, errors.Wrap(ctx.Err(), "timed out to load packages")
return nil, fmt.Errorf("timed out to load packages: %w", ctx.Err())
}
if loadMode&packages.NeedSyntax == 0 {
@ -299,7 +298,7 @@ func (cl *ContextLoader) Load(ctx context.Context, linters []*linter.Config) (*l
loadMode := cl.findLoadMode(linters)
pkgs, err := cl.loadPackages(ctx, loadMode)
if err != nil {
return nil, errors.Wrap(err, "failed to load packages")
return nil, fmt.Errorf("failed to load packages: %w", err)
}
deduplicatedPkgs := cl.filterDuplicatePackages(pkgs)

View File

@ -7,7 +7,6 @@ import (
"strings"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
gopackages "golang.org/x/tools/go/packages"
"github.com/golangci/golangci-lint/internal/errorutil"
@ -46,7 +45,7 @@ func NewRunner(cfg *config.Config, log logutils.Log, goenv *goutil.Env, es *lint
enabledLinters, err := es.GetEnabledLintersMap()
if err != nil {
return nil, errors.Wrap(err, "failed to get enabled linters")
return nil, fmt.Errorf("failed to get enabled linters: %w", err)
}
// print deprecated messages

View File

@ -1,12 +1,11 @@
package packages
import (
"errors"
"fmt"
"go/token"
"strconv"
"strings"
"github.com/pkg/errors"
)
func ParseErrorPosition(pos string) (*token.Position, error) {
@ -26,7 +25,7 @@ func ParseErrorPosition(pos string) (*token.Position, error) {
if len(parts) == 3 { // no column
column, err = strconv.Atoi(parts[2])
if err != nil {
return nil, errors.Wrapf(err, "failed to parse column from %q", parts[2])
return nil, fmt.Errorf("failed to parse column from %q: %w", parts[2], err)
}
}

View File

@ -1,13 +1,13 @@
package processors
import (
"errors"
"fmt"
"go/parser"
"go/token"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/golangci/golangci-lint/pkg/logutils"
"github.com/golangci/golangci-lint/pkg/result"
)
@ -107,7 +107,7 @@ func (p *AutogeneratedExclude) getOrCreateFileSummary(i *result.Issue) (*ageFile
doc, err := getDoc(i.FilePath())
if err != nil {
return nil, errors.Wrapf(err, "failed to get doc of file %s", i.FilePath())
return nil, fmt.Errorf("failed to get doc of file %s: %w", i.FilePath(), err)
}
fs.isGenerated = isGeneratedFileByComment(doc)
@ -119,7 +119,7 @@ func getDoc(filePath string) (string, error) {
fset := token.NewFileSet()
syntax, err := parser.ParseFile(fset, filePath, nil, parser.PackageClauseOnly|parser.ParseComments)
if err != nil {
return "", errors.Wrap(err, "failed to parse file")
return "", fmt.Errorf("failed to parse file: %w", err)
}
var docLines []string

View File

@ -1,11 +1,10 @@
package processors
import (
"fmt"
"path/filepath"
"strings"
"github.com/pkg/errors"
"github.com/golangci/golangci-lint/pkg/goutil"
"github.com/golangci/golangci-lint/pkg/result"
)
@ -37,7 +36,7 @@ func (p Cgo) Process(issues []result.Issue) ([]result.Issue, error) {
if !filepath.IsAbs(i.FilePath()) {
absPath, err := filepath.Abs(i.FilePath())
if err != nil {
return false, errors.Wrapf(err, "failed to build abs path for %q", i.FilePath())
return false, fmt.Errorf("failed to build abs path for %q: %w", i.FilePath(), err)
}
issueFilePath = absPath
}

View File

@ -8,8 +8,6 @@ import (
"sort"
"strings"
"github.com/pkg/errors"
"github.com/golangci/golangci-lint/internal/robustio"
"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/fsutils"
@ -77,14 +75,14 @@ func (f Fixer) fixIssuesInFile(filePath string, issues []result.Issue) error {
// can't just use bufio.scanner: it has a line length limit
origFileData, err := f.fileCache.GetFileBytes(filePath)
if err != nil {
return errors.Wrapf(err, "failed to get file bytes for %s", filePath)
return fmt.Errorf("failed to get file bytes for %s: %w", filePath, err)
}
origFileLines := bytes.Split(origFileData, []byte("\n"))
tmpFileName := filepath.Join(filepath.Dir(filePath), fmt.Sprintf(".%s.golangci_fix", filepath.Base(filePath)))
tmpOutFile, err := os.Create(tmpFileName)
if err != nil {
return errors.Wrapf(err, "failed to make file %s", tmpFileName)
return fmt.Errorf("failed to make file %s: %w", tmpFileName, err)
}
// merge multiple issues per line into one issue
@ -112,7 +110,7 @@ func (f Fixer) fixIssuesInFile(filePath string, issues []result.Issue) error {
tmpOutFile.Close()
if err = robustio.Rename(tmpOutFile.Name(), filePath); err != nil {
_ = robustio.RemoveAll(tmpOutFile.Name())
return errors.Wrapf(err, "failed to rename %s -> %s", tmpOutFile.Name(), filePath)
return fmt.Errorf("failed to rename %s -> %s: %w", tmpOutFile.Name(), filePath, err)
}
return nil
@ -241,7 +239,7 @@ func (f Fixer) writeFixedFile(origFileLines [][]byte, issues []result.Issue, tmp
outLine += "\n"
}
if _, err := tmpOutFile.WriteString(outLine); err != nil {
return errors.Wrap(err, "failed to write output line")
return fmt.Errorf("failed to write output line: %w", err)
}
}

View File

@ -1,7 +1,7 @@
package processors
import (
"github.com/pkg/errors"
"fmt"
"github.com/golangci/golangci-lint/pkg/result"
)
@ -22,7 +22,7 @@ func filterIssuesErr(issues []result.Issue, filter func(i *result.Issue) (bool,
for i := range issues {
ok, err := filter(&issues[i])
if err != nil {
return nil, errors.Wrapf(err, "can't filter issue %#v", issues[i])
return nil, fmt.Errorf("can't filter issue %#v: %w", issues[i], err)
}
if ok {

View File

@ -1,12 +1,11 @@
package processors
import (
"fmt"
"path/filepath"
"regexp"
"strings"
"github.com/pkg/errors"
"github.com/golangci/golangci-lint/pkg/fsutils"
"github.com/golangci/golangci-lint/pkg/logutils"
"github.com/golangci/golangci-lint/pkg/result"
@ -35,7 +34,7 @@ func NewSkipDirs(patterns []string, log logutils.Log, runArgs []string) (*SkipDi
p = fsutils.NormalizePathInRegex(p)
patternRe, err := regexp.Compile(p)
if err != nil {
return nil, errors.Wrapf(err, "can't compile regexp %q", p)
return nil, fmt.Errorf("can't compile regexp %q: %w", p, err)
}
patternsRe = append(patternsRe, patternRe)
}
@ -52,7 +51,7 @@ func NewSkipDirs(patterns []string, log logutils.Log, runArgs []string) (*SkipDi
absArg, err := filepath.Abs(arg)
if err != nil {
return nil, errors.Wrapf(err, "failed to abs-ify arg %q", arg)
return nil, fmt.Errorf("failed to abs-ify arg %q: %w", arg, err)
}
absArgsDirs = append(absArgsDirs, absArg)
}