UNPKG

tiny-bin

Version:

A library for building tiny and beautiful command line apps.

71 lines (70 loc) 2.65 kB
/* IMPORT */ import getCurrentPackage from 'get-current-package'; import process from 'node:process'; import colors from 'tiny-colors'; import CommandDefault from './command_default.js'; import CommandHelp from './command_help.js'; import CommandVersion from './command_version.js'; import Commands from './commands.js'; import Config from './config.js'; import Logger from './logger.js'; import Option from './option.js'; import { parseArgv } from './utils.js'; /* MAIN */ class Bin { /* CONSTRUCTOR */ constructor(options) { /* VARIABLES */ this.stdout = new Logger(this, console.log); this.stderr = new Logger(this, console.error); this.config = new Config(this); this.commands = new Commands(this); this.config.name = options.name ?? this.config.name; this.config.description = options.description ?? this.config.description; const fallback = new CommandDefault(this); const help = new CommandHelp(this); const version = new CommandVersion(this); this.commands.register(fallback); this.commands.register(help); this.commands.register(version); this.command = fallback; this.command.options.register(new Option(this, { name: '--help', description: 'Display help for the command' })); this.command.options.register(new Option(this, { name: '--version, -v', description: 'Display the version number' })); this.command.options.register(new Option(this, { name: '--no-color, --no-colors', description: 'Disable colored output', hidden: true })); } /* API */ fail(message) { this.stderr.print(); this.stderr.indent(); this.stderr.print(colors.red(message)); this.stderr.dedent(); this.stderr.print(); process.exit(1); } async run(argv = process.argv.slice(2)) { var _a, _b; if (!this.config.package || !this.config.version) { const pkg = getCurrentPackage(); if (pkg) { const { name, version } = pkg; (_a = this.config).package || (_a.package = name); (_b = this.config).version || (_b.version = version); } } try { const options = parseArgv(argv); await this.commands.run(this.command.name, options, argv); if (this.config.autoExit) { process.exit(); } } catch (error) { console.error(error); if (this.config.autoExit) { process.exit(1); } } } } /* EXPORT */ export default Bin;