3

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?

Jason Xu
  • 2,903
  • 5
  • 31
  • 54

1 Answers1

1

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, 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

Community
  • 1
  • 1
icza
  • 389,944
  • 63
  • 907
  • 827
  • thanks for the answer @icza, however it's about finding who depends on a given pkg, not the pkg depending on who. not sure if you have such answers? – Jason Xu Jan 20 '16 at 07:38
  • @JasonXu Please read the whole answer. What you're looking for is in the output of the given commands. – icza Jan 20 '16 at 07:39
  • it works for me, as tested I can run "go list -f "{{.ImportPath}} {{.Imports}}" ./... |grep my_pkg_path " in my root project folder to get what I want. thanks. – Jason Xu Jan 20 '16 at 07:48