Member-only story

A Quick and Scrappy Bazel Autocomplete

Matt Kornfield
3 min readMar 20, 2023

A simple autocomplete to find available bazel commands.

Photo by Lavi Perchik on Unsplash

tl;dr, Give it a spin: throw this in your ~/.bash_profile or whatever prompt you use, and hit tab after typing bazel inside your bazel project to get the autocomplete going (first time will be a bit slow loading the targets). You’ll want to rm /tmp/bazelq.txt if you edit the set of bazel targets.

_bazel_complete() {
cur="${COMP_WORDS[COMP_CWORD]}"
_get_comp_words_by_ref -n : cur
if [[ ! -f /tmp/bazelq.txt ]]; then
bazel query //... | grep "//" >/tmp/bazelq.txt
fi
if [[ ${#COMP_WORDS[@]} < 3 ]]; then
COMPREPLY=($(compgen -W "build query run test" "$cur"))
elif [[ ${#COMP_WORDS[@]} < 6 ]]; then
contents_without_colon=$(cat /tmp/bazelq.txt | cut -d: -f1 )
for i in {3..5}; do
contents=$(echo "$contents_without_colon" | cut -d/ -f1-${i} | uniq)
possible_compreply=($(compgen -W "$contents" "$cur"))
if [[ ${#possible_compreply[@]} > 1 ]]; then
break
fi
done
if [[ ${#possible_compreply[@]} == 1 || ${#possible_compreply[@]} == 0 ]]; then
contents=$(cat /tmp/bazelq.txt)
possible_compreply=($(compgen -W "$contents" "$cur"))
fi
COMPREPLY+=(${possible_compreply[@]})
fi
__ltrim_colon_completions "$cur"
}
complete -F _bazel_complete bazel

Longer Explanation

--

--

Matt Kornfield
Matt Kornfield

Written by Matt Kornfield

Today's solutions are tomorrow's debugging adventure.

No responses yet