Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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?

like image 726
Martin Tournoij Avatar asked Dec 06 '16 12:12

Martin Tournoij


People also ask

How do I use GO imports?

goimports If your project does not have goimports, click the go get goimports link in the Goimports file notification window. Otherwise, open the Terminal tool window (View | Tool Windows | Terminal), and type the following command to install goimports: go get golang.org/x/tools/cmd/goimports . Press Enter .


2 Answers

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.

like image 88
John S Perayil Avatar answered Oct 09 '22 18:10

John S Perayil


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.

like image 26
StevieB Avatar answered Oct 09 '22 17:10

StevieB