简体   繁体   中英

How can I tell goimports to prefer one package over another?

This file:

package foo

func errorer() error {
    return errors.New("Whoops")
}

Will be transformed to this with goimports :

package foo

import "errors"

func errorer() error {
    return errors.New("Whoops")
}

However, I'd like to use the github.com/pkg/errors package everywhere in this project, and not the errors package.

Can I tell goimports to always prefer the github.com/pkg/errors package?

Using .goimportsignore would not work in your case as the package you want to ignore is in the standard lib and not under GOPATH.

The -local flag would also not work because both the packages have the same name so errors will still be chosen over pkg/errors .

Your options are to write your own version of goimports using the golang.org/x/tools/imports

Or another inconvenient way is to make sure you call error.Wrap or one of the other functions the first time in a new file, rather than errors.New so that goimports can identify pkg/errors .

I haven't tried this but according to the docs at: https://github.com/golang/tools/blob/master/cmd/goimports/doc.go

To exclude directories in your $GOPATH from being scanned for Go files, goimports respects a configuration file at $GOPATH/src/.goimportsignore which may contain blank lines, comment lines (beginning with '#'), or lines naming a directory relative to the configuration file to ignore when scanning. No globbing or regex patterns are allowed. Use the "-v" verbose flag to verify it's working and see what goimports is doing.

So you could try excluding the errors directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM