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. eg 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?
Support for this is included in the go
tool itself. From question: 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, eg
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.