Shanimal
Shanimal

Reputation: 11718

Setup command line completion with yargs

I'm creating a script with node JS and want to enable async command line completion with yargs.

The completion section of the yargs documentation says: "concat the generated script to your .bashrc or .bash_profile"

But I don't see any information about how to generate the script.

Upvotes: 7

Views: 4960

Answers (1)

Shanimal
Shanimal

Reputation: 11718

The documentation isn't completely clear how to do this, but I figured it out.

Install yargs

npm install -g yargs

Create your script (e.g script.js)

#! /usr/local/bin/node
var argv = require('yargs')
    .completion('completion', function(current, argv, done) {
        setTimeout(function() {
          done([
            'apple',
            'banana'
          ]);
        }, 500);
    })
    .argv;

Save your script and set permissions

chmod +x script.js

On the command line pass the command name (the first parameter in the completion call) to your script as the first parameter.

./script.js completion

This will output the command line completion block to add to .bashrc or .bash_profile

_yargs_completions()
{
    local cur_word args type_list

    cur_word="${COMP_WORDS[COMP_CWORD]}"
    args=$(printf "%s " "${COMP_WORDS[@]}")

    # ask yargs to generate completions.
    type_list=`./shan.js --get-yargs-completions $args`

    COMPREPLY=( $(compgen -W "${type_list}" -- ${cur_word}) )

    # if no match was found, fall back to filename completion
    if [ ${#COMPREPLY[@]} -eq 0 ]; then
      COMPREPLY=( $(compgen -f -- "${cur_word}" ) )
    fi

    return 0
}

Upvotes: 10

Related Questions