Git Product home page Git Product logo

yargs-interactive's Introduction

Yargs Interactive

Build Status Coverage Status semantic-release npm npm

Read the blog post

Interactive (prompt) support for yargs, based on inquirer. Useful for using the same CLI for both for humans and non-humans (like CI tools). Also supports mixed mode (yay!).

Yargs Interactive

This tool helps you to build command line tools without worring to parse arguments, or develop the logic to ask them.

Installation

npm install -S yargs-interactive

Then, add this code in your CLI code to get all the arguments parsed:

#!/usr/bin/env node

const yargsInteractive = require("yargs-interactive");
const options = {
  name: { type: "input", default: "A robot", describe: "Enter your name" },
  likesPizza: { type: "confirm", default: false, describe: "Do you like pizza?" }
};

yargsInteractive()
  .usage("$0 <command> [args]")
  .interactive(options)
  .then(result => {
    // Your business logic goes here.
    // Get the arguments from the result
    // e.g. myCli(result.name);
    console.log(`\nResult is:\n` + `- Name: ${result.name}\n` + `- Likes pizza: ${result.likesPizza}\n`);
  });

Now, by simply wrapping your CLI code with this tool, you'll get all the information you need from the user. For instance, save the previous snipped in a file named my-cli.js and run it in your terminal:

➜ node my-cli.js --interactive

Basic usage

Note: See other CLI examples in this folder.

Usage

It supports the following use cases

Prompt questions (full-interactive)

my-cli.js

const yargsInteractive = require("yargs-interactive");

const options = {
  name: {
    type: "input",
    describe: "Enter your name"
  },
  likesPizza: {
    type: "confirm",
    describe: "Do you like pizza?"
  }
};

yargsInteractive()
  .usage("$0 <command> [args]")
  .interactive(options)
  .then(result => {
    // The tool will prompt questions and will output your answers.
    // TODO: Do something with the result (e.g result.name)
    console.log(result);
  });

Usage in terminal

➜ node my-cli.js --interactive

If you want to use interactive mode always, avoiding the need of sending it as an argument, set the --interactive parameter to true by default:

const options = {
  interactive: { default: true },
  ...
};

yargsInteractive()
  .usage('$0 <command> [args]')
  .interactive(options)
  .then((result) => {
    // The tool will prompt questions and will output your answers.
    // TODO: Do something with the result (e.g result.name)
    console.log(result)
  });

And then simply call your CLI with no parameters.

➜ node my-cli.js

Options

Property Type Description
type string (Required) The type of the option to prompt (e.g. input, confirm, etc.). We provide all prompt types supported by Inquirer.
describe string (Required) The message to display when prompting the option (e.g. Do you like pizza?)
default any The default value of the option.
prompt string (Default is if-empty) Property to decide whether to prompt the option or not. Possible values: always, never, if-no-arg (prompts if the option was not sent via command line parameters) and if-empty (prompts if the value was not sent via command line parameters and it doesn't have a default property).

Prompt some questions (mixed mode)

You can opt-out options from interactive mode by setting the prompt property to never. By default, its value is if-empty, prompting the question to the user if the value was not set via command line parameters, or if it doesn't have a default property. Setting it to if-no-arg will prompt the question if no argument is provided. Lastly, you can use always to always prompt the option.

my-cli.js

const yargsInteractive = require("yargs-interactive");

const options = {
  name: {
    // prompt property, if not set, defaults to 'if-empty'
    // In this case, it means the question will be prompted
    // if it is not provided by args, as it doesn't have a default value.
    type: "input",
    describe: "Enter your name"
  },
  likesPizza: {
    type: "confirm",
    default: false,
    describe: "Do you like pizza?",
    prompt: "never" // because everyone likes pizza
  }
};

yargsInteractive()
  .usage("$0 <command> [args]")
  .interactive(options)
  .then(result => {
    // The tool will prompt questions output the answers.
    // You can opt-out options by using `prompt: 'never'`. For these properties, it
    // will use the value sent by parameter (--likesPizza) or the default value.
    // TODO: Do something with the result (e.g result.name)
    console.log(result);
  });

Usage in terminal

➜ node my-cli.js --interactive

Notice that if you enter node my-cli.js --name='Johh' --interactive name won't be prompted either (as by default it uses if-empty).

No prompt at all (ye olde yargs)

my-cli.js

const yargsInteractive = require("yargs-interactive");

const options = {
  name: {
    type: "input",
    default: "nano",
    describe: "Enter your name"
  },
  likesPizza: {
    type: "confirm",
    default: false,
    describe: "Do you like pizza?"
  }
};

yargsInteractive()
  .usage("$0 <command> [args]")
  .interactive(options)
  .then(result => {
    // The tool will output the values set via parameters or
    // the default value (if not provided).
    // TODO: Do something with the result (e.g result.name)
    console.log(result);
  });

Usage in terminal

➜ node my-cli.js --name='Johh' --likesPizza

yargs-interactive's People

Contributors

favna avatar iamturns avatar nanovazquez avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

yargs-interactive's Issues

How do you use it with commands?

I don't see how to use this package with commands. E.g. ...

yargsInteractive()
    .command('do-it', 'Does things.', o => o
      .options(myOptions))
    .strict()
    .demandCommand()
    .help()
    .argv;

I can only call .interactive(...) and pass in options directly from the yargsInteractive() return. I can't seem to configure an interactive command.

Support for Typescript typings

@nanovazquez I don't know how familiar you are with Typescript, but I opened a PR at DefinitelyTyped to have typings for yargs-interactive. I need to update it now that options is choices. But I'm thinking the interfaces should probably extend from inquirer at some point. I'm just not sure what all is passed from yargs-interactive to inquirer here. Any input on that PR would be helpful.

Supplying argument does not remove prompt in `if-empty` mode

Steps to replicate

  1. Create 'mixed mode' example as described within README.md
  2. Invoke with --name='Johh' --interactive args (also shown in README)

Expected behaviour

I will not be prompted for name, as it has been supplied as an arg

Actual behaviour

I am prompted for name

Potential fix

I think I've fixed the problem locally with these changes:

--- a/node_modules/yargs-interactive/src/yargs-interactive.js
+++ b/node_modules/yargs-interactive/src/yargs-interactive.js
@@ -29,10 +29,15 @@ let yargsInteractive = (processArgs = process.argv.slice(2), cwd) => {
 
     // Remove options with prompt value set to 'never'
     // and options with prompt value set to 'if-empty' but no default value or value set via parameter
-    const interactiveOptions = filterObject(mergedOptions, (item, key) => (
-      item.prompt !== 'never'
-      && (item.prompt !== 'if-empty' || isEmpty(item.default) || isEmpty(argv[key]))
-    ));
+    const interactiveOptions = filterObject(mergedOptions, (item, key) => {
+      if (item.prompt === 'never') {
+        return false;
+      }
+      if (item.prompt === 'always') {
+        return true;
+      }
+      return isEmpty(item.default) && isEmpty(argv[key]);
+    });
 
     // Check if we should get the values from the interactive mode
     return argv.interactive

Checkbox list doesn't work on Linux

I just implemented this code with a single param of type checkbox and it works perfectly fine on my Windows machine (using Git Bash with powerline), but on my Linux hosting machine (Shell: zsh v5.4.2 / bash v4.4.20 | Distro: Ubuntu 18.04.3 LTS) it completely breaks. Linux at the top.

image

And this is the list I'm feeding the checkbox command as choices:
image

The sourecode is on GitHub: https://github.com/Favna/ribbon/
Or the specific commit which adds the file where I use yargs interactive: favna/ribbon@fcaa7f8

Following your example adding --interactive doesn't allow interactive mode

^ like what title says.

I'm trying to enter interactive mode, but whatever I do, i can't. Am I missing something here?

i saved the file like so in test.js


const yargsInteractive = require("yargs-interactive");
const options = {
  interactive: { default: true },
  name: { type: "input", default: "A robot", describe: "Enter your name" },
  likesPizza: {
    type: "confirm",
    default: false,
    describe: "Do you like pizza?",
  },
};

yargsInteractive()
  .usage("$0 <command> [args]")
  .interactive(options)
  .then((result) => {
    // Your business logic goes here.
    // Get the arguments from the result
    // e.g. myCli(result.name);
    console.log(
      `\nResult is:\n` +
        `- Name: ${result.name}\n` +
        `- Likes pizza: ${result.likesPizza}\n`
    );
  });

then i run

node test.js --interactive

outputs immediately without prompts:


Result is:
- Name: A robot
- Likes pizza: false

How to use the list type from inquirer?

Do list types work for this? I'm playing around and trying the following as an option

  Favorite: {
    describe: "What is your favorite color?",
    prompt: "always",
    type: "list",
    choices: [
      "Blue",
      "Red",
      "Green",
      "Yellow",
      "Orange"
    ],
  },

But I just get an error saying You must provide a choices parameter.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.