using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace AppliStation
{
///
/// 低機能な引数解析をする。
///
public class ArgParse
{
///
/// 解析結果
///
private Dictionary opts;
///
/// 解析結果をハッシュ辞書として取得
///
public Dictionary Opts {
get {
lock (opts) {
return opts;
}
}
}
public ArgParse()
: this(new Dictionary())
{
}
///
/// 初期化
///
/// 初期の辞書
public ArgParse(Dictionary hashDefault)
{
opts = hashDefault;
}
///
/// ハッシュの中身を設定あるいは取得する。
///
public object this[string key] {
set {
lock(opts) {
opts[key] = value;
}
}
get {
lock(opts) {
return opts[key];
}
}
}
///
/// 引数を解析する
///
/// 対象引数
/// 残った(オプションではない)引数
public string[] Parse(string[] args)
{
List rest = new List();
lock (opts) {
bool disableOptionParse = false;
for (int i = 0; i < args.Length; i++) {
if (disableOptionParse || !args[i].StartsWith("-")) {
rest.Add(args[i]);
} else {
if (args[i].StartsWith("-")) {
if (args[i] == "--") {
// オプション解析中断
disableOptionParse = true;
} else {
parseOption(args[i]);
}
}
}
}
}
return rest.ToArray();
}
///
/// オプショントークンの解析
///
///
private void parseOption(string option)
{
Match match = Regex.Match(option, "^--?([^=]+)(=\"?(.+)\"?)?$");
if (match.Success) {
string key = match.Groups[1].Value;
string val = match.Groups[3].Value;
if (opts.ContainsKey(key)) { // 登録結果に入っていること
object origVal = opts[key];
try {
if (origVal is bool) {
opts[key] = val.ToLower() != "no";
} else if (origVal is int) {
opts[key] = int.Parse(val);
} else /* if (origVal is string) */ {
opts[key] = val;
}
} catch (FormatException) {
throw new ApplicationException(string.Format("Illegal Format For {0}", key));
}
} else {
throw new ApplicationException(string.Format("Undefined option: {0}", key));
}
}
}
}
}