<%
# To make changes to the completions:
#
# - For changes to a command under `COMMANDS` or `DEVELOPER COMMANDS` sections):
#   - Find the source file in `Library/Homebrew/[dev-]cmd/<command>.{rb,sh}`.
#   - For `.rb` files, edit the `cmd_args` block. For subcommand metadata,
#     edit `Library/Homebrew/<command>/subcommand.rb` and
#     `Library/Homebrew/<command>/subcommand/*.rb` if they exist.
#   - For `.sh` files, edit the top comment, being sure to use the line prefix
#     `#:` for the comments to be recognized as documentation. If in doubt,
#     compare with already documented commands.
# - For other changes: Edit this file.
#
# When done, regenerate the completions by running `brew generate-man-completions`.
%>
# Bash completion script for brew(1)
# This file is automatically generated by running `brew generate-man-completions`.
# See Library/Homebrew/completions/bash.erb for editing instructions.

if [[ -n ${POSIXLY_CORRECT:-} ]] || shopt -oq posix
then
  echo "Homebrew Bash completions do not work in POSIX mode" 1>&2
  return
fi

__brewcomp_words_include() {
  local element idx
  for (( idx = 1; idx < COMP_CWORD; idx++ ))
  do
    element=${COMP_WORDS[idx]}
    [[ -n ${element} && ${element} == "$1" ]] && return 0
  done
  return 1
}

__brewcomp() {
  # break $1 on space, tab, and newline characters,
  # and turn it into a newline separated list of words
  local list s sep=$'\n' IFS=$' \t\n'
  local cur=${COMP_WORDS[COMP_CWORD]}

  for s in $1
  do
    __brewcomp_words_include "${s}" || list+="${s}${sep}"
  done

  list=${list%"${sep}"}

  IFS="${sep}"
  while read -r line; do COMPREPLY+=("${line}"); done < <(compgen -W "${list}" -- "${cur}")
}

# Don't use __brewcomp() in any of the __brew_complete_foo functions, as
# it is too slow and is not worth it just for duplicate elimination.
__brew_complete_formulae() {
  local cur="${COMP_WORDS[COMP_CWORD]}"
  local formulae
  formulae="$(HOMEBREW_COMPLETION=1 brew formulae)"
  while read -r line; do COMPREPLY+=("${line}"); done < <(compgen -W "${formulae}" -- "${cur}")
}

__brew_complete_casks() {
  local cur="${COMP_WORDS[COMP_CWORD]}"
  local casks
  casks="$(HOMEBREW_COMPLETION=1 brew casks)"
  while read -r line; do COMPREPLY+=("${line}"); done < <(compgen -W "${casks}" -- "${cur}")
}

__brew_complete_installed_formulae() {
  local cur="${COMP_WORDS[COMP_CWORD]}"
  local installed_formulae
  installed_formulae="$(command ls "${HOMEBREW_CELLAR:-$(brew --cellar)}" 2>/dev/null)"
  while read -r line; do COMPREPLY+=("${line}"); done < <(compgen -W "${installed_formulae}" -- "${cur}")
}

__brew_complete_installed_casks() {
  local cur="${COMP_WORDS[COMP_CWORD]}"
  local installed_casks
  installed_casks="$(command ls "$(brew --caskroom)" 2>/dev/null)"
  while read -r line; do COMPREPLY+=("${line}"); done < <(compgen -W "${installed_casks}" -- "${cur}")
}

__brew_complete_outdated_formulae() {
  local cur="${COMP_WORDS[COMP_CWORD]}"
  local outdated_formulae
  outdated_formulae="$(HOMEBREW_NO_AUTO_UPDATE=1 brew outdated --formula --quiet)"
  while read -r line; do COMPREPLY+=("${line}"); done < <(compgen -W "${outdated_formulae}" -- "${cur}")
}

__brew_complete_outdated_casks() {
  local cur="${COMP_WORDS[COMP_CWORD]}"
  local outdated_casks
  outdated_casks="$(HOMEBREW_NO_AUTO_UPDATE=1 brew outdated --cask --quiet 2>/dev/null)"
  while read -r line; do COMPREPLY+=("${line}"); done < <(compgen -W "${outdated_casks}" -- "${cur}")
}

__brew_complete_tapped() {
  local dir taps taplib
  taplib=${HOMEBREW_REPOSITORY:-$(brew --repository)}/Library/Taps

  for dir in "${taplib}"/*/*
  do
    [[ -d ${dir} ]] || continue
    dir=${dir#"${taplib}"/}
    dir=${dir/homebrew-/}
    taps+=" ${dir}"
  done
  __brewcomp "${taps}"
}

__brew_complete_commands() {
  # Auto-complete Homebrew commands

  local cur="${COMP_WORDS[COMP_CWORD]}"
  local cmds
  local maintainer_cmds
  local user_aliases

  if [[ -n ${__HOMEBREW_COMMANDS} ]]
  then
    cmds=${__HOMEBREW_COMMANDS}
  elif [[ -n ${HOMEBREW_CACHE:-} && -f ${HOMEBREW_CACHE}/all_commands_list.txt ]]
  then
    cmds="$(< "${HOMEBREW_CACHE}/all_commands_list.txt")"
  elif [[ -n ${HOMEBREW_REPOSITORY:-} && -f ${HOMEBREW_REPOSITORY}/completions/internal_commands_list.txt ]]
  then
    cmds="$(< "${HOMEBREW_REPOSITORY}/completions/internal_commands_list.txt")"
  fi
  if [[ -n ${HOMEBREW_DEVELOPER:-} ]]
  then
    maintainer_cmds="<%= maintainer_commands.join(" ") %>"
  fi
  user_aliases="$(__brew_list_aliases)"
  while read -r line
  do
    [[ $(__brew_internal_command_alias "${line}") == "${line}" ]] || continue
    COMPREPLY+=("${line}")
  done < <(compgen -W "${cmds} ${maintainer_cmds} ${user_aliases}" -- "${cur}")
  export __HOMEBREW_COMMANDS=${cmds}
}

__brew_complete_services() {
  local cur="${COMP_WORDS[COMP_CWORD]}"
  local services
  services="$(command find "$(brew --cellar)" -mindepth 3 -maxdepth 3 -name '*.service' \
    | awk -F'homebrew.|.service' '{print $3}' \
    | sort -d)"
  while read -r line; do COMPREPLY+=("${line}"); done < <(compgen -W "${services}" -- "${cur}")
}

# compopt is only available in newer versions of bash
__brew_complete_files() {
  command -v compopt &> /dev/null && compopt -o default
}

__brew_internal_command_alias() {
  case "$1" in
    <%= aliases.join("\n    ") + "\n" %>
    *) echo "$1" ;;
  esac
}

# https://github.com/Homebrew/homebrew-aliases
__brew_list_aliases() {
  local aliases_dir="${HOME}/.config/brew-aliases"
  local pattern="alias: brew ([^[:space:]]+)"
  local alias_name line
  local -a aliases

  [[ ! -d ${aliases_dir} ]] && aliases_dir="${HOME}/.brew-aliases"
  [[ ! -d ${aliases_dir} ]] && return

  for file in "${aliases_dir}"/*; do
    [[ ! -f ${file} || ${file} == *~ ]] && continue
    alias_name="${file##*/}"
    {
      read -r line
      if read -r line && [[ ${line} =~ ${pattern} ]]; then
        alias_name="${BASH_REMATCH[1]}"
      fi
    } < "${file}"
    aliases+=("${alias_name}")
  done
  [[ -n ${aliases[*]+"${aliases[*]}"} ]] && echo "${aliases[@]}"
}

<%= completion_functions.join("\n") %>

_brew() {
  local i=1 cmd

  # find the subcommand
  while [[ "${i}" -lt "${COMP_CWORD}" ]]
  do
    local s="${COMP_WORDS[i]}"
    case "${s}" in
      --*)
        cmd="${s}"
        break
        ;;
      -*)
        ;;
      *)
        cmd="${s}"
        break
        ;;
    esac
    (( i++ ))
  done

  if [[ "${i}" -eq "${COMP_CWORD}" ]]
  then
    __brew_complete_commands
    return
  fi

  cmd="$(__brew_internal_command_alias "${cmd}")"

  # subcommands have their own completion functions
  case "${cmd}" in
    <%= function_mappings.join("\n    ").concat("\n") %>
    *) ;;
  esac
}

# keep around for compatibility
_brew_to_completion() {
  _brew
}

complete -o bashdefault -o default -F _brew brew
