Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git autocomplete for custom bash functions

In my .bash_profile, I have a lot of functional shortcuts for git. For example:

function gitpull() {
    branch="$1"

    if [[ -z $branch ]]; then
        current_branch=`git symbolic-ref -q --short HEAD`
        git pull origin $current_branch;
    elif [[ -n $branch && $branch == "m" ]]; then
        git pull origin master;
    else
        git pull origin $branch;
    fi;
}

However, when I'm typing this in the terminal, I want it to autocomplete git branches. How do I do this? (I already am using .git-completion.bash)

like image 680
Nxt3 Avatar asked Feb 05 '23 04:02

Nxt3


2 Answers

Manually-crafted bash completion is as simple as this:

# our handler that returns choices by populating Bash array COMPREPLY
# (filtered by the currently entered word ($2) via compgen builtin)
_gitpull_complete() {
    branches=$(git branch -l | cut -c3-)
    COMPREPLY=($(compgen -W "$branches" -- "$2"))
}

# we now register our handler to provide completion hints for the "gitpull" command
complete -F _gitpull_complete gitpull

After sourcing the above commands:

$ gitpull <TAB>
asd     master  qwe     zxc
$ gitpull m<TAB>
$ gitpull master

The ultimate reference on bash completion is (of course) the section on Programmable Completion in the bash manual, but a nice introduction is given on "Debian Administration" page (part 1 and a more important part 2).

like image 106
randomir Avatar answered Feb 07 '23 10:02

randomir


The recommended method is by using __git_complete():

__git_complete gitpull _git_pull
like image 33
FelipeC Avatar answered Feb 07 '23 09:02

FelipeC