英文:
who's using my Go package
问题
在Go语言中,有一种方法/工具可以列出哪些包(本地工作空间)引用了给定的包吗?
英文:
My scenario is we have many small projects in development, and some of them have dependency on each other. and we are trying to provide some automated tests based on dependency relationship. e.g. when a package is changed, make sure all depending packages pass their own unit-test.
So the question is, in Go, is there a way/tool to list which packages (local work space) are referring to a given package?
答案1
得分: 1
这个功能已经包含在go
工具本身中。从问题中得知:https://stackoverflow.com/questions/28166249/how-to-list-installed-go-packages
你可以使用以下命令来列出包及其依赖项(一个包导入的其他包):
go list -f "{{.ImportPath}} {{.Imports}}" ./...
在你的Go工作区的src
文件夹中执行该命令。或者使用以下命令来递归地列出包及其依赖项:
go list -f "{{.ImportPath}} {{.Deps}}" ./...
是的,这不是你想要的方向,因为你想要导入特定包的包。但你可以在上述命令的输出中轻松搜索你的包名。列出你的包作为依赖项的行就是你要找的行;这些行的第一个“token”将是导入你的包的包(带有到工作区src
文件夹的路径)。
在Unix系统中,你可以使用|grep
来过滤这些行,例如:
go list -f "{{.ImportPath}} {{.Imports}}" ./... |grep yourpackage
(这也会列出包含你的包及其依赖项的行。)
示例:
假设你有两个包:my/pack1
和my/pack2
,其中my/pack1
不导入任何包,而my/pack2
导入了fmt
和my/pack1
。上述命令的输出将包括:
path/to/workspace/src/my/pack1
path/to/workspace/src/my/pack2 [fmt my/pack1]
你要找的是导入my/pack1
的包:你可以看到my/pack2
导入了它,因为my/pack1
被列为my/pack2
的依赖项。
还有一个开源项目可以实现这个功能:https://github.com/cespare/deplist
英文:
Support for this is included in the go
tool itself. From question: https://stackoverflow.com/questions/28166249/how-to-list-installed-go-packages
You can use
go list -f "{{.ImportPath}} {{.Imports}}" ./...
to list packages and their dependencies (packages that a package imports). Execute it in the src
folder of your Go workspace. Or
go list -f "{{.ImportPath}} {{.Deps}}" ./...
Which lists packages and their dependencies recursively.
Yes, this is not the direction you want because you want packages that import a specific package. But you can easily search in the output of the above commands for your package name. Lines where your package is listed as a dependency are the ones you are looking for; the first "token" of these lines will be the packages (with path to workspace src
folder) that import your package.
On Unix systems you can use |grep
to filter for these lines, e.g.
go list -f "{{.ImportPath}} {{.Imports}}" ./... |grep yourpackage
(This will also list a line containing your package and its dependencies.)
Example:
Let's say you have 2 packages: my/pack1
and my/pack2
, where my/pack1
imports nothing, and my/pack2
imports fmt
and my/pack1
, the output of the above commands will include:
path/to/workspace/src/my/pack1
path/to/workspace/src/my/pack2 [fmt my/pack1]
And you are looking for packages that import my/pack1
: you can see my/pack2
imports it because my/pack1
is listed as a dependency for my/pack2
There is also an open-source project doing just this: https://github.com/cespare/deplist
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论