mini-commander

a single-file helper for making simple cli tools in nodejs
git clone https://github.com/TanguyAndreani/mini-commander
Log | Files | Refs | README

mini-commander.js (1653B)


      1 const util = require('util');
      2 
      3 const Commander = {
      4 
      5 
      6     /* PRIVATE ATTRIBUTES */
      7 
      8     command_object: {
      9         alias(s) {
     10             this.alias = s
     11             return (this)
     12         },
     13         description(s) {
     14             this.description = s
     15             return (this)
     16         },
     17         action(fn) {
     18             this.action = fn
     19             return (this)
     20         }
     21     },
     22 
     23     /* list of command_objects */
     24     commands: [],
     25 
     26 
     27     /* PUBLIC INTERFACE */
     28 
     29     command(name) {
     30         var c = Object.create(this.command_object)
     31         c.name = name
     32         this.commands.push(c)
     33         return (c)
     34     },
     35 
     36     usage() {
     37         if (this.name) {
     38             console.log("NAME")
     39             console.log("\t" + this.name + '\n')
     40         }
     41 
     42         if (this.description) {
     43             console.log("DESCRIPTION")
     44             console.log("\t" + this.description + '\n')
     45         }
     46 
     47         if (this.command) {
     48             console.log("COMMANDS")
     49             for (let command of this.commands) {
     50                 console.log(util.format('\t%s (%s)\t%s',
     51                                                         command.name,
     52                                                         command.alias,
     53                                                         command.description))
     54             }
     55         } else {
     56             console.log("Add some commands!")
     57         }
     58     },
     59 
     60     parse(av) {
     61         for (let command of this.commands) {
     62             if (command.name == av[2] || command.alias == av[2]) {
     63                 command.action(av)
     64                 return;
     65             }
     66         }
     67         this.usage()
     68         process.exit(1)
     69     }
     70 }
     71 
     72 module.exports = Commander