2

Using yargs is it possible for the user of the CLI to specify which command they want to call with the arguments and then the CLI replies with the following message before running the code:

Are you sure you want to execute this code on environment X with these settings: .... Y / N:

Y would execute the code N would do nothing

Update: Just found an npm modulecalled yargs-interactive. I think this is the answer to my question.

Blake Rivell
  • 13,105
  • 31
  • 115
  • 231

1 Answers1

3

I was not able to find anything in yargs itself to do this. So I just used Node's readline module:

import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'


async function confirm(question) {
  const line = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  })

  return new Promise((resolve) => {
    line.question(question, (response) => {
      line.close()
      resolve(response === 'Y')
    })
  })
}

async function handleRemove(argv) {
  const confirmed = await confirm(`Are you sure you want to remove the stuff? [Y/n]`)

  if (confirmed) {
    // Remove everything
  }
}

yargs(hideBin(process.argv))
  .command({
    command: 'remove',
    describe: 'Remove important stuff',
    handler: handleRemove,
  })
  .showHelpOnFail(true)
  .scriptName('cli')
  .demandCommand()
  .help().argv

bman
  • 5,016
  • 4
  • 36
  • 69