-
Notifications
You must be signed in to change notification settings - Fork 0
/
CMDOptionParser.cs
executable file
·119 lines (103 loc) · 3.48 KB
/
CMDOptionParser.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
using System;
using System.Collections.Generic;
namespace ffteq
{
struct CMDParsedOption
{
public CMDOption Opt;
public string[] Args;
public CMDParsedOption(CMDOption opt, string[] args)
{
Opt = opt;
Args = args;
}
}
class CMDOptionParser
{
private CMDOption[] availableOpts;
private string programDesc;
private void PrintOptions()
{
foreach (CMDOption o in availableOpts)
{
Console.Write(o.Name);
foreach (CMDOptionParam a in o.Params)
{
Console.Write(' ');
Console.Write(a.Name);
}
Console.Write('\n');
Console.WriteLine();
Console.WriteLine(o.Description);
Console.WriteLine();
Console.WriteLine();
}
}
private static void PrintParamHelp(CMDOption o, CMDOptionParam p)
{
Console.WriteLine("Option: {0}", o.Name);
Console.WriteLine("Param: {0}", p.Name);
Console.WriteLine(p.Description);
}
public CMDOptionParser(CMDOption[] availableOpts, string programDesc)
{
this.availableOpts = availableOpts;
this.programDesc = programDesc;
}
public void PrintHelp()
{
Console.WriteLine(programDesc);
Console.WriteLine();
PrintOptions();
}
public List<CMDParsedOption> Parse(string[] args)
{
List<CMDParsedOption> parsed = new List<CMDParsedOption>();
for (int i = 0; i < args.Length; i++)
{
string s = args[i];
bool wrongOpt = true;
foreach (CMDOption o in availableOpts)
{
if (s == o.Name)
{
wrongOpt = false;
// Prepare array of args of this option
if (i + o.ParamNum >= args.Length)
{
throw new ApplicationException(String.Format(
"Not enough arguments for option {0}",
o.Name
));
}
string[] oArgs = new string[o.ParamNum];
Array.Copy(args, i + 1, oArgs, 0, o.ParamNum);
// Validate args
for (int j = 0; j < o.ParamNum; j++)
{
if (!o.Params[j].Validate(oArgs[j]))
{
PrintParamHelp(o, o.Params[j]);
throw new ApplicationException(
"Invalid argument"
);
}
}
parsed.Add(new CMDParsedOption(o, oArgs));
// Skip args of this option
i += o.ParamNum;
break;
}
}
if (wrongOpt)
{
throw new ApplicationException(String.Format(
"Unrecognized option: {0}",
s
));
}
}
return parsed;
}
}
}