#
# 'git' bash completion 
#
# Copyright (c) Paolo Giarrusso, 2005
# Copyright (c) Ben Clifford, 2005
#

bashdefault="-o bashdefault"
default="-o default"
o_help="-h"

_git ()
{
    local cur cmd cmds opts
    cur=${COMP_WORDS[COMP_CWORD]}
    COMPREPLY=()
    if [ $COMP_CWORD -eq 1 ]; then
        cmds="$(git help -a | grep --regexp '^ ')"
        COMPREPLY=( $(compgen -W "${cmds}" -- $cur) )
    else
        local cmd=${COMP_WORDS[1]}
	local prev=${COMP_WORDS[COMP_CWORD-1]}
        case $cmd in
        branch)
            # git branch NEWBRANCHNAME BASE
            # always complete on branch names
            # XXX could probably just complete on the first 2 args
            COMPREPLY=( $(compgen -W "$(__git_refs)" -- $cur) )
            ;;
	checkout)
	    # git checkout [-f] [-b <new_branch>] [<branch>] [<paths>...]
	    opts="-f -b" 
	    if [ "$prev" = "-b" ]; then 
	        # complete on branch name
	        COMPREPLY=( $(compgen -W "$(__git_heads)" -- $cur) )
	    else
	        COMPREPLY=( $(compgen -W "${opts} $(__git_heads)" -- $cur) )
	        # XXX actually here, need to detect if it is the first 
	        # non-option parameter - if so, complete with git_refs,
	        # otherwise complete with filename
	    fi
	    ;;
        cherry)
            COMPREPLY=( $(compgen -W "$(__git_refs)" -- $cur) )
            ;;
        diff-tree)
        #git diff-tree [--stdin] [-m] [-c] [--cc] [-s] [-v] [--pretty] [-t] [-r] [--root] [<common diff options>] <tree-ish> [<tree-ish>] [<path>...]
            opts="--stdin -m -c --cc -s -v --pretty -t -r --root"
	    COMPREPLY=( $(compgen -f -W "${opts} $(__git_heads)" -- $cur) )
            ;;
	fetch)
            COMPREPLY=( $(compgen -W "$(__git_remotes)" -- $cur) )
            ;;
        ls-tree)
        #git ls-tree [-d] [-r] [-t] [-z] [--name-only] [--name-status] [--full-name] <tree-ish> [path...]
        # this is missing some functionality -- we should complete the 
        # first non-opt as a treeish, and the rest as paths but actually
        # what we do is just complete both treeish and paths for everything
            opts="-d -r -t -z --name-only --name-status --full-name"
	    COMPREPLY=( $(compgen -f -W "${opts} $(__git_heads)" -- $cur) )
            ;;
	name-rev)
            COMPREPLY=( $(compgen -W "--tags --all --stdin $(__git_refs)" -- $cur) )
            ;;
	pull)
            COMPREPLY=( $(compgen -W "$(__git_remotes)" -- $cur) )
            ;;
	push)
            COMPREPLY=( $(compgen -W "$(__git_remotes)" -- $cur) )
            ;;
	rebase)
            COMPREPLY=( $(compgen -W "$(__git_refs)" -- $cur) )
            ;;
	show-branch)
            COMPREPLY=( $(compgen -W "--all --heads --tags --topo-order --current --more= --list --independent --merge-base --no-name --sha1-name $(__git_refs)" -- $cur) )
            ;;
	*)
	    COMPREPLY=( $(compgen $default -W "${o_help}" -f -- $cur) )
	    ;;
	esac
    fi
}


complete $default -F _git git

