-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandLineOption.cs
More file actions
386 lines (348 loc) · 10 KB
/
CommandLineOption.cs
File metadata and controls
386 lines (348 loc) · 10 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
// File: CommandLineOptions.cs
//
// This is a re-usable component to be used when you
// need to parse command-line options/parameters.
//
// Separates command line parameters from command line options.
// Uses reflection to populate member variables the derived class with the values
// of the options.
//
// An option can start with "-" or "--". On Windows systems, it can start with "/" as well.
//
// I define 3 types of "options":
// 1. Boolean options (yes/no values), e.g: /r to recurse
// 2. Value options, e.g: /loglevel=3
// 2. Parameters: standalone strings like file names
//
// An example to explain:
// csc /nologo /t:exe myfile.cs
// | | |
// | | + parameter
// | |
// | + value option
// |
// + boolean option
//
// Please see a short description of the CommandLineOptions class
// at http://codeblast.com/~gert/dotnet/sells.html
//
// Gert Lombard (gert@codeblast.com)
// James Newkirk (jim@nunit.org)
using System;
using System.Reflection;
using System.Collections;
using System.Text;
namespace Codeblast
{
//
// The Attributes
//
[AttributeUsage(AttributeTargets.Field)]
public class OptionAttribute : Attribute
{
protected object optValue;
protected string optName;
protected string description;
protected bool mandatory = false;
public string Alias
{
get { return optName; }
set { optName = value; }
}
public object Value
{
get { return optValue; }
set { optValue = value; }
}
public string Description
{
get { return description; }
set { description = value; }
}
public bool Mandatory
{
get { return mandatory; }
set { mandatory = value; }
}
}
//
// The CommandLineOptions members
//
public abstract class CommandLineOptions
{
protected ArrayList parameters;
protected bool isInvalid = false;
private int optionCount;
private ArrayList invalidArguments = new ArrayList();
private bool allowForwardSlash;
public CommandLineOptions( string[] args )
: this( System.IO.Path.DirectorySeparatorChar != '/', args ) {}
public CommandLineOptions( bool allowForwardSlash, string[] args )
{
this.allowForwardSlash = allowForwardSlash;
optionCount = Init( args );
if ( MissingMandatoryOption() )
{
isInvalid = true;
}
}
public bool MissingMandatoryOption()
{
Type t = this.GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.Instance|BindingFlags.Public);
foreach (FieldInfo field in fields)
{
OptionAttribute[] atts = (OptionAttribute[])field.GetCustomAttributes(typeof(OptionAttribute), true);
foreach(OptionAttribute a in atts) {
if ( a.Mandatory && field.GetValue(this) == null) {
InvalidOption(field.Name);
return true;
}
}
}
return false;
}
public IList InvalidArguments
{
get { return invalidArguments; }
}
public bool NoArgs
{
get
{
return ParameterCount == 0 && optionCount == 0;
}
}
public bool AllowForwardSlash
{
get { return allowForwardSlash; }
}
public int Init(params string[] args)
{
int count = 0;
int n = 0;
while (n < args.Length)
{
int pos = IsOption(args[n]);
if (pos > 0)
{
// It's an option:
if (GetOption(args, ref n, pos))
count++;
else
InvalidOption(args[Math.Min(n, args.Length-1)]);
}
else
{
if (parameters == null) parameters = new ArrayList();
parameters.Add(args[n]);
if ( !IsValidParameter(args[n]) )
InvalidOption( args[n] );
}
n++;
}
return count;
}
// An option starts with "/", "-" or "--":
protected virtual int IsOption(string opt)
{
char[] c = null;
if (opt.Length < 2)
{
return 0;
}
else if (opt.Length > 2)
{
c = opt.ToCharArray(0, 3);
if (c[0] == '-' && c[1] == '-' && IsOptionNameChar(c[2])) return 2;
}
else
{
c = opt.ToCharArray(0, 2);
}
if ((c[0] == '-' || c[0] == '/' && AllowForwardSlash) && IsOptionNameChar(c[1])) return 1;
return 0;
}
protected virtual bool IsOptionNameChar(char c)
{
return Char.IsLetterOrDigit(c) || c == '?';
}
protected virtual void InvalidOption(string name)
{
invalidArguments.Add( name );
isInvalid = true;
}
protected virtual bool IsValidParameter(string param)
{
return true;
}
protected virtual bool MatchAlias(FieldInfo field, string name)
{
object[] atts = (object[])field.GetCustomAttributes(typeof(OptionAttribute), true);
foreach (OptionAttribute att in atts)
{
if (string.Compare(att.Alias, name, true) == 0) return true;
}
return false;
}
protected virtual FieldInfo GetMemberField(string name)
{
Type t = this.GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.Instance|BindingFlags.Public);
FieldInfo myField = null;
int matchcount = 0;
foreach (FieldInfo field in fields)
{
// if (string.Compare(field.Name, name, true) >= 0)
if ( field.Name.IndexOf(name, StringComparison.CurrentCultureIgnoreCase) == 0 )
{
matchcount++;
myField = field;
}
if (MatchAlias(field, name)) return field;
}
if ( matchcount == 1 )
{
return myField;
}
else {
Console.WriteLine("Matchcount = {0}", matchcount);
}
return null;
}
protected virtual object GetOptionValue(FieldInfo field)
{
object[] atts = (object[])field.GetCustomAttributes(typeof(OptionAttribute), true);
if (atts.Length > 0)
{
OptionAttribute att = (OptionAttribute)atts[0];
return att.Value;
}
return null;
}
protected virtual bool GetOption(string[] args, ref int index, int pos)
{
try
{
object cmdLineVal = null;
string opt = args[index].Substring(pos, args[index].Length-pos);
SplitOptionAndValue(ref opt, ref cmdLineVal);
FieldInfo field = GetMemberField(opt);
if (field != null)
{
object value = GetOptionValue(field);
if (value == null)
{
if (field.FieldType == typeof(bool))
value = true; // default for bool values is true
else if(field.FieldType == typeof(string))
{
value = cmdLineVal != null ? cmdLineVal : args[++index];
field.SetValue(this, Convert.ChangeType(value, field.FieldType));
string stringValue = (string)value;
if(stringValue == null || stringValue.Length == 0) return false;
return true;
}
else if(field.FieldType == typeof(string[]))
{
value = cmdLineVal != null ? cmdLineVal : args[++index];
//ArrayList al = new ArrayList();
//foreach(string s in ((string)value).Split(','))
//{
//al.Add(s.Trim());
//}
string[] sa = ((string)value).Split(',');
string[] trimmed = new string[sa.Length];
for(int i = 0; i < sa.Length; i++) {
trimmed[i] = sa[i].Trim();
}
field.SetValue(this, trimmed);
return true;
}
// JWT
else if(field.FieldType.GetTypeInfo().IsEnum) {
cmdLineVal = cmdLineVal != null ? cmdLineVal : args[++index];
value = Enum.Parse( field.FieldType, (string)cmdLineVal, true );
}
else
value = cmdLineVal != null ? cmdLineVal : args[++index];
}
field.SetValue(this, Convert.ChangeType(value, field.FieldType));
return true;
}
}
catch (Exception)
{
// Ignore exceptions like type conversion errors.
}
return false;
}
protected virtual void SplitOptionAndValue(ref string opt, ref object val)
{
// Look for ":" or "=" separator in the option:
int pos = opt.IndexOfAny( new char[] { ':', '=' } );
if (pos < 1) return;
val = opt.Substring(pos+1);
opt = opt.Substring(0, pos);
}
// Parameter accessor:
public string this[int index]
{
get
{
if (parameters != null) return (string)parameters[index];
return null;
}
}
public ArrayList Parameters
{
get { return parameters; }
}
public int ParameterCount
{
get
{
return parameters == null ? 0 : parameters.Count;
}
}
public virtual void Help()
{
Console.WriteLine(GetHelpText());
}
public virtual string GetHelpText()
{
StringBuilder helpText = new StringBuilder();
Type t = this.GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.Instance|BindingFlags.Public);
char optChar = allowForwardSlash ? '/' : '-';
foreach (FieldInfo field in fields)
{
object[] atts = (object[])field.GetCustomAttributes(typeof(OptionAttribute), true);
if (atts.Length > 0)
{
OptionAttribute att = (OptionAttribute)atts[0];
if (att.Description != null)
{
string valType = "";
if (att.Value == null)
{
if (field.FieldType == typeof(float)) valType = "=FLOAT";
else if (field.FieldType == typeof(string)) valType = "=STR";
else if (field.FieldType != typeof(bool)) valType = "=X";
}
if (att.Mandatory) {
helpText.AppendFormat("{0}{1,-20}\t{2} (Mandatory)", optChar, field.Name+valType, att.Description);
}
else {
helpText.AppendFormat("{0}{1,-20}\t{2}", optChar, field.Name+valType, att.Description);
}
if (att.Alias != null)
helpText.AppendFormat(" (Alias format: {0}{1}{2})", optChar, att.Alias, valType);
helpText.Append( Environment.NewLine );
}
}
}
return helpText.ToString();
}
}
}