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

huangapple go评论77阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年12月6日 20:03:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/40994957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定