コマンドラインツールを簡単に作る CLAP

Java の頃は

Commns CLI があったのでコマンドラインツールを作るのにいちいち args をパースするなんて厄介な事はしなくて済んでいたのですが、C# になってからは同じようなものが見つからずせこせこ引数を読み取ったり、メンドイ時は「第一引数は〜、第二引数は〜」みたいな手抜きもやってました。。

CLAP : Command-Line Auto Parser

A Kick-Ass .NET Command-Line Parser と銘打たれたなかなか素敵なライブラリです。
Github adrianaisemberg / CLAP
※最近は C# でも github 多いですね。

using
using CLAP;
using CLAP.Validation;
アプリケーション用のクラスのひな形
class Application {
  [Verb]
  public static void Test(string message) {
    Console.WriteLine("Hello " + message);
  }
}
実行クラス
class Program {
  static void Main(string[] args) {
    Parser<Application>.Run(args);
  }
}
実行

上記をビルドしたバイナリを sample.exe とする。

> sample.exe test -message:World
Hello World

基本はこれでOK。
Verb で指定したメソッド名を第一引数にし、第二引数移行はメソッドの引数をハイフンつけて指定し、値をコロンを挟んで指定する。

スペース含んだ値を指定する時はダブルクォートで囲みます。

> sample.exe test -message:"dany goodby"
Hello dany goodby

型によって若干書き方が変わります。例えば bool なら true/false (or 未指定)や、配列ならカンマ区切りなどです。

二つの引数
class Application {
  [Verb]
  public static void Test(string message) {
    Console.WriteLine("Hello " + message);
  }

  [Verb]
  public static void Sum(int one, int two) {
    Console.WriteLine(ont + two);
  }
}

実行

> sample.exe sum -one:1 -two:2
3
引数にエイリアス・説明を指定
class Application {
  [Verb]
  public static void Test(
    [Parameter(Aliases="m", Description="表示するメッセージ。頭にHello を付けます。")]
    string message) {
    Console.WriteLine("Hello " + message);
  }
}

実行

> sample.exe test -m:"hello howlow"
Hello hello howlow

便利ですね。

デフォルト値
class Application {
  [Verb]
  public static void Test(
    [Parameter(Aliases="m", Description="表示するメッセージ。頭にHello を付けます。"),Default=" World"]
    string message) {
    Console.WriteLine("Hello " + message);
  }
}

実行

> sample.exe test
Hello World

素晴らしい。

必須項目
class Application {
  [Verb]
  public static void Sum(
    [Parameter(Required=true)]
    int one, 
    int two) {
    Console.WriteLine(ont + two);
  }
}

実行

> sample.exe sum -two:2
ハンドルされていない例外: CLAP.MissingRequiredArgumentException: Missing argumen
t for required parameter 'one'
.....

ちゃんとチェックしてくれます。

高度なバリデーション
class Application {
  [Verb]
  public static void Sum(
    [Parameter(Required=true)]
    int one, 
    [MoreThan(10)]
    int two) {
    Console.WriteLine(ont + two);
  }
}

実行

> sample.exe sum -one:1 -two:2
ハンドルされていない例外: CLAP.ValidationException: two: 2 is not more than 3
...

おお、他にも以下がありますみたいです。

  • MoreThan
  • MoreOrEqualTo
  • LessThan
  • LessOrEqualTo
  • RegexMatches
ヘルプの自動生成

これが一番感動しました。

class Application {
  [Empty, Help]
  public static void Help(string help) {
    Console.WriteLine(help);
  }
}

実行

> sample.exe
test:
 -message/m: 表示するメッセージ。頭にHello を付けます。 [String]

sum:
 -one:  [Int32, Required]
 -two:  [Int32, More than 3]

これで引継ぎもばっちりですね!

Github の README や以下の作者のサイトにもっと詳細な解説があるので、使用する際は一読すると良いと思います。というか、このエントリもほぼ似た内容です。