@sap/cli-core
Version:
Command-Line Interface (CLI) Core Module
180 lines (179 loc) • 7.2 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCommands = exports.executeCommand = exports.init = void 0;
if (process.env.SUPPRESS_NO_CONFIG_WARNING === undefined) {
process.env.SUPPRESS_NO_CONFIG_WARNING = "true";
}
/* eslint-disable import/first */
const path_1 = __importDefault(require("path"));
const logger_1 = require("../logger");
const constants_1 = require("../constants");
const cache_1 = require("../cache");
const config_1 = require("../config");
const commands_1 = require("../utils/commands");
const discovery_1 = require("../discovery");
const settings_1 = require("../settings");
const utils_1 = require("./utils");
const utils_2 = require("../commands/handler/options/utils");
const core_1 = require("../config/core");
const ResultHandlerImpl_1 = require("../result/ResultHandlerImpl");
const ResultHandlerFactory_1 = require("../result/ResultHandlerFactory");
const SecretsStorageImpl_1 = require("../cache/secrets/SecretsStorageImpl");
const SecretsStorageSingleton_1 = require("../cache/secrets/SecretsStorageSingleton");
const utils_3 = require("../commands/handler/utils");
let program;
let initialized = false;
const getLogger = () => (0, logger_1.get)("dwc.dwc");
const MANDATORY_OPTIONS = [
constants_1.OPTION_VERSION,
constants_1.OPTION_HELP,
constants_1.OPTION_HOST,
constants_1.OPTION_FILE_PATH,
constants_1.OPTION_FORCE,
constants_1.OPTION_OUTPUT,
constants_1.OPTION_VERBOSE,
constants_1.OPTION_INPUT,
constants_1.OPTION_OPTIONS_FILE,
];
const setTenant = async () => {
const config = (0, config_1.get)();
if (config.host) {
return;
}
const readHostFromArgv = async () => (0, utils_1.getOptionValueFromArgv)(constants_1.ROOT_COMMAND, constants_1.OPTION_HOST);
const readHostFromOptionsFile = async () => {
const filePath = (0, utils_1.getOptionValueFromArgv)(constants_1.ROOT_COMMAND, constants_1.OPTION_OPTIONS_FILE);
return (0, utils_2.getValueFromOptionsFile)(filePath, constants_1.OPTION_HOST);
};
const readHostFromOptions = async () => {
if (!config.options?.[constants_1.OPTION_HOST.longName]) {
throw new Error("host not found in options");
}
return config.options[constants_1.OPTION_HOST.longName];
};
const strategies = [
{
func: readHostFromArgv,
name: "read host from argv",
},
{
func: readHostFromOptionsFile,
name: "read host from options-file",
},
{
func: readHostFromOptions,
name: "read host from options",
},
];
const { trace } = getLogger();
for (const { name, func } of strategies) {
trace(`trying to ${name}`);
try {
// eslint-disable-next-line no-await-in-loop
const host = (0, utils_3.replaceLeadingTrailingSingleQuotes)(await func());
(0, config_1.set)({
tenant: host,
options: { ...config.options, [constants_1.OPTION_HOST.longName]: host },
});
break;
}
catch (err) {
trace(`failed to ${name}`, err);
}
}
};
const setHost = async () => {
const settings = await (0, settings_1.get)();
if (settings.host) {
(0, config_1.set)({ options: { [constants_1.OPTION_HOST.longName]: settings.host } });
}
};
const initCacheTolerant = async () => {
try {
await (0, cache_1.init)();
}
catch {
// ignore
}
};
const registerMandatoryOptions = () => {
MANDATORY_OPTIONS.forEach((option) => (0, commands_1.registerLongName)(constants_1.ROOT_COMMAND, option));
};
async function setupSecretsStorage() {
const instance = new SecretsStorageImpl_1.SecretsStorageImpl();
await instance.initializeStorage();
SecretsStorageSingleton_1.SecretsStorageSingleton.SINGLETON = instance;
}
const init = async () => {
const { debug } = getLogger();
if (initialized) {
return;
}
initialized = true;
const resultHandler = new ResultHandlerImpl_1.ResultHandlerImpl();
ResultHandlerFactory_1.ResultHandlerFactory.set(resultHandler);
registerMandatoryOptions();
await setHost();
await setTenant();
await initCacheTolerant();
await setupSecretsStorage();
const cliName = (0, config_1.get)()[constants_1.CLI_NAME];
program = (0, commands_1.createCommand)();
program.name(cliName);
program.version((0, core_1.getVersion)(), "-v, --version", "output the current version");
program.description((0, config_1.get)()[constants_1.CLI_DESCRIPTION]);
program.showHelpAfterError(`Make sure to always define the host using the --host option or by running ${cliName}` +
` config host set "<Server_URL>". Did you initialize the CLI by running ${cliName} config` +
` cache init --host "<Server_URL>"?` +
` Add option --help, -h or go to ${(0, config_1.get)()[constants_1.CLI_SAP_HELP]} for additional information.`);
program.addOption(await (0, commands_1.buildOption)(constants_1.ROOT_COMMAND, constants_1.OPTION_HOST));
program.addOption(await (0, commands_1.buildOption)(constants_1.ROOT_COMMAND, constants_1.OPTION_OPTIONS_FILE));
program.configureHelp({ sortSubcommands: true });
program.addHelpText("afterAll", `Only command-specific options are listed here. To learn more about available generic options,` +
` visit ${(0, core_1.getGenericOptionsHelp)()}`);
const commandsPath = path_1.default.join(__dirname, "..", "commands");
await (0, utils_1.addCommandsFromFolder)(commandsPath, program);
debug("cli initialized");
};
exports.init = init;
const executeCommand = async (command) => {
await program.parseAsync(command?.split(" ") ?? undefined);
};
exports.executeCommand = executeCommand;
const buildCommandsObject = (name, command, object = {}) => {
const commandName = name || "dwc";
// eslint-disable-next-line no-param-reassign
object[commandName] = async (options) => {
await (0, exports.executeCommand)(new Array(2)
.fill("dummy")
.concat(name.split(" ").concat(options
? Object.entries(options).reduce((prev, curr) => {
const [key, value] = curr;
return prev.concat([key, value]);
}, [])
: []))
.join(" "));
return ResultHandlerFactory_1.ResultHandlerFactory.get().getResult();
};
/* istanbul ignore next */
command.commands.forEach((c) => {
buildCommandsObject(name ? `${name} ${c.name()}` : c.name(), c, object);
});
return object;
};
const reinitialize = (host) => {
initialized = false;
(0, config_1.initialize)();
(0, config_1.set)({ tenant: host });
(0, config_1.setCustomConfig)();
(0, discovery_1.clear)();
};
const getCommands = async (host) => {
reinitialize(host);
await (0, exports.init)();
return buildCommandsObject("", program);
};
exports.getCommands = getCommands;