一、commander

#!/usr/bin/env node
const program = require('commander');
const colors  = require('colors');
const pkg = require('./package.json');
function range(val, d) {
    return val.split('..').map(Number);
  }
   
  function list(val) {
    return val.split(',');
  }
   
  function collect(val, memo) {
    memo.push(val);
    return memo;
  }
   
  function increaseVerbosity(v, total) {
    return total + 1;
  }
program
    .version(pkg.version, '-v, --version')
    .option('-u, --username <firstname>', 'add username')
    .option('-p, --password [num]', 'add password')
    .option('--no-sauce', 'Remove sauce')

    // .option('-i, --integer <n>', 'An integer argument', parseInt)
    .option('-f, --float <n>', 'A float argument', parseFloat)
    .option('-r, --range [a..b]', 'A range', range, 12)
    .option('-l, --list <items>', 'A list', list)
    .option('-o, --optional [value]', 'An optional value')
    .option('-c, --collect [value]', 'A repeatable value', collect, [])
    .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
 


program
    .command('create <project> [rest...]')
    .alias('init')
    .description('ssy cli description')
    .option('-i, --information [info]', 'add information')
    .action((projectName, cmd, options)=>{
        console.log("ssy",projectName, cmd, options.information)
    })

if (!process.argv.slice(2).length) {
    program.outputHelp(make_red);
}
       
function make_red(txt) {
    return colors.red(txt); //display the help text in red on the console
}
// must be before .parse() since
// node's emit() is immediate
program.on('--help', function(){
    console.log('')
    console.log('Examples:');
    console.log('  $ ssy --help');
    console.log('  $ ssy -h');
});
program.parse(process.argv);
// console.log(program);

 

posted @ 2019-03-09 17:09  shangyueyue  阅读(300)  评论(0编辑  收藏  举报