I'm wondering if it's possible to use bazel's query language to identify unused go_repositorys.
The use case or likely scenario is that a transitive dependency is added to the WORKSPACE as a requirement for some third party library. At a later date, the third party library is updated where the transitive dependency is no longer used by any target in //....
How can we easily find unused go_repository by any path under //...?
There's not an automatic way to do that at the moment. bazelbuild/bazel-gazelle#213 is a feature request for gazelle update-repos to remove go_repository rules that aren't referenced.
Probably the simplest thing to do right now:
go_repository rules by parsing WORKSPACE. I imagine a small awk script would be the simplest way to do this.bazel query 'deps(//...)' and grep for anything that looks like a repository name. Pipe to sort and uniq.go_repository rules that don't appear in the above list.Thanks! That answers my question. I'll follow bazelbuild/bazel-gazelle#213.
If I write any command in the meantime, I'll add it here.
Here's a very crude start to this solution
# Get the unique dep names in WORKSPACE
awk '/^go_repository/ {gsub("\"",""); gsub(",",""); print}' FS="\n" RS="" WORKSPACE | \
awk '/name/ {print $3}' | \
sort | uniq > /tmp/workspace.deps
# Get the deps in use
bazel query 'kind(go_library, deps(//...)) -//...' |
awk '{split($0, part, "//");gsub("@","", part[1]); print part[1]}' | \
sort | uniq > /tmp/in-use.deps
# Find go_repositories to delete
grep -f /tmp/in-use.deps -v /tmp/workspace.deps
Most helpful comment
Here's a very crude start to this solution