Source

ap3-sdk-bin / ap3.completion.bash

Full commit
#!/usr/bin/bash
#
# Atlassian AP3 SDK completion
# ============================
# Bash completion support for [ap3](https://bitbucket.org/atlassian/ap3-sdk-bin)
#
# loosely based on the git-flow completion script:
# Copyright (c) 2010 [Justin Hileman](http://justinhileman.com)
# Distributed under the [MIT License](http://creativecommons.org/licenses/MIT/)
#
case "$COMP_WORDBREAKS" in
*:*) : great ;;
*)   COMP_WORDBREAKS="$COMP_WORDBREAKS:"
esac

_ap3()
{
	local cur words cword prev
	_get_comp_words_by_ref -n =: cur words cword prev

	local commands="$(_list_ap3_commands)"

	local subcommand="$(__ap3_find_subcommand "$commands")"
	if [ -z "$subcommand" ]; then
		__ap3comp "$commands"
		return
	fi

	case "$subcommand" in
	config)
		_ap3_config
		return
		;;
	new)
		_ap3_new
		return
		;;
	start)
		_ap3_start
		return
		;;
	help)
		_ap3_help
		return
		;;
	*)
		COMPREPLY=()
		;;
	esac
}

############
# Commands #
############
_ap3_help ()
{
	__ap3comp "$(_list_ap3_commands)"
}

_ap3_config ()
{
	__ap3comp "bitbucket servlet-kit"
}

_ap3_new ()
{
	__ap3comp "ringo-kit servlet-kit"
}

_ap3_start ()
{
	__ap3comp "confluence jira p3"
}

############
# Helpers  #
############
__ap3_find_subcommand()
{
	local word subcommand c=1
	while [ $c -lt $cword ]; do
		word="${words[c]}"
		for subcommand in $1; do
			if [ "$subcommand" = "$word" ]; then
				echo "$subcommand"
				return
			fi
		done
		c=$((++c))
	done
}

__ap3comp ()
{
	local cur_="$cur"

	if [ $# -gt 2 ]; then
		cur_="$3"
	fi
	case "$cur_" in
	--*=)
		COMPREPLY=()
		;;
	*)
		local IFS=$'\n'
		COMPREPLY=($(compgen -P "${2-}" \
			-W "$(__ap3comp_1 "${1-}" "${4-}")" \
			-- "$cur_"))
		;;
	esac
}

__ap3comp_1 ()
{
	local c IFS=' '$'\t'$'\n'
	for c in $1; do
		case "$c$2" in
		--*=*) printf %s$'\n' "$c$2" ;;
		*.)    printf %s$'\n' "$c$2" ;;
		*)     printf %s$'\n' "$c$2" ;;
		esac
	done
}

_get_comp_words_by_ref ()
{
	while [ $# -gt 0 ]; do
		case "$1" in
		cur)
			cur=${COMP_WORDS[COMP_CWORD]}
			;;
		prev)
			prev=${COMP_WORDS[COMP_CWORD-1]}
			;;
		words)
			words=("${COMP_WORDS[@]}")
			;;
		cword)
			cword=$COMP_CWORD
			;;
		-n)
			# assume COMP_WORDBREAKS is already set sanely
			shift
			;;
		esac
		shift
	done
}

_list_ap3_commands ()
{
	local subcommands="bash-it config help init new start"
	local i IFS=" "$'\n'
	for i in $subcommands
	do
		case $i in
		*--*)             : helper pattern;;
		*) echo $i;;
		esac
	done
}

complete -F _ap3 ap3