From 6704287fb4309da416b185ff5a0ca6cc9878f3f9 Mon Sep 17 00:00:00 2001 From: James Wainwright Date: Wed, 17 Jan 2024 14:36:01 +0000 Subject: [PATCH] [bazel] Allow ./bazelisk.sh to use --bazelrc flags These flags need to come _before_ the subcommand, i.e.: ``` bazel --bazelrc=... cquery # VALID bazel cquery --bazelrc=... # INVALID ``` which is done in this script by pushing flags that come before the subcommand name into an array and re-applying them in the correct order later. If these Bash arrays are confusing and you've come across this commit in a `git blame` then hopefully this will help: 1. Bash supports arrays defined using parentheses: `array=("foo" "bar")` 2. Arrays can't be passed as arguments to functions, they are expanded and get mixed into other arguments, so we use a global instead. 4. the syntax for expanding an array into its elements with correct quoting on each is: `"${array[@]}"`. Signed-off-by: James Wainwright --- bazelisk.sh | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/bazelisk.sh b/bazelisk.sh index 7ba3153f717571..9f2a42d83f0873 100755 --- a/bazelisk.sh +++ b/bazelisk.sh @@ -93,10 +93,14 @@ function outquery_starlark_expr() { esac } +# Arguments: +# $qexpr: starlark expression - see `outquery_starlark_expr` +# $name: name of an array containing Bazel arguments that should come _before_ +# the subcommand (e.g. `--bazelrc=...`). function do_outquery() { - local qexpr="$1" - shift - "$file" cquery "$@" \ + local qexpr="$1"; shift + + "$file" "${pre_cmd_args[@]}" cquery "$@" \ --output=starlark --starlark:expr="$qexpr" \ --ui_event_filters=-info --noshow_progress } @@ -121,6 +125,14 @@ function main() { fi fi + # Shift all flags (starting with `-`) that come before the subcommand + # into an array. + pre_cmd_args=() + while [[ "${1-}" == -* ]]; do + pre_cmd_args+=("$1") + shift + done + case "${1-}" in outquery*) # The custom 'outquery' command can be used to query bazel for the @@ -130,8 +142,7 @@ function main() { # outquery-all: return all output files associated with the label. # outquery-x: return output files containing the substring "x". # outquery.x: return output files ending with the substring ".x". - local qexpr - qexpr="$(outquery_starlark_expr "$1")" + local qexpr="$(outquery_starlark_expr "$1")" shift do_outquery "$qexpr" "$@" ;; @@ -150,13 +161,13 @@ function main() { local qexpr outfile qexpr="$(outquery_starlark_expr outquery)" outfile=$(do_outquery "$qexpr" "$@") - "$file" build "$@" + "$file" "${pre_cmd_args[@]}" build "$@" # shellcheck disable=SC2059 # We are intentionally using $command_template as a format string. eval "$(printf "$command_template" "$outfile")" ;; *) - exec "$file" "$@" + exec "$file" "${pre_cmd_args[@]}" "$@" ;; esac }