Rules_go: question: How to query for unused go_repository?

Created on 1 Dec 2018  路  3Comments  路  Source: bazelbuild/rules_go

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 //...?

question

Most helpful comment

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

All 3 comments

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:

  • Make a list of go_repository rules by parsing WORKSPACE. I imagine a small awk script would be the simplest way to do this.
  • Run bazel query 'deps(//...)' and grep for anything that looks like a repository name. Pipe to sort and uniq.
  • Remove 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
Was this page helpful?
0 / 5 - 0 ratings