如何在我的 Go 源代码中找到相对导入?

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

How do I find relative imports in my Go source?

问题

我正在尝试在我的项目中使用dep,当我尝试添加一个依赖时:

dep ensure -add github.com/foo/bar

我遇到了很多类似的错误:

ensure Solve(): No versions of github.com/foo/bar met constraints:
    v1.2.3: Could not introduce github.com/foo/bar@v1.2.3, as its subpackage github.com/foo/bar 
    does not contain usable Go code (*build.NoGoError).. (Package is required by (root).)

显然,这类问题通常是由于项目中的相对导入引起的。

在一个大型项目中,如何定位相对导入,同时还有供应商依赖?是否有任何现有的Go工具可以帮助我解决这个问题?

我目前的解决方案是通过grep -rn '"\./' --include=*.go .的输出进行遍历,但这个过程很慢。

英文:

I'm trying to use dep in my project and when I attempt to add a dependency:

<!-- language-all: none -->

dep ensure -add github.com/foo/bar

I get lots of errors similar to:

ensure Solve(): No versions of github.com/foo/bar met constraints:
v1.2.3: Could not introduce github.com/foo/bar@v1.2.3, as its subpackage github.com/foo/bar 
does not contain usable Go code (*build.NoGoError).. (Package is required by (root).)

Apparently such problems are generally caused by a relative import within the project in question.

How can I locate the relative imports in a large project, with vendored dependencies? Could any existing Go tools help me here?

My current solution is to crawl through the output of grep -rn &#39;&quot;\./&#39; --include=\*.go ., but that's slow going.

答案1

得分: 1

你可以使用go list命令来查找所有导入的包。

go list -f '{{ join .Imports "\n" }}'

在内部,相对导入会转换为绝对路径,并以_为前缀,因此这应该显示任何包中的相对导入。

go list -f '{{ join .Imports "\n" }}' ./... | grep '^_'

由于相对导入必须在GOPATH中,所以相对于名称引用的包不起作用。这可能是一个你没有使用的包,或者是在_test.go文件中隐式运行的包目录内的内容。但是,你可以单独检查测试导入,尽管它们会被展开,但它们不会被清理和加上_前缀。

go list -f '{{ join .TestImports "\n" }}' ./... | grep '\./'
英文:

You can use the go list command to find all imported packages.

go list -f &#39;{{ join .Imports &quot;\n&quot; }}&#39;

Internally, relative imports are converted to an absolute path, and prefixed with _, so this should show any relative imports in any of your packages.

go list -f &#39;{{ join .Imports &quot;\n&quot; }}&#39; ./... | grep &#39;^_&#39;

Relative imports don't work with packages referenced by name, since those must be in the GOPATH anyways. It's likely a package you're not using, or something in _test.go files meant to be run implicitly from within the package directory. You can check the test imports separately, however while they are expanded, they are not cleaned and prefixed with _.

go list -f &#39;{{ join .TestImports &quot;\n&quot; }}&#39; ./... | grep &#39;\./&#39;

huangapple
  • 本文由 发表于 2017年9月8日 18:39:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/46114587.html
匿名

发表评论

匿名网友

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

确定