LoginSignup
2
2

More than 5 years have passed since last update.

コマンドライン引数にて、1つのオプションに不定個の値が紐づく場合のパース(Groovy)

Last updated at Posted at 2016-04-20

参考:http://www.javaworld.com/article/2074004/core-java/customizing-groovy-s-clibuilder-usage-statements.html

目的

Groovyでコマンドライン引数をパースする。
一つのオプションに対して、複数の値がある場合に対応したい。
特に、値の個数が不定な場合をなんとかしたい。

手段

CliBuilderを使う。
オプションで値の個数を無制限にする。
値を使う時は、変数名の末尾にsを付ける。

実装

cli.groovy
import org.apache.commons.cli.Option

def cli = new CliBuilder(usage: "groovy cli.groovy [options]")
cli.with {
  h("help")
  l("argument list", args: Option.UNLIMITED_VALUES, valueSeparator: ",", required: true)
}

def options = cli.parse(args)

if(!options) {
  System.exit(255)
}

//受け取ったものを一つだけダンプしてみる
println options.l

//受け取ったものを全部ダンプしてみる(変数名の末尾にsをつければOK)
println options.ls

補足

argsに引数の個数を書く。
通常、argsはint型で具体的な値を記入する(1とか2とか)。
Option.UNLIMITED_VALUES が無制限という意味のスタティック定数。

実行例

groovy cli.groovy -l test,test2,test3
#=> test
#=> [test, test2, test3]

オプション名の後にスペースは何個あっても良い(0個でもOK)

groovy cli.groovy -ltest,test2,test3
groovy cli.groovy -l  test,test2,test3
groovy cli.groovy -l   test,test2,test3
#=> test
#=> [test, test2, test3]

横に長いと辛いなら例えば(※シェルの文法の話ですが)

groovy cli.groovy -l test,\
test2,\
test3,\
test4
#=> test
#=> [test, test2, test3, test4]
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2