kislyuk / argcomplete

Python and tab completion, better together.
https://kislyuk.github.io/argcomplete/
Apache License 2.0
1.39k stars 129 forks source link

How to complete user-defined git subcommands? #347

Open jnikula opened 3 years ago

jnikula commented 3 years ago

git and some other tools support user-defined subcommands by having git-some-subcommand in PATH. Running git some-subcommand runs the custom subcommand via git binary. I can't figure out how to make argcomplete support completion on that subcommand alone. Obviously it works for git-some-subcommand directly, but how to enable it via git while preserving regular git completion?

kislyuk commented 3 years ago

I'm not sure if that's possible with argcomplete - git registers its own completion module that gets activated when bash sees a command line that starts with git.

With that said, I have some custom git commands defined in my ~/.gitconfig, and the git completion module completes them for me.

algorythmic commented 3 years ago

To provide completions for git some-command, git completion looks for a function called _git_some_command.

If git-some-command is written to be completed with argcomplete, you just need to define a wrapper function that

  1. adjusts the necessary completion-related variables enough to make it look like the original command is being completed
  2. calls _python_argcomplete like normal completion would.

Using the example from argcomplete docs:

chmod +x describe_github_user.py
ln -s describe_github_user.py git-describe-github-user
PATH+=:$PWD

_git_describe_github_user() {
    # replace command word and following spaces with `git-'
    local new_line="git-${COMP_LINE##"${COMP_WORDS[0]}"+( )}"
    # adjust point to account for the difference in line length
    COMP_POINT=$(( COMP_POINT - ${#COMP_LINE} + ${#new_line} ))
    COMP_LINE=$new_line
    # call the argcomplete handler
    _python_argcomplete "git-describe-github-user"
}

and now you'll get completions for git describe-github-user as expected.