UNPKG

@auttam/easycli

Version:

A quick and easy way of creating cli for your npm package.

320 lines (319 loc) 11.7 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.optionInfo = exports.paramInfo = exports.version = exports.command = exports.program = void 0; const os_1 = require("os"); const settings_1 = require("./settings"); const runtime_error_1 = require("./errors/runtime-error"); const stringWidth = require('string-width'); var defaultLeftIndent = 3; var defaultRightIndent = 3; const BOLD = '\u001b[1m'; const RESET = '\u001b[0m'; const UNDERLINE = '\u001b[4m'; function boldText(text) { if (!settings_1.SettingStore.useColors) return text; return BOLD + text + RESET; } function underlineText(text) { if (!settings_1.SettingStore.useColors) return text; return UNDERLINE + text + RESET; } function underlinedBoldText(text) { if (!settings_1.SettingStore.useColors) return text; return BOLD + UNDERLINE + text + RESET; } function padString(target, width) { if (!width || isNaN(width) || width < target.length) return target; return target + ' '.repeat(width - target.length); } function getWidth(...target) { var width = 0; if (!target) return width; target.forEach(str => width += stringWidth(str)); return width; } function wrap(width, prefix, ...strings) { var target = strings.join(' '); if (getWidth(prefix, target, os_1.EOL) < width) { return [prefix + target]; } else { var words = target.split(/\s/g); target = prefix; var initialWidth = target.length + os_1.EOL.length; for (var idx = 0; idx < words.length; idx++) { var wordLen = getWidth(words[idx]); if (wordLen + initialWidth < width) { target += words[idx] + ' '; initialWidth += wordLen; } else { return [target, words.slice(idx).join(' ')]; } } return [target]; } return [prefix, target]; } function printColumnar(columnCollection, options = { colWidth: 10, leftIndent: defaultLeftIndent, rightIndent: defaultRightIndent }) { if (!columnCollection || !columnCollection.length) return; options = options || {}; options.leftIndent = Number(options.leftIndent || 0); options.leftIndent = isNaN(options.leftIndent || 0) ? 0 : options.leftIndent; var strLeftIndent = options.leftIndent ? ' '.repeat(options.leftIndent) : ''; var strRightIndent = options.rightIndent ? ' '.repeat(options.rightIndent) : ''; options.rightIndent = Number(options.rightIndent || 0); options.rightIndent = isNaN(options.rightIndent) ? 0 : options.rightIndent; options.colWidth = Number(options.colWidth) || 0; var maxStringSize = (process.stdout.columns || 80) - (options.leftIndent + options.rightIndent + 5); var firstColWidth = 0; columnCollection.forEach(pair => { if (pair && pair[0].length > firstColWidth) firstColWidth = pair[0].length; }); if (options.colWidth > firstColWidth) { firstColWidth = options.colWidth; } firstColWidth += options.rightIndent; while (columnCollection.length) { var pair = columnCollection.shift() || []; var firstCol = (pair.shift() || '').trim(); var secondCol = pair.join(' '); var wrapped = wrap(maxStringSize, padString(strLeftIndent + firstCol, firstColWidth) + strRightIndent, secondCol); console.log(wrapped[0]); if (wrapped[1]) { columnCollection.unshift(['', wrapped[1]]); } } } function printProgramInfo(programInfo) { console.log(); console.log(boldText(`${programInfo.name} v${programInfo.version}`)); if (programInfo.help) { console.log(); console.log(programInfo.help); } } function printProgramUsage(config) { console.log(); var label = 'Usage: '; if (settings_1.SettingStore.enableCommands) { console.log(label + config.binaryName + (config.commands.length ? ' <command>' : '') + (config.options.length ? ' [options ...]' : '')); } else { var usage = label + config.binaryName; if (config.params.length) { if (config.params.length == 1) { usage += ' <' + Array.from(config.params.getItems())[0].name + '>'; } else { usage += ' [params ...]'; } } if (config.options.length) { usage += ' [options ...]'; } console.log(usage); } } function printCommandList(config, commands) { console.log(); console.log(underlinedBoldText('Available Commands:')); console.log(); var columnCollection = []; for (var command of commands.getItems()) { columnCollection.push([command.name, command.help]); } printColumnar(columnCollection); } function printOptionList(options) { if (!options.length) return; console.log(); console.log(underlinedBoldText('Options:')); console.log(); var columnCollection = []; for (var option of options.getItems()) { let optionName = []; let otherNames = []; if (Array.isArray(option.aliases) && option.aliases.length) { option.aliases.forEach((name) => { if (name.length == 1) { optionName.push('-' + name); } else { otherNames.push('--' + name); } }); } optionName.push('--' + option.name); columnCollection.push([optionName.join(', '), option.help || 'no help text']); if (otherNames.length) { columnCollection.push(['', boldText('Other Names: ') + otherNames.join(', ')]); } } printColumnar(columnCollection); } function printParamsList(params) { if (!params || !params.length) return; console.log(); console.log(boldText('Parameters:')); console.log(); var columnCollection = []; for (var param of params.getItems()) { var desc = param.help || ''; desc += param.required ? ' ' + boldText('(required)') : ''; columnCollection.push([param.name || '', desc]); if (param.acceptOnly && param.acceptOnly.length) { columnCollection.push(['', boldText('Accepted Values: ') + param.acceptOnly.join(', ')]); } } printColumnar(columnCollection); } function printCommandUsage(config, command) { console.log(); console.log(command.help); var usage = 'Usage: ' + config.binaryName + ' ' + command.name; if (command.params.length) { usage += ' [param ...]'; } if (command.options.length) { usage += ' [options ...]'; } console.log(); console.log(usage); } function programHelp(config) { printProgramInfo(config.toConfig()); printProgramUsage(config); var commandHelpHint = ''; if (settings_1.SettingStore.enableCommands) { if (config.commands.length) { printCommandList(config, config.commands); commandHelpHint = '\nSee command help for more options'; } } else { if (config.params.length) { printParamsList(config.params); } } if (config.options.length) { printOptionList(config.options); } if (commandHelpHint) { console.log(commandHelpHint); } var globalHelp = []; if (settings_1.SettingStore.enableHelpCommand) { globalHelp.push([config.binaryName + ' --help, -h', 'To view help']); if (config.commands.length && settings_1.SettingStore.enableCommands) { globalHelp.push([config.binaryName + ' <command> --help, -h', 'To view command help']); } } if (settings_1.SettingStore.enableVersionOption) { globalHelp.push([config.binaryName + ' --version, -v', 'To view help']); } if (settings_1.SettingStore.enableHelpCommand && settings_1.SettingStore.enableCommands) { globalHelp.push([config.binaryName + ' help', 'To view help']); } if (globalHelp && globalHelp.length) { console.log(); console.log('Other usage:'); console.log(); printColumnar(globalHelp); } } function commandHelp(config, commandName) { if (!commandName) return; var command = config.commands.getByName(commandName); if (!command) { console.log(); console.log('Command "' + boldText(commandName) + '" is not a valid command.'); if (config.commands.length) { printCommandList(config, config.commands); console.log(); console.log(boldText('See command help for more options:')); console.log('\n ' + config.binaryName + ' <command> --help, -h'); } return; } printCommandUsage(config, command); if (command.params.length) { printParamsList(command.params); } if (command.options.length) { printOptionList(command.options); } } function print(config, commandName) { if (!config) throw new runtime_error_1.RuntimeError('Unable to show help. configuration not found'); if (commandName) { if (commandName.toLowerCase() == 'help') { return programHelp(config); } return commandHelp(config, commandName); } else { return programHelp(config); } } function program(config) { print(config); } exports.program = program; function command(config, name) { print(config, name); } exports.command = command; function version(config) { console.log(); console.log(config.name + ' v' + config.version); } exports.version = version; function printInfo(infoType, config, commandName, info, msg) { return __awaiter(this, void 0, void 0, function* () { infoType = infoType == 'param' ? 'Parameter' : 'Option'; if (msg) { console.log(); console.log(boldText(msg)); } console.log(); if (commandName) { console.log('Command Name: ' + boldText(commandName)); } console.log(infoType + ' Name: ' + boldText(info.name + (info.required ? boldText(' (required)') : ''))); if (info.acceptOnly && info.acceptOnly.length) { console.log(); console.log('Following values are allowed: '); console.log(); console.log(info.acceptOnly.join(', ')); } }); } function paramInfo(config, commandName, info, msg) { return printInfo('param', config, commandName, info, msg); } exports.paramInfo = paramInfo; function optionInfo(config, commandName, info, msg) { return printInfo('option', config, commandName, info, msg); } exports.optionInfo = optionInfo;