@sap/cli-core
Version:
Command-Line Interface (CLI) Core Module
72 lines (71 loc) • 2.83 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getValueFromOptionsFile = exports.setOption = exports.promptForValue = exports.checkOptions = void 0;
const prompts_1 = __importDefault(require("prompts"));
const fs_extra_1 = require("fs-extra");
const logger_1 = require("../../../logger");
const commands_1 = require("../../../utils/commands");
const config_1 = require("../../../config");
const checkOptions = async (options, command) => {
const intOptions = Array.isArray(options) ? options : [options];
for (const option of intOptions) {
if (!(0, commands_1.isOptionAlreadyRegistered)(option, command)) {
command.addOption(
// eslint-disable-next-line no-await-in-loop
await (0, commands_1.buildOption)(command, { ...option, required: false }));
}
}
};
exports.checkOptions = checkOptions;
const promptForValue = async (option) => {
let choices = [];
if (option.choices) {
choices =
typeof option.choices === "function"
? await option.choices()
: option.choices;
}
const { value } = await prompts_1.default.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;
};
exports.promptForValue = promptForValue;
const buildOptionName = (option) => `--${option.longName}`;
const setOption = (option, value) => {
const { output } = (0, logger_1.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}`);
}
(0, config_1.set)({
options: { [option.longName]: value },
});
};
exports.setOption = setOption;
const getValueFromOptionsFile = async (filePath, { longName }) => {
const options = JSON.parse(await (0, fs_extra_1.readFile)(filePath, { encoding: "utf8" }));
if (options[longName]) {
return options[longName];
}
throw new Error(`no value for option ${longName} found in file ${filePath}`);
};
exports.getValueFromOptionsFile = getValueFromOptionsFile;