Martin Tournoij
Martin Tournoij

Reputation: 27842

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?

Upvotes: 6

Views: 1891

Answers (2)

John S Perayil
John S Perayil

Reputation: 6345

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.

Upvotes: 4

StevieB
StevieB

Reputation: 1000

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.

Upvotes: 1

Related Questions