const fs = require('fs') const path = require('path') const utils = require('./utils') const default_options = { '-v': 'Verbose output level=debug.', '-vv': 'Verbose output level=trace.' } function printCommandUsage(command) { if(command.name === '?' || command.name === 'help') { return } console.log(`\n[${command.name}]\n${command.description || ''}`) if(command.usage && command.usage.options) { Object.entries(command.usage.options) .forEach(entry => console.log(`\t ${utils.formatColumns(entry[0], entry[1], 48, '.')}`)) } } function printCompleteUsage(commands) { Object.values(commands).sort((a, b) => a.name.localeCompare(b.name)).forEach(printCommandUsage) } function load() { let commands = fs.readdirSync(path.join(__dirname, 'cmd')) .filter(file => file.startsWith("cmd")) .reduce((result, item) => { let name = item.replace(/^cmd\./, '').replace(/\.js$/, ''); let command_path = path.join(__dirname, 'cmd', item); let command = require(command_path) command.name = result.name || name command.usage = command.usage || {} command.usage.options = command.usage.options || {} command.usage.options = { ...command.usage.options, ... default_options } command.printUsage = () => printCommandUsage(command) let run_command = command.run command.run = (args) => { if(args['?'] || args.help) { printCommandUsage(command) return } return run_command(args) } result[name] = command return result }, {}) commands.help = { name: 'help', run: () => printCompleteUsage(commands) } commands['?'] = { name: '?', run: () => printCompleteUsage(commands) } return commands } module.exports.load = load