目的
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]