inquirer#prompt TypeScript Examples

The following examples show how to use inquirer#prompt. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: resolve-version-mismatch.ts    From nx-dotnet with MIT License 8 votes vote down vote up
async function getResolvedVersion({
  packageName,
  desired,
  configured,
}: {
  packageName?: string;
  desired: string;
  configured: string;
}) {
  const { resolution } = await prompt([
    {
      type: 'list',
      name: 'resolution',
      choices: [
        desired,
        configured,
        {
          name: 'Allow mismatched versions for this package',
          value: ALLOW_MISMATCH,
          short: 'Allow mismatch',
        },
      ],
      message: `There appears to be a mismatch between your current package preferences and the requested version ${
        packageName ? 'for ' + packageName : ''
      }. Which version would you like to use?`,
    },
  ]);
  return resolution;
}
Example #2
Source File: generator.spec.ts    From nx-dotnet with MIT License 6 votes vote down vote up
describe('sync generator', () => {
  let appTree: Tree;

  beforeEach(() => {
    appTree = createTreeWithEmptyWorkspace();
    updateConfig(appTree, { nugetPackages: {} });

    (prompt as jest.MockedFunction<typeof prompt>)
      .mockReset()
      .mockImplementation((async () => {
        return {};
      }) as () => Promise<Answers> & { ui: PromptUI });

    (getNxDotnetProjects as jest.MockedFunction<typeof getNxDotnetProjects>)
      .mockReset()
      .mockImplementation(() => Promise.resolve(new Map()));
  });

  it('should run successfully', async () => {
    await generator(appTree);
    expect(true).toBeTruthy();
  });
});
Example #3
Source File: plugin.create.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
pluginCreateRunner: TaskRunner<PluginCreateOptions> = async ({ name }) => {
  const destPath = path.resolve(process.cwd(), getPluginIdFromName(name || ''));
  let pluginDetails;

  // 1. Verifying if git exists in user's env as templates are cloned from git templates
  await verifyGitExists();

  // 2. Prompt plugin template
  const { type } = await promptPluginType();

  // 3. Fetch plugin template from Github
  await fetchTemplate({ type, dest: destPath });

  // 4. Prompt plugin details
  do {
    pluginDetails = await promptPluginDetails(name);
    formatPluginDetails(pluginDetails);
  } while ((await prompt<{ confirm: boolean }>(promptConfirm('confirm', 'Is that ok?'))).confirm === false);

  // 5. Update json files (package.json, src/plugin.json)
  await prepareJsonFiles({ pluginDetails, pluginPath: destPath });

  // 6. Remove cloned repository .git dir
  await removeGitFiles(destPath);
}
Example #4
Source File: create.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
promptPluginDetails = async (name?: string) => {
  const username = (await getGitUsername()).trim();
  const responses = await prompt<PluginDetails>([
    promptInput('name', 'Plugin name', true, name),
    promptInput('org', 'Organization (used as part of plugin ID)', true),
    promptInput('description', 'Description'),
    promptInput('keywords', 'Keywords (separated by comma)'),
    // Try using git specified username
    promptConfirm('author', `Author (${username})`, username, username !== ''),
    // Prompt for manual author entry if no git user.name specifed
    promptInput('author', `Author`, true, undefined, (answers: any) => !answers.author || username === ''),
    promptInput('url', 'Your URL (i.e. organisation url)'),
  ]);

  return {
    ...responses,
    author: responses.author === true ? username : responses.author,
  };
}
Example #5
Source File: create.ts    From grafana-chinese with Apache License 2.0 6 votes vote down vote up
promptPluginType = async () =>
  prompt<{ type: PluginType }>([
    {
      type: 'list',
      message: 'Select plugin type',
      name: 'type',
      choices: [
        { name: 'Angular panel', value: 'angular-panel' },
        { name: 'React panel', value: 'react-panel' },
        { name: 'Datasource plugin', value: 'datasource-plugin' },
      ],
    },
  ])
Example #6
Source File: resolve-version-mismatch.ts    From nx-dotnet with MIT License 6 votes vote down vote up
async function promptForDesiredVersion(packageName?: string): Promise<string> {
  const { choice } = await prompt([
    {
      name: 'choice',
      message: `You have not yet set a version for ${
        packageName ? packageName : 'this package'
      }. Which version would you like to install?`,
    },
  ]);
  return choice;
}
Example #7
Source File: prompt-for-template.ts    From nx-dotnet with MIT License 6 votes vote down vote up
export function promptForTemplate(
  client: DotNetClient,
  search?: string,
  language?: string,
): string | Promise<string> {
  const available = client.listInstalledTemplates({ search, language });

  if (search) {
    const exactMatch = available.find((x) => x.shortNames.includes(search));
    if (exactMatch) {
      return exactMatch.shortNames[0];
    }
  }

  return prompt<{ template: string }>([
    {
      name: 'template',
      type: 'list',
      message:
        'What template should the project be initialized with? (https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-new#template-options) ',
      choices: available.map((a) => ({
        value: a.shortNames[0],
        message: a.templateName,
      })),
    },
  ]).then((a) => a.template);
}
Example #8
Source File: generator.spec.ts    From nx-dotnet with MIT License 6 votes vote down vote up
describe('restore generator', () => {
  let appTree: Tree;

  beforeEach(() => {
    appTree = createTreeWithEmptyWorkspace();
    updateConfig(appTree, { nugetPackages: {} });

    (prompt as jest.MockedFunction<typeof prompt>)
      .mockReset()
      .mockImplementation((async () => {
        return {};
      }) as () => Promise<Answers> & { ui: PromptUI });

    (getNxDotnetProjects as jest.MockedFunction<typeof getNxDotnetProjects>)
      .mockReset()
      .mockImplementation(() => Promise.resolve(new Map()));
  });

  it('should run successfully', async () => {
    await generator(appTree, null);
    expect(true).toBeTruthy();
  });
});
Example #9
Source File: index.ts    From open-source with MIT License 6 votes vote down vote up
function gitCommit<T>(files: T, ask: string): Observable<T> {
  return exec('git', ['status']).pipe(
    concatMap(() => exec('git', ['diff', '--cached', '--numstat'])),
    concatMap((output) => {
      const lines = (output.stdout?.toString() || '').split('\n').filter(Boolean).length;
      return lines
        ? (!opts.dryRun ? prompt(question(ask)).ui.process : of({ name: '', answer: 'msg' })).pipe(
            concatMap(({ answer }) => exec('git', ['commit', '--no-verify', '-m', `"${answer}"`], { dryRun: opts.dryRun })),
          )
        : of(files);
    }),
    mapTo(files),
    catchError(() => throwError('Do not use --git outside a repository')),
  );
}
Example #10
Source File: index.ts    From open-source with MIT License 6 votes vote down vote up
function gitCommit<T>(files: T, ask: string): Observable<T> {
  return exec('git', ['status']).pipe(
    concatMap(() => exec('git', ['diff', '--cached', '--numstat'])),
    concatMap((output) => {
      const lines = (output.stdout?.toString() || '').split('\n').filter(Boolean).length;
      return lines
        ? (!opts.dryRun ? prompt(question(ask)).ui.process : of({ name: '', answer: 'msg' })).pipe(
            concatMap(({ answer }) => exec('git', ['commit', '--no-verify', '-m', `"${answer}"`], { dryRun: opts.dryRun })),
          )
        : of(files);
    }),
    mapTo(files),
    catchError(() => throwError('Do not use --git outside a repository')),
  );
}
Example #11
Source File: command-log.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public async promptList(choices: string[] | NameValue[], message: string): Promise<string> {
    const result = await prompt({
      prefix: chalk.bold.cyan('?'),
      name: 'value',
      type: 'list',
      message,
      choices,
      loop: false,
    })

    deletePreviousLine()

    return result.value
  }
Example #12
Source File: command-log.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
   * Ask for password WITHOUT confirmation
   *
   * @returns password
   */
  public async askForPassword(message: string, clear = true): Promise<string> {
    if (this.verbosityLevel === VerbosityLevel.Quiet) {
      throw new CommandLineError(Message.optionNotDefined('password'))
    }

    const { value } = await prompt({
      prefix: chalk.bold.cyan('?'),
      type: 'password',
      name: 'value',
      message,
    })

    if (!value) {
      deletePreviousLine()
      throw new CommandLineError('No password specified')
    }

    if (clear) {
      deletePreviousLine()
    }

    return value
  }
Example #13
Source File: command-log.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
   * Ask for an arbitrary value
   *
   * @returns value
   */
  public async askForValue(message: string): Promise<string> {
    const input = await prompt({
      prefix: chalk.bold.cyan('?'),
      name: 'value',
      message,
    })
    const { value } = input

    if (!value) {
      deletePreviousLine()
      throw new CommandLineError('No value specified')
    }

    deletePreviousLine()

    return value
  }
Example #14
Source File: command-log.ts    From swarm-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public async confirm(message: string): Promise<boolean> {
    const { value } = await prompt({
      prefix: chalk.bold.cyan('?'),
      type: 'confirm',
      name: 'value',
      message,
    })

    return value
  }
Example #15
Source File: generator.spec.ts    From nx-dotnet with MIT License 5 votes vote down vote up
describe('nuget-reference generator', () => {
  let appTree: Tree;

  const options: NugetReferenceGeneratorSchema = {
    packageName: 'test',
    project: 'test',
    allowVersionMismatch: false,
  };

  let dotnetClient: DotNetClient;

  beforeEach(() => {
    appTree = createTreeWithEmptyWorkspace();
    appTree.write(
      'workspace.json',
      JSON.stringify({
        projects: {
          test: {},
        },
      }),
    );
    appTree.write(
      'nx.json',
      JSON.stringify({
        projects: {
          test: {
            tags: [],
          },
        },
      }),
    );

    updateConfig(appTree, { nugetPackages: {} });
    (prompt as jest.MockedFunction<typeof prompt>)
      .mockReset()
      .mockImplementation((async () => {
        return {};
      }) as () => Promise<Answers> & { ui: PromptUI });

    dotnetClient = new DotNetClient(mockDotnetFactory());
  });

  it('runs calls dotnet add package reference', async () => {
    await generator(appTree, options, dotnetClient);
    const mock = dotnetClient as jest.Mocked<DotNetClient>;
    expect(mock.addPackageReference).toHaveBeenCalledTimes(1);
  });

  it('only prompts user once on version mismatch / miss', async () => {
    await generator(appTree, options, dotnetClient);
    expect(prompt).toHaveBeenCalledTimes(1);
  });

  it('provides resolved version to dotnet add package reference', async () => {
    const { getProjectFileForNxProject } = await import('@nx-dotnet/utils');

    const projectFilePath = 'libs/test/Test.csproj';

    (getProjectFileForNxProject as jest.MockedFunction<() => Promise<string>>)
      .mockReset()
      .mockResolvedValue(projectFilePath);

    updateConfig(appTree, {
      nugetPackages: { [options.packageName]: '1.2.3' },
    });
    await generator(appTree, options, dotnetClient);
    const mock = dotnetClient as jest.Mocked<DotNetClient>;
    expect(mock.addPackageReference).toHaveBeenCalledWith(
      projectFilePath,
      options.packageName,
      { version: '1.2.3' },
    );
  });
});
Example #16
Source File: install.ts    From gdmod with MIT License 5 votes vote down vote up
async execute() {
    const results = await prompt([
      {
        type: "list",
        name: "type",
        message: "What type of export is the game you wish to patch?",
        choices: [
          { name: "A local HTML5 export", value: "dir" },
          { name: "An online HTML5 export", value: "web" },
          { name: "A PC export", value: "asar" },
          { name: "A mobile export", value: "mobile" },
        ],
      },
      {
        name: "location",
        message: `What is the path to the ${chalk.italic
          .blue`app.asar`} file of the game? You can find it under "the/game/folder/resources/app.asar".`,
        when: (currentAnswers) => {
          return currentAnswers.type === "asar";
        },
        validate: async (answer) => {
          try {
            const stat = await fs.stat(answer);
            if (!stat.isFile()) return "The path entered is not a file!";
          } catch {
            return "Cannot find or access the asar file!";
          }
          return true;
        },
      },
      {
        name: "location",
        message: `What is the path to the directory of the game?`,
        when: (currentAnswers) => {
          return currentAnswers.type === "dir";
        },
        validate: async (answer) => {
          const fs = require("fs/promises");
          try {
            const stat = await fs.stat(answer);
            if (!stat.isDirectory())
              return "The path entered is not a directory!";
          } catch {
            return "Cannot find or access the directory!";
          }
          return true;
        },
      },
      {
        type: "confirm",
        name: "electron",
        message: `Do you wish to apply electron only patches?`,
        when: (currentAnswers) => {
          return currentAnswers.type === "dir";
        },
      },
    ]);

    if (results.type === "mobile") {
      console.info(
        chalk.red`\nMobile is sadly not supported by GDMod currently.`
      );
      return 1;
    }

    if (results.type === "web") {
      console.log(
        chalk`{green The CLI cannot patch games hosted online. Please use the browser extension for this platform.} 
{italic {bold Learn more at} {underline {grey https://github.com/arthuro555/gdmod/wiki/Installation-Guide#web-games}}.}`
      );
      return 1;
    }

    const command: string[] = ["install", results.type, results.location];
    if (results.electron) command.push("--electron");
    return await this.cli.run(command.concat(this.rest));
  }
Example #17
Source File: prompts.spec.ts    From the-fake-backend with ISC License 5 votes vote down vote up
jest.mock('inquirer', () => ({
  registerPrompt: jest.fn(),
  prompt: jest.fn(),
}));
Example #18
Source File: prompts.spec.ts    From the-fake-backend with ISC License 5 votes vote down vote up
describe('source/prompts.ts', () => {
  describe('promptRoutePath', () => {
    it('calls inquirer prompt', () => {
      const paths = ['/users', '/dogs'];
      promptRoutePath(paths);
      expect(mocked(prompt)).toHaveBeenCalledWith([
        {
          type: 'autocomplete',
          name: 'url',
          message: 'Search for the endpoint URL:',
          source: expect.any(Function),
        },
      ]);
    });
  });

  describe('promptRouteMethodType', () => {
    it('calls inquirer prompt', () => {
      const methodTypes = ['GET', 'POST'];
      promptRouteMethodType(methodTypes);
      expect(mocked(prompt)).toHaveBeenCalledWith([
        {
          type: 'autocomplete',
          name: 'type',
          message: 'Select the type:',
          source: expect.any(Function),
        },
      ]);
    });
  });

  describe('promptRouteMethodOverride', () => {
    it('calls inquirer prompt', () => {
      const overrides = ['Dogoo', 'Doggernaut'];
      promptRouteMethodOverride(overrides);
      expect(mocked(prompt)).toHaveBeenCalledWith([
        {
          type: 'autocomplete',
          name: 'name',
          message: 'Select the override settings:',
          source: expect.any(Function),
        },
      ]);
    });
  });

  describe('promptProxy', () => {
    it('calls inquirer prompt', () => {
      const proxies = ['First', 'Second'];
      promptProxy(proxies);
      expect(mocked(prompt)).toHaveBeenCalledWith([
        {
          type: 'autocomplete',
          name: 'proxy',
          message: 'Select the proxy:',
          source: expect.any(Function),
        },
      ]);
    });
  });
});
Example #19
Source File: version.ts    From gitmars with GNU General Public License v3.0 5 votes vote down vote up
prompt([
    {
        type: 'list',
        name: 'recommend',
        message: 'Choose which version do you want?',
        default: newVers.production[0].version,
        choices: [
            // new Separator(' === Increase (recommend) === '),
            ...newVers.increase.map(el => `${el.id}) ${el.version}`),
            // new Separator(' === Production (recommend) === '),
            ...newVers.production.map(el => `${el.id}) ${el.version}`),
            'create pre version',
            new Separator(' --- Exit --- '),
            'exit',
            new Separator()
        ]
    },
    {
        type: 'list',
        name: 'pre',
        message: 'Choose which version do you want?',
        default: newVers.pre[0].version,
        choices: [
            ...newVers.pre.map(el => `${el.id}) ${el.version}`),
            new Separator(' --- Exit --- '),
            'exit',
            new Separator()
        ],
        when(data) {
            return data.recommend === 'create pre version'
        }
    },
    {
        type: 'confirm',
        name: 'confirm',
        message: '[Be Cautious]: Do you need to create a git tag?',
        default: true,
        when(data) {
            return data.recommend !== 'exit' && data.pre !== 'exit'
        }
    }
]).then((data: { recommend: string; pre?: string; confirm: boolean }) => {
    if (data.recommend === 'exit' || data.pre === 'exit') {
        process.exit(0)
    }

    const PACKAGE_JSON_URL = resolve(ROOT, 'package.json')
    const [id] = (data.pre || data.recommend).split(')')
    const { command, version } = searchVerTarget(id)

    if (data.confirm) {
        execSync(command, execOption)
    } else {
        writeJSON(PACKAGE_JSON_URL, {
            ...pkg,
            version
        })
    }
    spawnSync('npx', ['prettier', '--write', './package.json'], spawnOption)
})