Last active
June 21, 2023 20:42
-
-
Save NotTimTam/e320f51aac584c7126003dc5d38fecf5 to your computer and use it in GitHub Desktop.
Build a command line interface using a commander program.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Builds commands and options for a Commander.js program object using an array of command objects. | |
* @param {Object[]} commands - An array of command objects, where each object represents a command with its options. | |
* @param {string} commands.name - The name of the command. | |
* @param {string} commands.description - The description of the command. | |
* @param {Object[]} commands.options - An array of option objects for the command. | |
* @param {string} commands.options.flags - The flags for the option. | |
* @param {string} commands.options.description - The description of the option. | |
* @param {function} commands.action - The action function for the command. | |
*/ | |
const build_cli = (program, commands) => { | |
try { | |
let usedDefault = false; | |
// Loop through the commands and add them to the program. | |
for (const command of commands) { | |
if (!command.name && usedDefault) | |
throw "You cannot set more than one index command."; | |
else if (!command.name) usedDefault = true; | |
let cmd = ( | |
command.name ? program.command(command.name) : program | |
).description(command.description || "No description provided."); | |
// Add all command options. | |
if (command.options) | |
for (const option of command.options) | |
cmd = cmd.option( | |
option.flags, | |
option.description || "No description provided." | |
); | |
// Add all command arguments. | |
if (command.arguments) | |
for (const argument of command.arguments) | |
cmd = cmd.argument( | |
argument.flags, | |
argument.description || "No description provided." | |
); | |
cmd.action(command.action); | |
} | |
} catch (err) { | |
console.error("ERROR:", err); | |
process.exit(1); | |
} | |
}; | |
module.exports = build_cli; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment