JavaScriptNode.js

commander.jsでコマンド指定がない場合にヘルプを出す

CLIコマンドを作っていると、Serverless FWのようにデフォルトではヘルプを出したい時があります。 commander.jsでやる方法がissueにありましたので、ほぼ自分向けにまとめます。 From: Sh […]

広告ここから
広告ここまで

CLIコマンドを作っていると、Serverless FWのようにデフォルトではヘルプを出したい時があります。

$ sls

Commands
* You can run commands with "serverless" or the shortcut "sls"
* Pass "--verbose" to this command to get in-depth plugin info
* Pass "--help" after any <command> for contextual help

Framework
* Documentation: https://serverless.com/framework/docs/

config ........................ Configure Serverless
config credentials ............ Configures a new provider profile for the Serverless Framework
create ........................ Create new Serverless service

commander.jsでやる方法がissueにありましたので、ほぼ自分向けにまとめます。

From: Show help if no command was executed #7

program.argsのlengthで判定する

slsのようにコマンドがない場合、program.argsが空になります。ということで、ここを使って判定しようという解決策の様子です。

#!/usr/bin/env node

/**
 * Module dependencies.
 */
const program = require('commander')

// バージョン情報
program
  .version('0.0.1', '-v, --version')

program
  .command('exec <cmd>')
  .alias('ex')
  .description('execute the given remote cmd')
  .option("-e, --exec_mode <mode>", "Which exec mode to use")
  .action((cmd, options) => {
    const mode = options.exec_mode || 'default'
    console.log('exec "%s" using %s mode', cmd, mode)
  }).on('--help', function() {
    console.log('  Examples:')
    console.log()
    console.log('    $ deploy exec sequential')
    console.log('    $ deploy exec async')
    console.log()
  })

program.parse(process.argv)


// For default, show help
const NO_COMMAND_SPECIFIED = program.args.length === 0;
if (NO_COMMAND_SPECIFIED) {
  // e.g. display usage
  program.help();
}

これで何もコマンドを渡さない場合はヘルプを出すようになります。

$ ./cli.js 

  Usage: cli [options] [command]

  Options:

    -v, --version            output the version number
    -h, --help               output usage information

  Commands:

    exec|ex [options] <cmd>  execute the given remote cmd

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts