xref: /aosp_15_r20/external/pigweed/pw_cli/py/pw_cli/shell_completion/pw.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
15# Source common bash completion functions
16# Path to this directory, works in bash and zsh
17COMPLETION_DIR=$(dirname "${BASH_SOURCE[0]-$0}")
18. "${COMPLETION_DIR}/common.bash"
19
20_pw () {
21  local i=1 cmd
22
23  if [[ -n ${ZSH_VERSION-} ]]; then
24    emulate -L bash
25    setopt KSH_TYPESET
26
27    # Workaround zsh's bug that leaves 'words' as a special
28    # variable in versions < 4.3.12
29    typeset -h words
30  fi
31
32  # find the subcommand
33  while [[ $i -lt $COMP_CWORD ]]; do
34    local s="${COMP_WORDS[i]}"
35    case "$s" in
36    --*) ;;
37    -*) ;;
38    *)  cmd="$s"
39      break
40      ;;
41    esac
42    i=$((++i))
43  done
44
45  if [[ $i -eq $COMP_CWORD ]]; then
46    local cur="${COMP_WORDS[COMP_CWORD]}"
47    case "$cur" in
48      -*)
49        local all_options=$(pw --no-banner --tab-complete-option "")
50        __pwcomp "${all_options}"
51        return
52        ;;
53      *)
54        local all_commands=$(pw --no-banner --tab-complete-command "")
55        __pwcomp "${all_commands}"
56        return
57        ;;
58    esac
59    return
60  fi
61
62  # subcommands have their own completion functions
63  case "$cmd" in
64    help)
65      local all_commands=$(pw --no-banner --tab-complete-command "")
66      __pwcomp "${all_commands}"
67      ;;
68    *)
69      # If the command is 'build' and a function named _pw_build exists, then run it.
70      [[ $(type -t _pw_$cmd) == function ]] && _pw_$cmd
71      ;;
72  esac
73}
74
75complete -o bashdefault -o default -o nospace -F _pw pw
76