2015年11月29日日曜日

Sample code like GetOpt for C#

Sample code like GetOpt for C#

---- GetOpt.cs ----

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetOptForConsole
{
    using GetOptDic = System.Collections.Generic.Dictionary<String, Object>;
    using GetOptList = System.Collections.Specialized.StringCollection;

    /// <summary>
    /// Analyze argument class.
    /// </summary>
    /// <example>
    /// src1 /MAT dir1\dir2\mat.txt src2 /material dir2\dir3\mat.txt /omi abc /dmy def src3 src4
    /// /MAT and /material : set to the same variable.
    /// </example>
    /// <code>
    /// string materialFile;
    /// var opt = new GetOpt();
    /// opt.Add("/MAT", c => materialFile = c);
    /// opt.Add("/material", c => materialFile = c);
    /// opt.Add("/omi", "");
    /// opt.Run(args);
    /// string omi = opt["/omi"];
    /// string mat = opt["/MAT"];    // throw ArgumentException
    ///
    /// string [] newArgs = opt.Args.ToString();
    /// --- OR ---
    /// foreach(string a in opt.Args) {
    ///     ...
    /// }
    /// --- OR ---
    /// if (opt.Args.Count >= 1) source1 = opt.Args[0];
    /// if (opt.Args.Count >= 2) source2 = opt.Args[1];
    /// </code>
    class GetOpt
    {
        /// <summary>
        /// Store option arguments.
        /// </summary>
        private GetOptDic mOptions = new GetOptDic();
        /// <summary>
        /// Store non option arguments.
        /// </summary>
        private GetOptList mArgs = new GetOptList();

        public GetOpt() { }
        public GetOpt(GetOpt iOriginal) { this.mOptions.Concat(iOriginal.mOptions); }

        /// <summary>
        /// Regist option argument (if action).
        /// </summary>
        /// <param name="iKey">Option name. (ex: /MAT)</param>
        /// <param name="iValue">Action. (ex: (Action \lt string \gt )(c => { materialPath = c; }) )</param>
        public void Add(string iKey, Action<string> iValue) { this.mOptions.Add(iKey, iValue); }
        /// <summary>
        /// Regist option argument (if string).
        /// </summary>
        /// <param name="iKey">Option name. (ex: /MAT)</param>
        /// <param name="iValue">Initial value. default is <seealso cref="String.Empty"/> 。</param>
        public void Add(string iKey, string iValue = "") { this.mOptions.Add(iKey, iValue); }
        /// <summary>
        /// Get option value. (if string)
        /// </summary>
        /// <param name="iKey">Option name. (ex: /MAT)</param>
        /// <returns>Option value. </returns>
        /// <exception cref="ArgumentException">Illigal argument. the value is action. </exception>
        public string this[string iKey]
        {
            get
            {
                object val = this.mOptions[iKey];
                if (val is string)
                {
                    // unboxing.
                    return (string)val;
                }
                else
                {
                    throw new ArgumentException(message: "Illigal argument. the value is action.", paramName: "iKey");
                }
            }
        }
        /// <summary>
        /// Get the collection of non option value.
        /// </summary>
        public System.Collections.Specialized.StringCollection Args
        {
            get
            {
                return mArgs;
            }
        }
        /// <summary>
        /// Analyze argument.
        /// </summary>
        /// <param name="args">Arguments. </param>
        public void Run(string[] args)
        {
            string curOption = "";
            foreach (string curArg in args)
            {
                if (curOption != "")
                {
                    if (this.mOptions[curOption] is string)
                    {
                        this.mOptions[curOption] = curArg;
                    }
                    else if (this.mOptions[curOption] is Action<string>)
                    {
                        var action = (Action<string>)this.mOptions[curOption];
                        action(curArg);
                    }
                    curOption = "";
                }
                else if (this.mOptions.ContainsKey(curArg))
                {
                    curOption = curArg;
                }
                else
                {
                    mArgs.Add(curArg);
                }

            }
        }
    }

    class SampleOfGetOpt
    {
        public static void SampleMain()
        {
            var originalArgs = new string[] { @"src1", @"/MAT", @"dir1\dir2\mat.txt", @"src2", @"/material", @"dir2\dir3\mat.txt", @"/omi", @"abc", @"/dmy", @"def", @"src3", @"src4" };

            string materialFile = "";
            var opt = new GetOpt();
            opt.Add("/MAT", c => materialFile = c);
            opt.Add("/material", c => materialFile = c);
            opt.Add("/omi", "");
            opt.Add("/dmy", "");
            opt.Run(originalArgs);

            Console.WriteLine("materialFile=[" + materialFile + "]");

            string omi = opt["/omi"];
            Console.WriteLine("/omi=[" + omi + "]");

            string dmy = opt["/dmy"];
            Console.WriteLine("/dmy=[" + dmy + "]");

            string mat = "";
            try
            {
                mat = opt["/MAT"];    // throw ArgumentException
                Console.WriteLine("/MAT=[" + mat + "]");
            }
            catch (Exception e)
            {
                Console.WriteLine("/MAT=[[" + e.ToString() + "]]");
            }

            foreach (string a in opt.Args)
            {
                Console.WriteLine("opt.Args=[" + a + "]");
            }
        }
    }
}



0 件のコメント:

コメントを投稿