UNPKG

adba

Version:
70 lines (69 loc) 2.76 kB
#!/usr/bin/env node 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()); }); }; require('dotenv').config(); import fs from 'fs'; import path from 'path'; import yargs from 'yargs'; import { hideBin } from 'yargs/helpers'; import { resolveRefs } from 'dbl-utils'; import * as pkg from './index'; const cli = yargs(hideBin(process.argv)); /** * Parse a CLI argument. If the argument is a path to a JSON file, the file is * loaded and JSON references are resolved. Otherwise the raw value is returned. * * @param value - Raw argument value. * @returns Parsed value. */ function parseInput(value) { if (typeof value !== 'string') return value; let content = value; if (fs.existsSync(value)) { content = fs.readFileSync(value, 'utf8'); } try { const json = JSON.parse(content); return resolveRefs(json, { env: process.env }); } catch (_a) { return value; } } for (const name of Object.keys(pkg)) { const fn = pkg[name]; if (typeof fn !== 'function') continue; const cmdPath = path.join(__dirname, 'commands', `${name}.js`); if (fs.existsSync(cmdPath)) { const mod = require(cmdPath); const describe = mod.describe || `Run ${name}`; const builder = typeof mod.builder === 'function' ? mod.builder : (y) => y; const handler = mod.handler || mod.main; if (typeof handler === 'function') { cli.command(name, describe, builder, handler); } } else { cli.command(name + ' [args..]', `Run the function ${name}`, y => y.positional('args', { type: 'string', array: true }), (argv) => __awaiter(void 0, void 0, void 0, function* () { const raw = (argv.args || []); const args = raw.map(a => parseInput(a)); const result = yield Promise.resolve(fn(...args)); if (result !== undefined) { if (typeof result === 'string') console.log(result); else console.log(JSON.stringify(result, null, 2)); } })); } } cli.demandCommand(1).help().argv;