Apache Commons CLI、コマンドライン解析

コマンドラインオプション解析ライブラリの定番ってなんだろう。Commonsブランドを選んでみたが開発状況が微妙。
1.1をつかってみた。

command --limitsize 1000 -n "hoge hage" input.txt output.csv

みたいなコマンドラインを解析してみる。
OptionsオブジェクトにOptionオブジェクトを登録。CommandLineParserにOptionsとString[] argsを渡してCommandLineオブジェクトを得る。

public class ApacheCLITest {
	public static void main(String[] args) {
		// command [opts]... <infile> <outfile> 
		Option opt_limitsize=OptionBuilder.
			withLongOpt("limitsize"). //長いオプション。--limitsize
			withDescription("max size of output file"). //オプションの説明
			hasArg(). //このオプションは引数を一つとる。hasArgs()やhasArgs(int num)で複数とることも可能
			withArgName("size"). //引数の名前
			create(); //インスタンス作成
		Option opt_name=OptionBuilder.
			withLongOpt("name"). //--name
			withDescription("your name").
			isRequired(). //オプションを指定しなかったらエラーになる
			hasArg().
			withArgName("name").
			create('n'); //短いオプションの名前(-n)を指定してインスタンス作成
		Options opts=new Options();
		opts. //オプション登録
			addOption(opt_limitsize).
			addOption(opt_name);

		//usageを表示してみる
		HelpFormatter hf=new HelpFormatter();
		hf.printHelp("hoge [opts] <infile> <outfile>",opts);

		//パーサはGnuParserのほかにもPosixParser,BasicParserがある。
		//オプション引数の解析方法が違う。GnuParserだと --option arg 、PosixParserだと --option=arg 、BasicParserは知らない
		CommandLineParser parser=new GnuParser();
		CommandLine cl=null;
		try {
			cl=parser.parse(opts, new String[]{
					"--limitsize","1000",
					"-n","hoge hage",
					"input.txt",
					"output.csv"
				},true); //第三引数をtrueにすると不明なオプションが出てきた時点で解析を終了する。
				//以降のパラメータはgetArgs()で取得可能。

		} catch(ParseException e) { //MissingArgumentExceptionとかMissingOptionExceptionとか飛んでくる
			e.printStackTrace(); //実際にはusage表示するなり不正なオプションについて指摘するなり(後者のほうが親切)
			return;
		}
		System.out.println(cl.hasOption("limitsize"));
		System.out.println(cl.getOptionValue("limitsize","100")); //デフォルト値を指定してオプション取得
		System.out.println(cl.getOptionValue("name"));
		System.out.println(cl.getArgs()[0]);
		System.out.println(cl.getArgs()[1]);
	}
}
usage: hoge [opts] <infile> <outfile>
    --limitsize <size>   max size of output file
 -n,--name <name>        your name
true
1000
hoge hage
input.txt
output.csv

usageを自動生成してくれるのがいかす。
同じオプションが重複したときエラーにするにはどうするんだろうとかOption#setType/CommandLine#getOptionObjectあたりどう使えばいいんだろうとか(ソース読んでない)わかんないけど、まあ便利そうですね。

ref