How to use inquirer - 10 common examples

To help you get started, we’ve selected a few inquirer examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github FormidableLabs / builder-init / test / server / spec / lib / prompts.spec.js View on Github external
beforeEach(function () {
    // Intercept all real stdin/stdout.
    runStub = base.sandbox.stub(Prompt.prototype, "run");
  });
github vuejs / vue-cli / packages / @vue / cli-test-utils / assertPromptModule.js View on Github external
choose: 1 // package.json
      },
      {
        message: 'Save this as a preset',
        confirm: false
      }
    )
    if (!loadOptions().packageManager) {
      expectedPrompts.push({
        message: 'package manager',
        choose: 0 // yarn
      })
    }
  }

  expectPrompts(expectedPrompts)
  const creator = new Creator('test', '/', [].concat(module))
  const preset = await creator.promptAndResolvePreset()

  if (opts.pluginsOnly) {
    delete preset.useConfigFiles
  }
  expect(preset).toEqual(expectedOptions)
}
github expo / expo / tools / expotools / src / commands / PromoteVersionsToProduction.ts View on Github external
// amount of time so that the cache is invalidated before fetching from prod
  await new Promise(resolve => setTimeout(resolve, 10));

  Config.api.host = PRODUCTION_HOST;
  const versionsProd = await Versions.versionsAsync();
  const delta = jsondiffpatch.diff(versionsProd, versionsStaging);

  if (!delta) {
    console.log(chalk.yellow('There are no changes to apply in the configuration.'));
    return;
  }

  console.log(`Here is the diff from ${chalk.green('staging')} -> ${chalk.green('production')}:`);
  console.log(jsondiffpatch.formatters.console.format(delta, versionsProd));

  const { isCorrect } = await inquirer.prompt<{ isCorrect: boolean }>([
    {
      type: 'confirm',
      name: 'isCorrect',
      message: `Does this look correct? Type \`y\` to update ${chalk.green('production')} config.`,
      default: false,
    },
  ]);

  if (isCorrect) {
    // Promote staging configuration to production.
    await Versions.setVersionsAsync(versionsStaging);

    console.log(
      chalk.green('\nSuccessfully updated production config. You can check it out on'),
      chalk.blue(`https://${PRODUCTION_HOST}/--/api/v2/versions`)
    );
github open-wc / open-wc / packages / generator-open-wc / generators / app / index.js View on Github external
/* eslint-disable no-console */

const Generator = require('yeoman-generator');
const inquirer = require('inquirer');

const choices = {
  appStarter: 'Create Open Web Components Starter App',
  appProduction:
    'Create Open Web Components Enterprise App Setup (if you feel lost use the Starter App first)',
  separator1: new inquirer.Separator(),
  wcVanilla: 'Create a vanilla web component following the Open Web Components recommendations',
  wcUpgrade: 'Upgrade my existing web component to use the Open Web Components recommendations',
  separator2: new inquirer.Separator(),
  nothing: 'Nah, I am fine thanks! => exit',
};

module.exports = class GeneratorApp extends Generator {
  async prompting() {
    console.log('');
    console.log('Welcome to Open Web Components:');
    console.log('');

    this.answers = await this.prompt([
      {
        type: 'list',
        name: 'action',
github popomore / projj / lib / base_command.js View on Github external
* prompt(questions) {
    if (!this[PROMPT]) {
      // create a self contained inquirer module.
      this[PROMPT] = inquirer.createPromptModule();
      const promptMapping = this[PROMPT].prompts;
      for (const key of Object.keys(promptMapping)) {
        const Clz = promptMapping[key];
        // extend origin prompt instance to emit event
        promptMapping[key] = class CustomPrompt extends Clz {
          /* istanbul ignore next */
          static get name() { return Clz.name; }
          run() {
            process.send && process.send({ type: 'prompt', name: this.opt.name });
            process.emit('message', { type: 'prompt', name: this.opt.name });
            return super.run();
          }
        };
      }
    }
    return this[PROMPT](questions);
github pingyhq / pingy-cli / packages / cli / init / scaffold.js View on Github external
'use strict';

const ora = require('ora');
const inquirer = require('inquirer');
const pathTree = require('tree-from-paths');
const initLib = require('@pingy/init');
const scaffoldLib = require('@pingy/scaffold-primitive');
const listWithHelpText = require('./promptListWithHelpText');
const { basename } = require('path');

inquirer.registerPrompt('listWithHelpText', listWithHelpText);

const toNodeTree = (baseDir, paths) =>
  `  ${basename(baseDir)}/\n${pathTree
    .render(paths, baseDir, (parent, file) => file)
    .substring(1)
    .split('\n')
    .join('\n  ')}`;

const cwdNodeTree = info => toNodeTree(process.cwd(), info.preparedFiles);

const scaffoldConfirm = filesToWriteTxt =>
  inquirer.prompt([
    {
      type: 'listWithHelpText',
      name: 'doScaffold',
      // TODO: If any existing files exist then put up a red warning.
github Alek-S / select-run / cli.js View on Github external
const packageJsonPath = path.join(process.cwd(), 'package.json');


let packageJson;
try{
	packageJson = require(packageJsonPath);
}
catch(error) {
	// no package.json found
	errorMsg('package.json could not be read, you in the right directory?')
}

console.log(chalk.gray(`path: ${packageJsonPath}\n`) );

/* add checkbox-plus to inquirer prompt type */
inquirer.registerPrompt('checkbox-plus', require('inquirer-checkbox-plus-prompt'));
userInterview();



/**
 * @function userInterview
 * start the user interview with checkbox multi-select
 */
function userInterview () {
	const interviewMessage =
		`Select scripts -- (Press ${chalk.cyan('')} to select,` +
		` ${chalk.cyan('')} to complete)` +
		`\n${chalk.yellow('filter')}: `;

	inquirer
		.prompt({
github leebenson / reactql / cli / index.js View on Github external
);
            }

            // Add/edit `.reactql` file containing the current version, to enable
            // later upgrades
            fse.writeFileSync(
              path.resolve(installationPath, '.reactql'),
              kit.version
            );

            // Install package dependencies using NPM
            const installer = ['npm', ['i']];

            // Create a bottom bar to display the installation spinner at the bottom
            // of the console.
            const ui = new inquirer.ui.BottomBar({ bottomBar: spinner[0] });

            // Temporary var to track the position of the 'spinner'
            let i = 0;

            // Update the spinner every 300ms, to reflect the installation activity
            const update = setInterval(function () {
              ui.updateBottomBar(`\n${spinner[++i % 4]} Installing modules -- Please wait...`);
            }, 300);

            // Execute yarn/npm as a child process, pipe output to stdout
            spawn(...installer, {cwd: installationPath, stdio: 'pipe'})
              .stdout.pipe(ui.log)
              .on('error', () => fatalError("Couldn't install packages"))
              // When finished, stop the spinner, update with usage instructons and exit
              .on('close', function () {
                clearInterval(update);
github Fitbit / fitbit-sdk-toolchain / src / newProject.ts View on Github external
const packageJSON = fsExtra.readJSONSync(packageJSONPath);
  const config = normalizeProjectConfig(packageJSON);

  // Extract the member to a variable so that type guards work properly.
  const packageName = packageJSON.name;

  const defaultDisplayName =
    typeof packageName === 'string' ? lodash.startCase(packageName) : undefined;

  const {
    appType,
    appDisplayName,
    withCompanion,
    withSettings,
    enabledBuildTargets,
  }: ProjectCreationArgs = await inquirer.prompt([
    {
      name: 'appType',
      type: 'list',
      choices: Object.values(AppType),
      message: 'What type of application should be created?',
    },
    {
      name: 'appDisplayName',
      message: 'What should the name of this application be?',
      // Inquirer will not allow a default that fails validation
      // to be submited.
      default: defaultDisplayName,
      validate: validateDisplayName,
    },
    {
      name: 'withCompanion',
github aws-amplify / amplify-cli / packages / amplify-category-predictions / provider-utils / awscloudformation / prediction-category-walkthroughs / infer-walkthrough.js View on Github external
async function followUpQuestions(context, questionObj, inferType, defaultValues, parameters) {
  const answers = await inquirer.prompt(questionObj.endpointPrompt(parameters));
  if (answers.endpointConfig === 'import') {
    // attempt to get existing endpoints
    Object.assign(answers, await getEndpoints(context, questionObj, parameters));
  }
  if (answers.endpointConfig === 'create') {
    // create endpoint in console
    await createEndpoint(context, defaultValues);
    // import existing endpoint
    Object.assign(answers, await getEndpoints(context, questionObj, parameters));
  }

  Object.assign(answers, await inquirer.prompt(questionObj.authAccess.prompt(parameters)));
  return answers;
}