#!/bin/bash
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
#
# This script was generated by `pants bash-completion`
#
# Pants Autocompletion Support
#
# To use, copy this script to a file. You can either install it by:
#
#  - Copying the script to /etc/bash-completion.d/pants-completion.bash.
#  - Using the "source" command to include it in your ~/.bashrc file.
#
# Note that the autocompletion will not work if you just run the file.
# It must be "sourced" into the environment

__pants_scopes='{{{scopes_text}}}'
{{{options_text}}}

# Pants autocompletion handler.
__pants_autocomplete() {
  # The reply to the shell must be placed in the COMPREPLY variable.
  COMPREPLY=()

  local pants="${COMP_WORDS[0]}"

  # Determine what the user is trying to autocomplete (scope, option, or target).

  local saw_scope=0
  local scope_name=''
  local is_option=0
  local is_scope=0

  local i=1   # Skip index 0 which is the "./pants" command.
  while [[ $i -le $COMP_CWORD ]]; do
    local arg="${COMP_WORDS[i]}"
    case "$arg" in
      -*)
        is_option=1
        is_scope=0
        ;;
      *)
        is_option=0
        if [[ $saw_scope = 1 ]]; then
          is_scope=0
        else
          is_scope=1
          saw_scope=1
          scope_name="$arg"
        fi
    esac

    i="$(expr "$i" + 1)"
  done

  # Return a response to bash based on the context.
  if [[ $is_scope = 1 ]]; then
    # Autocomplete using the scope names and global flags.
    # TODO(tdyas): Fix https://github.com/pantsbuild/pants/issues/1793.
    COMPREPLY=($(compgen -W "${__pants_scopes} ${__pants_global_options}" -- "${COMP_WORDS[COMP_CWORD]}" ))
  elif [[ $is_option = 1 ]]; then
    # Autocomplete using any relevant options for `scope_name`.
    local options=''
    local scope_name_for_var=`echo "${scope_name}" | tr .- __  `
    eval "options=\"\${__pants_options_for_${scope_name_for_var}}\""
    COMPREPLY=($(compgen -W "${options}" -- "${COMP_WORDS[COMP_CWORD]}" ))
  else
    local arg="${COMP_WORDS[COMP_CWORD]}"
    if [[ "$arg" =~ ":" ]]; then
      local parts=(${arg//:/ })
      local path=${parts[0]}

      # If the path before the colon points at a valid BUILD file, query Pants for the targets.
      if [ -r "${path}/BUILD" ]; then
        local completions=`"$pants" list "${path}:" 2>/dev/null | cut -d: -f2`
        COMPREPLY=($(compgen -W "${completions}" -- "${parts[1]}" ))
      fi
    fi
  fi
}

# Install the pants autocompletion handler. The "default" completion option tells Bash to perform its regular
# filename substitution if the function fails to provide candidates.
complete -o default -F __pants_autocomplete pants
