英文:
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 '"\./' --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 '{{ join .Imports "\n" }}'
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 '{{ join .Imports "\n" }}' ./... | grep '^_'
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 '{{ join .TestImports "\n" }}' ./... | grep '\./'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论