Magento Module-Manager Bash Completion

Update (March 2, 2011): For the latest version of the modman bash_completion script check out the GitHub repository.

The following bash_completion script will enable your Linux shell to auto-complete Magento modman commands.  Make sure you have modman in your $PATH, then simply copy the file to /etc/bash_completion.d/modman or append to ~/.bash_completion.

#!/bin/bash
_modman()
{
	local cur prev opts modules mm
	COMPREPLY=()
	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[COMP_CWORD-1]}"

	opts="init --help --version"
	mm=$(_modman_get_mm)
	module=$(_modman_get_module)

	if [ -n "$mm" ] ; then
		opts="${opts} list repair update-all"
		modules=$(modman list)
	fi

	case "${prev}" in
		modman)
			opts="${opts} ${modules}"
			[ -n "$module" ] && opts="${opts} update deploy"
			;;

		init | --help | --version | list | repair | update-all)
			opts=""
			modules=""
			;;

		deploy | update | checkout | clone)
			opts="--force --copy"
			modules=""
			;;

		--force | --copy)
			opts=""
			modules=""
			;;

		*)
			[ ! -d "$mm/${prev}" ] && opts="checkout clone"
			[ -d "$mm/${prev}" ] && opts="update deploy"
			modules=""
			;;

	esac

	COMPREPLY=( $(compgen -W "${opts} ${modules}" -- ${cur}) )
	return 0
}

_modman_get_mm()
{
	local root _pwd
	_pwd=`pwd`
	root=$(_modman_realpath `pwd`)
	while ! [ -d $root/.modman ]; do
		if [ "$root" = "/" ]; then
			cd $_pwd && return 1
		fi
		cd ..
		root=`pwd`
	done
	cd $_pwd
	echo "$root/.modman"
}

_modman_get_module()
{
	local root module modpath mm _pwd
	_pwd=`pwd`
	mm=$(_modman_get_mm)
	root="$(dirname $mm)"
	module=''
	while [ "$root" != "$(pwd)" ]; do
		modpath=`pwd`
		if [ "$mm" = "$(dirname $modpath)" ]; then
			module=$(basename $modpath)
			break
		fi
		cd ..
	done
	cd $_pwd

	if [ -z "$module" ] ; then
		return 1
	fi

	echo $module
}

_modman_realpath()
{
	fname=${1%/} # strips trailing '/'
	while [ -L "$fname" ]; do
	 oldfname="$fname"
	 fname="$(command ls -l $fname)"
	 fname="${fname#*> }"
	 if [ "$fname" = . ] ; then
	 fname="$(dirname $oldfname)"
	 elif echo $fname | grep -vq '^/' - ; then
	 fname="$(dirname $oldfname)/$fname"
	 fi
	done
	pushd $(dirname $fname) > /dev/null
	fname=$(pwd -P)/$(basename $fname)
	popd > /dev/null
	echo $fname
}

complete -F _modman modman