golangの日記

Go言語を中心にプログラミングについてのブログ

javascript nodejs yargsの使い方

js.png


コマンドラインパーサー yargs の基本的な使い方とサブコマンドの実装。

リポジトリ

ドキュメント





目次



ダウンロード

$ npm i yargs

typescriptの場合は、これもダウンロードしとく
$ npm i @types/yargs --save-dev



ヘルプ

ヘルプとバージョンについて。

const yargs = require('yargs');

yargs
  .scriptName('hello')
  .usage(`Usage: $0 [options]`)
  .version().alias('v', 'version')
  .help().alias('h', 'help')
  .example(`$0 examples`)
  .epilog(`Copyright 2022 $0. All Rights Reserved.`)
  .parse(['-h'])
  • scriptName で名前を付ける。設定しなければファイル名になる。名前は $0 で埋め込むことができる。

  • version は、デフォルトで package.json のバージョンを表示する。オプション名は --version なので -v でもバージョン表示したい場合は .alias('v', 'version') をつける。

  • help のオプション名は --help なので -h でもバージョン表示する場合はこれも .alias('h', 'help') をつける。

  • exampleepilog は勿論必須ではないので必要なければ書かなくていい。

  • parse は引数が空の場合は process.argv をパースする。その場合 .parse() でも .argv でも同じらしい。


出力

Usage: hello [options]

Options:
  -v, --version  Show version number  [boolean]
  -h, --help     Show help            [boolean]

Examples:
  hello examples

Copyright 2022 hello. All Rights Reserved.



オプション

type に指定できるオプションの型 - array - boolean - count - number - string

const argv = yargs
  .option('s', {
    type: 'string',
    alias: 'string',
    requiresArg: true, // 値を必須にする
    // demandOption: true, // オプション自体を必須にする
    describe: 'description'
  })
  .option('n', {
    type: 'number',
    alias: 'number',
    requiresArg: true,
    default: 100, // 初期値の設定
    describe: 'description'
  })
  .option('b', {
    type: 'boolean',
    alias: 'boolean',
    // default: true, // 初期値を true にしても反転するわけではないらしい。
    describe: 'description'
  })
  .option('c', { // $ command -c -c -c とすると 3 になるやつ謎。
    type: 'count',
    alias: 'count',
    describe: 'description'
  })
  .option('a', { // $ command -a foo -a bar -a baz とすると配列 ['foo', 'bar', 'baz']
    type: 'array',
    alias: 'array',
    describe: 'description'
  })
  .option('f', { 
    type: 'string',
    alias: 'foo-bar', // キャメルケース fooBar が増える
    describe: 'description'
  })
  .parse(['-f', '-b', '-s', 'hello']);

// オプションとその値以外の引数
console.log(argv._) // [ 'foo', 'bar', 'baz' ]

パース結果。デフォルトの値を設定してないオプションと指定されなかったオプションは undefined

{
  _: [ 'foo', 'bar', 'baz' ],
  f: '',
  'foo-bar': '',
  fooBar: '',
  b: true,
  boolean: true,
  s: 'hello',
  string: 'hello',
  n: 100,
  number: 100,
  c: 0,
  count: 0,
  '$0': 'hello'
}



エラー

エラー(requiresArg: trueで値を指定してないとか)が発生した場合はエラーメッセージと一緒にヘルプが表示される仕様なので、エラーメッセージのみにしたい場合は .fail を使う。

yargs
  .option('s', {
    type: 'string',
    alias: 'string',
    requiresArg: true,
    describe: 'description'
  })
  .fail((msg, err, yargs) => {
    if (err) throw err;
  });

try {
  const argv = yargs.parse(['-s']);
  console.log(argv);
} catch (e) {
  console.error(`Error: ${e.message}`); // Error: Not enough arguments following: s
  process.exit(1);
}



サブコマンド

git コマンドの addcommit でそれっぽくしたサブコマンドのサンプル。

yargs
  .scriptName('git')
  .usage(`Usage: $0 [options]`)
  .help().alias('h', 'help')
  .version().alias('v', 'version')
  .command('help', 'Show this help')
  .command('version', 'Show version number', yargs => yargs.parse(['--version']))
  .command('add', 'Add file contents to the index', yargs => {
    return yargs
      .usage(`Usage: $0 add [options]`)
      .option('A', {
        alias: 'all',
        type: 'boolean',
        describe: 'Update the index not only where the working tree',
      })
      .version(false)
  })
  .command('commit', 'Record changes to the repository', yargs => {
    return yargs
      .usage(`Usage: $0 commit [options]`)
      .option('m', {
        alias: 'message',
        type: 'string',
        requiresArg: true,
        describe: 'Use the given <msg> as the commit message.'
      })
      .version(false)
  })

const argv = yargs.parse(['commit', '-m', 'Fix bug!']);
console.log(argv); // { _: [ 'commit' ], m: 'Fix bug!', message: 'Fix bug!', '$0': 'git' }

switch (argv._[0]) {
  case 'add':
    console.log('command: add!');
    break;
  case 'commit':
    console.log('command: commit!'); // command: commit!
    break;
}
  • .help().alias('h', 'help') を書いておけばサブコマンドにも--helpオプションが追加される。

  • help と同じで --version や、その他のオプションもサブコマンドに勝手に追加されるので .version(false) とか .hide(key) する。

  • .command('help', 'Show this help') は書かなくても $ command help とするとヘルプが表示される。

ヘルプの出力結果

Usage: git [options]

Commands:
  git help     Show this help
  git version  Show version number
  git add      Add file contents to the index
  git commit   Record changes to the repository

Options:
  -h, --help     Show help            [boolean]
  -v, --version  Show version number  [boolean]

$ git add --help とするとサブコマンドのヘルプが表示される。

Usage: git add [options]

Options:
  -A, --all   Update the index not only where the working tree  [boolean]
  -h, --help  Show help                                         [boolean]