1# Copyright 2011 Google Inc. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://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,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15# Add the following to your .bashrc to tab-complete ninja targets
16#   . path/to/ninja/misc/bash-completion
17
18_ninja_target() {
19    local cur prev targets dir line targets_command OPTIND
20
21    # When available, use bash_completion to:
22    #   1) Complete words when the cursor is in the middle of the word
23    #   2) Complete paths with files or directories, as appropriate
24    if _get_comp_words_by_ref cur prev &>/dev/null ; then
25        case $prev in
26            -f)
27                _filedir
28                return 0
29                ;;
30            -C)
31                _filedir -d
32                return 0
33                ;;
34        esac
35    else
36        cur="${COMP_WORDS[COMP_CWORD]}"
37    fi
38
39    if [[ "$cur" == "--"* ]]; then
40        # there is currently only one argument that takes --
41	COMPREPLY=($(compgen -P '--' -W 'version' -- "${cur:2}"))
42    else
43	dir="."
44	line=$(echo ${COMP_LINE} | cut -d" " -f 2-)
45        # filter out all non relevant arguments but keep C for dirs
46	while getopts :C:f:j:l:k:nvd:t: opt $line; do
47	    case $opt in
48                # eval for tilde expansion
49		C) eval dir="$OPTARG" ;;
50	    esac
51	done;
52	targets_command="eval ninja -C \"${dir}\" -t targets all 2>/dev/null | cut -d: -f1"
53	COMPREPLY=($(compgen -W '`${targets_command}`' -- "$cur"))
54    fi
55    return
56}
57complete -F _ninja_target ninja
58