UNPKG

@sap/cli-core

Version:

Command-Line Interface (CLI) Core Module

64 lines (63 loc) 2.37 kB
import prompts from "prompts"; import fs from "fs-extra"; import { get } from "../../../logger/index.js"; import { buildOption, isOptionAlreadyRegistered, } from "../../../utils/commands.js"; import { set as setConfig } from "../../../config/index.js"; export const checkOptions = async (options, command) => { const intOptions = Array.isArray(options) ? options : [options]; for (const option of intOptions) { if (!isOptionAlreadyRegistered(option, command)) { command.addOption( // eslint-disable-next-line no-await-in-loop await buildOption(command, { ...option, required: false })); } } }; export const promptForValue = async ( // This function expects that the `prompts` property is always defined option) => { let choices = []; if (option.choices) { choices = typeof option.choices === "function" ? await option.choices() : option.choices; } const { value } = await prompts.prompt({ type: option.prompts.type, choices: choices.map((choice) => ({ title: choice, value: choice, })), initial: option.prompts.initial, message: typeof option.prompts.message === "string" ? option.prompts.message : option.prompts.message(), name: "value", }); if (option.prompts.inputValidator) { if (!option.prompts.inputValidator(value)) { throw new Error(`input validator returned false for value ${value}`); } } return value; }; const buildOptionName = (option) => `--${option.longName}`; export const setOption = (option, value) => { const { output } = get("handler.options"); if (!value && (option.args || []).length > 0) { const name = buildOptionName(option); output(`error: required option '${name}' not specified`); throw new Error(`no value provided for option ${option.longName}`); } setConfig({ options: { [option.longName]: value }, }); }; export const getValueFromOptionsFile = async (filePath, { longName }) => { const options = JSON.parse(await fs.readFile(filePath, { encoding: "utf8" })); if (options[longName]) { return options[longName]; } throw new Error(`no value for option ${longName} found in file ${filePath}`); };