Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 612
Shanimal Avatar asked Aug 27 '15 19:08

Shanimal


People also ask

What is Yargs package?

Description. Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: commands and (grouped) options ( my-program. js serve --port=5000 ).

What is Yargs parser?

Yargs helps you build interactive command line tools by parsing arguments and generating an elegant user interface.


1 Answers

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
}
like image 137
Shanimal Avatar answered Sep 19 '22 08:09

Shanimal