Change directory to a Go package, with tab completion

In bash

To get:

~ $ gcd some<tab>
~ $ gcd something
~/go/pkgs/something $

put the following in your .bashrc:

# Bash function to cd to a package on GOPATH (inspiration for that
# from... elsewhere; I can't remember now unfortunately), and bash
# completion for the aforementioned (my own work). Have at it.
# -- Gavin Panella, 2013

gcd() {
    local package="$1"
    local pdir="$(go list -e -f '{{.Dir}}' "${package}")"
    if [ -z "${pdir}" ]
    then
        echo "${package} not found" >&2
        return 1
    else
        cd "${pdir}"
    fi;
}

_gcd() {
    local cur path paths
    # The current word due for completion.
    cur=${COMP_WORDS[COMP_CWORD]}
    # Non-local array storing the possible completions.
    COMPREPLY=()
    # Split GOPATH by colon, being careful about whitespace.
    IFS=: read -a paths -r <<< "$GOPATH"
    # Iterate GOPATH, again being careful about whitespace.
    for path in "${paths[@]}"
    do
        COMPREPLY=(
            "${COMPREPLY[@]}"
            # Ignore missing directories on GOPATH.
            $(cd "${path}/src" 2> /dev/null &&
                compgen -o dirnames "${cur}")
        )
    done
    return 0
}

complete -F _gcd -o nospace -S / gcd