blob: 2f182f02898520362bc264a99adcf54067fafca6 [file] [log] [blame]
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +00001# -*- sh -*- (Bash only)
2#
Damien Martin-Guillerezf88f4d82015-09-25 13:56:55 +00003# Copyright 2015 The Bazel Authors. All rights reserved.
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +00004#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
nharmata1694de62018-11-12 09:22:23 -080016
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +000017# The template is expanded at build time using tables of commands/options
18# derived from the bazel executable built in the same client; the expansion is
19# written to bazel-complete.bash.
20#
nharmata1694de62018-11-12 09:22:23 -080021# Don't use this script directly. Generate the final script with
22# bazel build //scripts:bash_completion instead.
23
24# This script expects a header to be prepended to it that defines the following
25# nullary functions:
26#
27# _bazel_completion_use_query - Has a successful exit code if
28# BAZEL_COMPLETION_USE_QUERY is "true".
29#
30# _bazel_completion_allow_tests_for_run - Has a successful exit code if
31# BAZEL_COMPLETION_ALLOW_TESTS_FOR_RUN is "true".
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +000032
33# The package path used by the completion routines. Unfortunately
34# this isn't necessarily the same as the actual package path used by
35# Bazel, but that's ok. (It's impossible for us to reliably know what
36# the relevant package-path, so this is just a good guess. Users can
37# override it if they want.)
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +000038: ${BAZEL_COMPLETION_PACKAGE_PATH:=%workspace%}
39
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +000040# Some commands might interfer with the important one, so don't complete them
41: ${BAZEL_IGNORED_COMMAND_REGEX:="__none__"}
42
Martin Probstf84650c2017-11-29 02:09:42 -080043# bazel & ibazel commands
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +000044: ${BAZEL:=bazel}
Martin Probstf84650c2017-11-29 02:09:42 -080045: ${IBAZEL:=ibazel}
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +000046
47# Pattern to match for looking for a target
48# BAZEL_BUILD_MATCH_PATTERN__* give the pattern for label-*
Benjamin Petersondac096c2019-03-22 10:29:40 -070049# when looking in the build file.
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +000050# BAZEL_QUERY_MATCH_PATTERN__* give the pattern for label-*
51# when using 'bazel query'.
nharmata1694de62018-11-12 09:22:23 -080052# _RUNTEST is a special case for _bazel_completion_allow_tests_for_run.
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +000053: ${BAZEL_BUILD_MATCH_PATTERN__test:='(.*_test|test_suite)'}
54: ${BAZEL_QUERY_MATCH_PATTERN__test:='(test|test_suite)'}
55: ${BAZEL_BUILD_MATCH_PATTERN__bin:='.*_binary'}
56: ${BAZEL_QUERY_MATCH_PATTERN__bin:='(binary)'}
57: ${BAZEL_BUILD_MATCH_PATTERN_RUNTEST__bin:='(.*_(binary|test)|test_suite)'}
58: ${BAZEL_QUERY_MATCH_PATTERN_RUNTEST__bin:='(binary|test)'}
59: ${BAZEL_BUILD_MATCH_PATTERN__:='.*'}
60: ${BAZEL_QUERY_MATCH_PATTERN__:=''}
61
62# Usage: _bazel__get_rule_match_pattern <command>
63# Determine what kind of rules to match, based on command.
64_bazel__get_rule_match_pattern() {
65 local var_name pattern
nharmata1694de62018-11-12 09:22:23 -080066 if _bazel_completion_use_query; then
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +000067 var_name="BAZEL_QUERY_MATCH_PATTERN"
68 else
69 var_name="BAZEL_BUILD_MATCH_PATTERN"
70 fi
71 if [[ "$1" =~ ^label-?([a-z]*)$ ]]; then
72 pattern=${BASH_REMATCH[1]:-}
nharmata1694de62018-11-12 09:22:23 -080073 if _bazel_completion_allow_tests_for_run; then
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +000074 eval "echo \"\${${var_name}_RUNTEST__${pattern}:-\$${var_name}__${pattern}}\""
75 else
76 eval "echo \"\$${var_name}__${pattern}\""
77 fi
78 fi
79}
80
81# Compute workspace directory. Search for the innermost
82# enclosing directory with a WORKSPACE file.
83_bazel__get_workspace_path() {
84 local workspace=$PWD
85 while true; do
86 if [ -f "${workspace}/WORKSPACE" ]; then
87 break
88 elif [ -z "$workspace" -o "$workspace" = "/" ]; then
89 workspace=$PWD
90 break;
91 fi
92 workspace=${workspace%/*}
93 done
94 echo $workspace
95}
96
97
98# Find the current piece of the line to complete, but only do word breaks at
99# certain characters. In particular, ignore these: "':=
100# This method also takes into account the current cursor position.
101#
102# Works with both bash 3 and 4! Bash 3 and 4 perform different word breaks when
103# computing the COMP_WORDS array. We need this here because Bazel options are of
104# the form --a=b, and labels of the form //some/label:target.
105_bazel__get_cword() {
106 local cur=${COMP_LINE:0:$COMP_POINT}
107 # This expression finds the last word break character, as defined in the
108 # COMP_WORDBREAKS variable, but without '=' or ':', which is not preceeded by
109 # a slash. Quote characters are also excluded.
110 local wordbreaks="$COMP_WORDBREAKS"
111 wordbreaks="${wordbreaks//\'/}"
112 wordbreaks="${wordbreaks//\"/}"
113 wordbreaks="${wordbreaks//:/}"
114 wordbreaks="${wordbreaks//=/}"
115 local word_start=$(expr "$cur" : '.*[^\]['"${wordbreaks}"']')
116 echo "${cur:$word_start}"
117}
118
119
120# Usage: _bazel__package_path <workspace> <displacement>
121#
122# Prints a list of package-path root directories, displaced using the
123# current displacement from the workspace. All elements have a
124# trailing slash.
125_bazel__package_path() {
126 local workspace=$1 displacement=$2 root
127 IFS=:
128 for root in ${BAZEL_COMPLETION_PACKAGE_PATH//\%workspace\%/$workspace}; do
129 unset IFS
130 echo "$root/$displacement"
131 done
132}
133
134# Usage: _bazel__options_for <command>
135#
136# Prints the set of options for a given Bazel command, e.g. "build".
137_bazel__options_for() {
138 local options
139 if [[ "${BAZEL_COMMAND_LIST}" =~ ^(.* )?$1( .*)?$ ]]; then
Philip Patsch27be7092018-08-28 02:30:51 -0700140 # assumes option names only use ASCII characters
141 local option_name=$(echo $1 | tr a-z A-Z | tr "-" "_")
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000142 eval "echo \${BAZEL_COMMAND_${option_name}_FLAGS}" | tr " " "\n"
143 fi
144}
145# Usage: _bazel__expansion_for <command>
146#
147# Prints the completion pattern for a given Bazel command, e.g. "build".
148_bazel__expansion_for() {
149 local options
150 if [[ "${BAZEL_COMMAND_LIST}" =~ ^(.* )?$1( .*)?$ ]]; then
Philip Patsch27be7092018-08-28 02:30:51 -0700151 # assumes option names only use ASCII characters
152 local option_name=$(echo $1 | tr a-z A-Z | tr "-" "_")
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000153 eval "echo \${BAZEL_COMMAND_${option_name}_ARGUMENT}"
154 fi
155}
156
157# Usage: _bazel__matching_targets <kind> <prefix>
158#
159# Prints target names of kind <kind> and starting with <prefix> in the BUILD
160# file given as standard input. <kind> is a basic regex (BRE) used to match the
161# bazel rule kind and <prefix> is the prefix of the target name.
162_bazel__matching_targets() {
163 local kind_pattern="$1"
164 local target_prefix="$2"
165 # The following commands do respectively:
166 # Remove BUILD file comments
167 # Replace \n by spaces to have the BUILD file in a single line
168 # Extract all rule types and target names
169 # Grep the kind pattern and the target prefix
170 # Returns the target name
171 sed 's/#.*$//' \
172 | tr "\n" " " \
173 | sed 's/\([a-zA-Z0-9_]*\) *(\([^)]* \)\{0,1\}name *= *['\''"]\([a-zA-Z0-9_/.+=,@~-]*\)['\''"][^)]*)/\
174type:\1 name:\3\
175/g' \
Googler86a40472016-09-06 18:01:11 +0000176 | "grep" -E "^type:$kind_pattern name:$target_prefix" \
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000177 | cut -d ':' -f 3
178}
179
180
181# Usage: _bazel__is_true <string>
182#
183# Returns true or false based on the input string. The following are
184# valid true values (the rest are false): "1", "true".
185_bazel__is_true() {
186 local str="$1"
187 [[ "$str" == "1" || "$str" == "true" ]]
188}
189
190# Usage: _bazel__expand_rules_in_package <workspace> <displacement>
191# <current> <label-type>
192#
193# Expands rules in specified packages, exploring all roots of
194# $BAZEL_COMPLETION_PACKAGE_PATH, not just $(pwd). Only rules
195# appropriate to the command are printed. Sets $COMPREPLY array to
196# result.
197#
nharmata1694de62018-11-12 09:22:23 -0800198# If _bazel_completion_use_query has a successful exit code, 'bazel query' is
199# used instead, with the actual Bazel package path;
200# $BAZEL_COMPLETION_PACKAGE_PATH is ignored in this case, since the actual Bazel
201# value is likely to be more accurate.
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000202_bazel__expand_rules_in_package() {
203 local workspace=$1 displacement=$2 current=$3 label_type=$4
204 local package_name=$(echo "$current" | cut -f1 -d:)
205 local rule_prefix=$(echo "$current" | cut -f2 -d:)
206 local root buildfile rule_pattern r result
207
208 result=
209 pattern=$(_bazel__get_rule_match_pattern "$label_type")
nharmata1694de62018-11-12 09:22:23 -0800210 if _bazel_completion_use_query; then
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000211 package_name=$(echo "$package_name" | tr -d "'\"") # remove quotes
212 result=$(${BAZEL} --output_base=/tmp/${BAZEL}-completion-$USER query \
Googler29765762019-03-06 01:41:43 -0800213 --keep_going --noshow_progress --output=label \
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000214 "kind('$pattern rule', '$package_name:*')" 2>/dev/null |
Googler86a40472016-09-06 18:01:11 +0000215 cut -f2 -d: | "grep" "^$rule_prefix")
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000216 else
217 for root in $(_bazel__package_path "$workspace" "$displacement"); do
Ian Cottrella7c54722017-08-24 11:20:43 +0200218 buildfile="$root/$package_name/BUILD.bazel"
219 if [ ! -f "$buildfile" ]; then
220 buildfile="$root/$package_name/BUILD"
221 fi
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000222 if [ -f "$buildfile" ]; then
223 result=$(_bazel__matching_targets \
224 "$pattern" "$rule_prefix" <"$buildfile")
225 break
226 fi
227 done
228 fi
229
230 index=$(echo $result | wc -w)
231 if [ -n "$result" ]; then
232 echo "$result" | tr " " "\n" | sed 's|$| |'
233 fi
234 # Include ":all" wildcard if there was no unique match. (The zero
235 # case is tricky: we need to include "all" in that case since
236 # otherwise we won't expand "a" to "all" in the absence of rules
237 # starting with "a".)
238 if [ $index -ne 1 ] && expr all : "\\($rule_prefix\\)" >/dev/null; then
239 echo "all "
240 fi
241}
242
243# Usage: _bazel__expand_package_name <workspace> <displacement> <current-word>
244# <label-type>
245#
246# Expands directories, but explores all roots of
247# BAZEL_COMPLETION_PACKAGE_PATH, not just $(pwd). When a directory is
248# a bazel package, the completion offers "pkg:" so you can expand
249# inside the package.
250# Sets $COMPREPLY array to result.
251_bazel__expand_package_name() {
252 local workspace=$1 displacement=$2 current=$3 type=${4:-} root dir index
253 for root in $(_bazel__package_path "$workspace" "$displacement"); do
254 found=0
255 for dir in $(compgen -d $root$current); do
256 [ -L "$dir" ] && continue # skip symlinks (e.g. bazel-bin)
257 [[ "$dir" =~ ^(.*/)?\.[^/]*$ ]] && continue # skip dotted dir (e.g. .git)
258 found=1
259 echo "${dir#$root}/"
Ian Cottrella7c54722017-08-24 11:20:43 +0200260 if [ -f $dir/BUILD.bazel -o -f $dir/BUILD ]; then
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000261 if [ "${type}" = "label-package" ]; then
262 echo "${dir#$root} "
263 else
264 echo "${dir#$root}:"
265 fi
266 fi
267 done
268 [ $found -gt 0 ] && break # Stop searching package path upon first match.
269 done
270}
271
272# Usage: _bazel__expand_target_pattern <workspace> <displacement>
273# <word> <label-syntax>
274#
275# Expands "word" to match target patterns, using the current workspace
276# and displacement from it. "command" is used to filter rules.
277# Sets $COMPREPLY array to result.
278_bazel__expand_target_pattern() {
279 local workspace=$1 displacement=$2 current=$3 label_syntax=$4
280 case "$current" in
281 //*:*) # Expand rule names within package, no displacement.
282 if [ "${label_syntax}" = "label-package" ]; then
283 compgen -S " " -W "BUILD" "$(echo current | cut -f ':' -d2)"
284 else
285 _bazel__expand_rules_in_package "$workspace" "" "$current" "$label_syntax"
286 fi
287 ;;
288 *:*) # Expand rule names within package, displaced.
289 if [ "${label_syntax}" = "label-package" ]; then
290 compgen -S " " -W "BUILD" "$(echo current | cut -f ':' -d2)"
291 else
292 _bazel__expand_rules_in_package \
293 "$workspace" "$displacement" "$current" "$label_syntax"
294 fi
295 ;;
296 //*) # Expand filenames using package-path, no displacement
297 _bazel__expand_package_name "$workspace" "" "$current" "$label_syntax"
298 ;;
299 *) # Expand filenames using package-path, displaced.
300 if [ -n "$current" ]; then
301 _bazel__expand_package_name "$workspace" "$displacement" "$current" "$label_syntax"
302 fi
303 ;;
304 esac
305}
306
307_bazel__get_command() {
308 for word in "${COMP_WORDS[@]:1:COMP_CWORD-1}"; do
Googler86a40472016-09-06 18:01:11 +0000309 if echo "$BAZEL_COMMAND_LIST" | "grep" -wsq -e "$word"; then
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000310 echo $word
311 break
312 fi
313 done
314}
315
316# Returns the displacement to the workspace given in $1
317_bazel__get_displacement() {
318 if [[ "$PWD" =~ ^$1/.*$ ]]; then
319 echo ${PWD##$1/}/
320 fi
321}
322
323
324# Usage: _bazel__complete_pattern <workspace> <displacement> <current>
325# <type>
326#
327# Expand a word according to a type. The currently supported types are:
328# - {a,b,c}: an enum that can take value a, b or c
329# - label: a label of any kind
330# - label-bin: a label to a runnable rule (basically to a _binary rule)
331# - label-test: a label to a test rule
332# - info-key: an info key as listed by `bazel help info-keys`
333# - command: the name of a command
334# - path: a file path
335# - combinaison of previous type using | as separator
336_bazel__complete_pattern() {
337 local workspace=$1 displacement=$2 current=$3 types=$4
338 for type in $(echo $types | tr "|" "\n"); do
339 case "$type" in
340 label*)
341 _bazel__expand_target_pattern "$workspace" "$displacement" \
342 "$current" "$type"
343 ;;
344 info-key)
345 compgen -S " " -W "${BAZEL_INFO_KEYS}" -- "$current"
346 ;;
347 "command")
348 local commands=$(echo "${BAZEL_COMMAND_LIST}" \
Googler86a40472016-09-06 18:01:11 +0000349 | tr " " "\n" | "grep" -v "^${BAZEL_IGNORED_COMMAND_REGEX}$")
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000350 compgen -S " " -W "${commands}" -- "$current"
351 ;;
352 path)
353 compgen -f -- "$current"
354 ;;
355 *)
356 compgen -S " " -W "$type" -- "$current"
357 ;;
358 esac
359 done
360}
361
362# Usage: _bazel__expand_options <workspace> <displacement> <current-word>
363# <options>
364#
365# Expands options, making sure that if current-word contains an equals sign,
366# it is handled appropriately.
367_bazel__expand_options() {
368 local workspace="$1" displacement="$2" cur="$3" options="$4"
369 if [[ $cur =~ = ]]; then
370 # also expands special labels
371 current=$(echo "$cur" | cut -f2 -d=)
372 _bazel__complete_pattern "$workspace" "$displacement" "$current" \
373 "$(compgen -W "$options" -- "$cur" | cut -f2 -d=)" \
374 | sort -u
375 else
376 compgen -W "$(echo "$options" | sed 's|=.*$|=|')" -- "$cur" \
377 | sed 's|\([^=]\)$|\1 |'
378 fi
379}
380
381
382_bazel__complete_stdout() {
383 local cur=$(_bazel__get_cword) word command displacement workspace
384
385 # Determine command: "" (startup-options) or one of $BAZEL_COMMAND_LIST.
386 command="$(_bazel__get_command)"
387
388 workspace="$(_bazel__get_workspace_path)"
389 displacement="$(_bazel__get_displacement ${workspace})"
390
391 case "$command" in
392 "") # Expand startup-options or commands
393 local commands=$(echo "${BAZEL_COMMAND_LIST}" \
Googler86a40472016-09-06 18:01:11 +0000394 | tr " " "\n" | "grep" -v "^${BAZEL_IGNORED_COMMAND_REGEX}$")
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000395 _bazel__expand_options "$workspace" "$displacement" "$cur" \
396 "${commands}\
397 ${BAZEL_STARTUP_OPTIONS}"
398 ;;
399
400 *)
401 case "$cur" in
402 -*) # Expand options:
403 _bazel__expand_options "$workspace" "$displacement" "$cur" \
404 "$(_bazel__options_for $command)"
405 ;;
406 *) # Expand target pattern
407 expansion_pattern="$(_bazel__expansion_for $command)"
408 NON_QUOTE_REGEX="^[\"']"
409 if [[ $command = query && $cur =~ $NON_QUOTE_REGEX ]]; then
410 : # Ideally we would expand query expressions---it's not
411 # that hard, conceptually---but readline is just too
412 # damn complex when it comes to quotation. Instead,
413 # for query, we just expand target patterns, unless
414 # the first char is a quote.
415 elif [ -n "$expansion_pattern" ]; then
416 _bazel__complete_pattern \
417 "$workspace" "$displacement" "$cur" "$expansion_pattern"
418 fi
419 ;;
420 esac
421 ;;
422 esac
423}
424
425_bazel__to_compreply() {
426 local replies="$1"
427 COMPREPLY=()
428 # Trick to preserve whitespaces
429 while IFS="" read -r reply; do
430 COMPREPLY+=("${reply}")
431 done < <(echo "${replies}")
432}
433
434_bazel__complete() {
435 _bazel__to_compreply "$(_bazel__complete_stdout)"
436}
437
438# Some users have aliases such as bt="bazel test" or bb="bazel build", this
439# completion function allows them to have auto-completion for these aliases.
440_bazel__complete_target_stdout() {
441 local cur=$(_bazel__get_cword) word command displacement workspace
442
443 # Determine command: "" (startup-options) or one of $BAZEL_COMMAND_LIST.
444 command="$1"
445
446 workspace="$(_bazel__get_workspace_path)"
447 displacement="$(_bazel__get_displacement ${workspace})"
448
449 _bazel__to_compreply "$(_bazel__expand_target_pattern "$workspace" "$displacement" \
Damien Martin-Guillerez60fde442016-07-22 15:47:25 +0000450 "$cur" "$(_bazel__expansion_for $command)")"
Damien Martin-Guillerez5f9c6ba2015-04-09 21:10:33 +0000451}
452
453# default completion for bazel
454complete -F _bazel__complete -o nospace "${BAZEL}"
Martin Probstf84650c2017-11-29 02:09:42 -0800455complete -F _bazel__complete -o nospace "${IBAZEL}"