xref: /aosp_15_r20/external/pigweed/pw_cli/py/pw_cli/shell_completion/common.bash (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1# Copyright 2023 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14
15if [[ -n ${ZSH_VERSION-} ]]; then
16  autoload -U +X bashcompinit && bashcompinit
17fi
18
19__pwcomp_words_include ()
20{
21  local i=1
22  while [[ $i -lt $COMP_CWORD ]]; do
23    if [[ "${COMP_WORDS[i]}" = "$1" ]]; then
24      return 0
25    fi
26    i=$((++i))
27  done
28  return 1
29}
30
31# Find the previous non-switch word
32__pwcomp_prev ()
33{
34  local idx=$((COMP_CWORD - 1))
35  local prv="${COMP_WORDS[idx]}"
36  while [[ $prv == -* ]]; do
37    idx=$((--idx))
38    prv="${COMP_WORDS[idx]}"
39  done
40}
41
42
43__pwcomp ()
44{
45  # break $1 on space, tab, and newline characters,
46  # and turn it into a newline separated list of words
47  local list s sep=$'\n' IFS=$' '$'\t'$'\n'
48  local cur="${COMP_WORDS[COMP_CWORD]}"
49
50  for s in $1; do
51    __pwcomp_words_include "$s" && continue
52    list="$list$s$sep"
53  done
54
55  case "$cur" in
56  --*=)
57    COMPREPLY=()
58    ;;
59  *)
60    IFS=$sep
61    COMPREPLY=( $(compgen -W "$list" -- "$cur" | sed -e 's/[^=]$/& /g') )
62    ;;
63  esac
64}
65
66