英文:
How can I tell goimports to prefer one package over another?
问题
这个文件:
package foo
func errorer() error {
return errors.New("Whoops")
}
将会通过 goimports
转换成这样:
package foo
import "errors"
func errorer() error {
return errors.New("Whoops")
}
然而,我想在这个项目的任何地方都使用 github.com/pkg/errors
包,而不是 errors
包。
我可以告诉 goimports
总是优先选择 github.com/pkg/errors
包吗?
英文:
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?
答案1
得分: 4
使用.goimportsignore
在您的情况下不起作用,因为您想要忽略的包是标准库中的,而不是在GOPATH下。
-local
标志也不起作用,因为这两个包具有相同的名称,所以errors
仍然会被选择而不是pkg/errors
。
您的选择是使用golang.org/x/tools/imports
编写自己的goimports
版本。
或者另一种不方便的方法是确保您在新文件中首次调用error.Wrap
或其他函数,而不是errors.New
,这样goimports
可以识别pkg/errors
。
英文:
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
.
答案2
得分: 1
我还没有尝试过这个,但根据文档上的说明:
要排除在你的 $GOPATH 中的目录,以免被扫描到 Go 文件,goimports 遵循一个配置文件,该文件位于 $GOPATH/src/.goimportsignore,它可以包含空行、注释行(以 '#' 开头)或者相对于配置文件的目录名,用于在扫描时忽略这些目录。不允许使用通配符或正则表达式模式。使用 "-v" 详细标志来验证它是否起作用,并查看 goimports 的操作。
所以你可以尝试排除 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论