Completion when program has sub-commands
Asked Answered
C

2

21

I have written a command-line tool that uses sub-commands much like Mercurial, Git, Subversion &c., in that its general usage is:

>myapp [OPTS] SUBCOMMAND [SUBCOMMAND-OPTS] [ARGS]

E.g.

>myapp --verbose speak --voice=samantha --quickly "hello there"

I'm now in the process of building Zsh completion for it but have quickly found out that it is a very complex beast. I have had a look at the _hg and _git completions but they are very complex and different in approach (I struggle to understand them), but both seem to handle each sub-command separately.

Does anyone know if there a way using the built in functions (_arguments, _values, pick_variant &c.) to handle the concept of sub-commands correctly, including handling general options and sub-command specific options appropriately? Or would the best approach be to manually handle the general options and sub-command?

A noddy example would be very much appreciated.

Many thanks.

Calve answered 25/1, 2012 at 9:57 Comment(0)
L
28

Writing completion scripts for zsh can be quite difficult. Your best bet is to use an existing one as a guide. The one for Git is way too much for a beginner. You can use this repo:

https://github.com/zsh-users/zsh-completions

As for your question, you have use the concept of state. You define your subcommands in a list and then identify via $state which command you are in. Then you define the options for each command. You can see this in the completion script for play. A simplified version is below:

_play() {
  local ret=1

  _arguments -C \
    '1: :_play_cmds' \
    '*::arg:->args' \
  && ret=0

  case $state in
    (args)
       case $line[1] in
         (build-module|list-modules|lm|check|id)
           _message 'no more arguments' && ret=0
         ;;
         (dependencies|deps)
           _arguments \
             '1:: :_play_apps' \
             '(--debug)--debug[Debug mode (even more informations logged than in verbose mode)]' \
             '(--jpda)--jpda[Listen for JPDA connection. The process will  suspended until a client is plugged to the JPDA port.]' \
             '(--sync)--sync[Keep lib/ and modules/ directory synced. Delete unknow dependencies.]' \
             '(--verbose)--verbose[Verbose Mode]' \
             && ret=0
         ;;
       esac
   esac

(If you are going to paste this, use the original source, as this won't work).

It looks daunting, but the general idea is not that complicated:

  • The subcommand comes first (_play_cmds is a list of subcommands with a description for each one).
  • Then come the arguments. The arguments are built based on which subcommand you are choosing. Note that you can group multiple subcommands if they share arguments.

With man zshcompsys, you can find more info about the whole system, although it is somewhat dense.

Lorenz answered 25/1, 2012 at 10:15 Comment(2)
That is fantastic thank you so much. I'm glad you said zshcompsys is dense as I was starting to think it was me ;)Calve
In 20 years this code will look like binary does to me today.Potpie
H
2

I found a technique that works well and is easy to understand. Basically, you create a new completion function for each subcommand and call it from the top-level completion function. Here's an example with dolt, showing how dolt completes to dolt table and dolt table completes to dolt table import, which then completes with a set of flags:

_dolt() {
    local line state

    _arguments -C \
               "1: :->cmds" \
               "*::arg:->args"
    case "$state" in
        cmds)
            _values "dolt command" \
                    "table[Commands for copying, renaming, deleting, and exporting tables.]" \
            ;;
        args)
            case $line[1] in
                table)
                    _dolt_table
                    ;;
            esac
            ;;
    esac
}

_dolt_table() {
    local line state

    _arguments -C \
               "1: :->cmds" \
               "*::arg:->args"
    case "$state" in
        cmds)
            _values "dolt_table command" \
                    "import[Creates, overwrites, replaces, or updates a table from the data in a file.]" \
            ;;
        args)
            case $line[1] in
                import)
                    _dolt_table_import
                    ;;
            esac
            ;;
    esac
}

_dolt_table_import() {
    _arguments -s \
               {-c,--create-table}'[Create a new table, or overwrite an existing table (with the -f flag) from the imported data.]' \
               {-u,--update-table}'[Update an existing table with the imported data.]' \
               {-f,--force}'[If a create operation is being executed, data already exists in the destination, the force flag will allow the target to be overwritten.]' \
               {-r,--replace-table}'[Replace existing table with imported data while preserving the original schema.]' \
               '(--continue)--continue[Continue importing when row import errors are encountered.]' \
               {-s,--schema}'[The schema for the output data.]' \
               {-m,--map}'[A file that lays out how fields should be mapped from input data to output data.]' \
               {-pk,--pk}'[Explicitly define the name of the field in the schema which should be used as the primary key.]' \
               '(--file-type)--file-type[Explicitly define the type of the file if it can''t be inferred from the file extension.]' \
               '(--delim)--delim[Specify a delimiter for a csv style file with a non-comma delimiter.]'
}

I wrote a full guide here:

https://www.dolthub.com/blog/2021-11-15-zsh-completions-with-subcommands/

Holman answered 1/12, 2022 at 19:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.