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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
|
//
// OptionList.cs
//
// Author: Rafael Teixeira (rafaelteixeirabr@hotmail.com)
//
// (C) 2002 Rafael Teixeira
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Text;
namespace Mono.GetOptions
{
[Flags]
public enum OptionsParsingMode
{
Linux = 1,
Windows = 2,
Both = 3
}
/// <summary>
/// Option Parsing
/// </summary>
public class OptionList
{
private Options optionBundle = null;
private OptionsParsingMode parsingMode;
private bool breakSingleDashManyLettersIntoManyOptions;
private bool endOptionProcessingWithDoubleDash;
private string appExeName;
private string appVersion;
private string appTitle = "Add a [assembly: AssemblyTitle(\"Here goes the application name\")] to your assembly";
private string appCopyright = "Add a [assembly: AssemblyCopyright(\"(c)200n Here goes the copyright holder name\")] to your assembly";
private string appDescription = "Add a [assembly: AssemblyDescription(\"Here goes the short description\")] to your assembly";
private string appAboutDetails = "Add a [assembly: Mono.About(\"Here goes the short about details\")] to your assembly";
private string appUsageComplement = "Add a [assembly: Mono.UsageComplement(\"Here goes the usage clause complement\")] to your assembly";
private string[] appAuthors;
private ArrayList list = new ArrayList();
private ArrayList arguments = new ArrayList();
private ArrayList argumentsTail = new ArrayList();
private MethodInfo argumentProcessor = null;
internal bool MaybeAnOption(string arg)
{
return ((parsingMode & OptionsParsingMode.Windows) > 0 && arg[0] == '/') ||
((parsingMode & OptionsParsingMode.Linux) > 0 && arg[0] == '-');
}
public string Usage
{
get
{
return "Usage: " + appExeName + " [options] " + appUsageComplement;
}
}
public string AboutDetails
{
get
{
return appAboutDetails;
}
}
#region Assembly Attributes
Assembly entry;
private object[] GetAssemblyAttributes(Type type)
{
return entry.GetCustomAttributes(type, false);
}
private string[] GetAssemblyAttributeStrings(Type type)
{
object[] result = GetAssemblyAttributes(type);
if ((result == null) || (result.Length == 0))
return new string[0];
int i = 0;
string[] var = new string[result.Length];
foreach(object o in result)
var[i++] = o.ToString();
return var;
}
private void GetAssemblyAttributeValue(Type type, string propertyName, ref string var)
{
object[] result = GetAssemblyAttributes(type);
if ((result != null) && (result.Length > 0))
var = (string)type.InvokeMember(propertyName, BindingFlags.Public | BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Instance, null, result[0], new object [] {}); ;
}
private void GetAssemblyAttributeValue(Type type, ref string var)
{
object[] result = GetAssemblyAttributes(type);
if ((result != null) && (result.Length > 0))
var = result[0].ToString();
}
#endregion
#region Constructors
private void AddArgumentProcessor(MemberInfo memberInfo)
{
if (argumentProcessor != null)
throw new NotSupportedException("More than one argument processor method found");
if ((memberInfo.MemberType == MemberTypes.Method && memberInfo is MethodInfo))
{
if (((MethodInfo)memberInfo).ReturnType.FullName != typeof(void).FullName)
throw new NotSupportedException("Argument processor method must return 'void'");
ParameterInfo[] parameters = ((MethodInfo)memberInfo).GetParameters();
if ((parameters == null) || (parameters.Length != 1) || (parameters[0].ParameterType.FullName != typeof(string).FullName))
throw new NotSupportedException("Argument processor method must have a string parameter");
argumentProcessor = (MethodInfo)memberInfo;
}
else
throw new NotSupportedException("Argument processor marked member isn't a method");
}
private void Initialize(Options optionBundle)
{
if (optionBundle == null)
throw new ArgumentNullException("optionBundle");
entry = Assembly.GetEntryAssembly();
appExeName = entry.GetName().Name;
appVersion = entry.GetName().Version.ToString();
this.optionBundle = optionBundle;
this.parsingMode = optionBundle.ParsingMode ;
this.breakSingleDashManyLettersIntoManyOptions = optionBundle.BreakSingleDashManyLettersIntoManyOptions;
this.endOptionProcessingWithDoubleDash = optionBundle.EndOptionProcessingWithDoubleDash;
GetAssemblyAttributeValue(typeof(AssemblyTitleAttribute), "Title", ref appTitle);
GetAssemblyAttributeValue(typeof(AssemblyCopyrightAttribute), "Copyright", ref appCopyright);
GetAssemblyAttributeValue(typeof(AssemblyDescriptionAttribute), "Description", ref appDescription);
GetAssemblyAttributeValue(typeof(Mono.AboutAttribute), ref appAboutDetails);
GetAssemblyAttributeValue(typeof(Mono.UsageComplementAttribute), ref appUsageComplement);
appAuthors = GetAssemblyAttributeStrings(typeof(AuthorAttribute));
if (appAuthors.Length == 0)
{
appAuthors = new String[1];
appAuthors[0] = "Add one or more [assembly: Mono.GetOptions.Author(\"Here goes the author name\")] to your assembly";
}
foreach(MemberInfo mi in optionBundle.GetType().GetMembers())
{
object[] attribs = mi.GetCustomAttributes(typeof(OptionAttribute), true);
if (attribs != null && attribs.Length > 0)
list.Add(new OptionDetails(mi, (OptionAttribute)attribs[0], optionBundle));
else
{
attribs = mi.GetCustomAttributes(typeof(ArgumentProcessorAttribute), true);
if (attribs != null && attribs.Length > 0)
AddArgumentProcessor(mi);
}
}
}
public OptionList(Options optionBundle)
{
Initialize(optionBundle);
}
#endregion
#region Prebuilt Options
private void ShowTitleLines()
{
Console.WriteLine(appTitle + " " + appVersion + " - " + appCopyright);
Console.WriteLine(appDescription);
Console.WriteLine();
}
private void ShowAbout()
{
ShowTitleLines();
Console.WriteLine(appAboutDetails);
StringBuilder sb = new StringBuilder("Authors: ");
bool first = true;
foreach(string s in appAuthors)
{
if (first)
first = false;
else
sb.Append(", ");
sb.Append(s);
}
Console.WriteLine(sb.ToString());
}
private void ShowHelp()
{
ShowTitleLines();
Console.WriteLine(Usage);
Console.WriteLine("Options:");
foreach (OptionDetails option in list)
Console.WriteLine(option);
}
private void ShowUsage()
{
Console.WriteLine(Usage);
Console.Write("Short Options: ");
foreach (OptionDetails option in list)
Console.Write(option.ShortForm.Trim());
Console.WriteLine();
}
private void ShowUsage(string errorMessage)
{
Console.WriteLine("ERROR: " + errorMessage.TrimEnd());
ShowUsage();
}
internal WhatToDoNext DoUsage()
{
ShowUsage();
return WhatToDoNext.AbandonProgram;
}
internal WhatToDoNext DoAbout()
{
ShowAbout();
return WhatToDoNext.AbandonProgram;
}
internal WhatToDoNext DoHelp()
{
ShowHelp();
return WhatToDoNext.AbandonProgram;
}
#endregion
#region Arguments Processing
public string[] ExpandResponseFiles(string[] args)
{
ArrayList result = new ArrayList();
foreach(string arg in args)
{
if (arg.StartsWith("@"))
{
try
{
StreamReader tr = new StreamReader(arg.Substring(1));
string line;
while ((line = tr.ReadLine()) != null)
{
result.AddRange(line.Split());
}
tr.Close();
}
catch (FileNotFoundException exception)
{
Console.WriteLine("Could not find response file: " + arg.Substring(1));
continue;
}
catch (Exception exception)
{
Console.WriteLine("Error trying to read response file: " + arg.Substring(1));
Console.WriteLine(exception.Message);
continue;
}
}
else
result.Add(arg);
}
return (string[])result.ToArray(typeof(string));
}
public string[] NormalizeArgs(string[] args)
{
bool ParsingOptions = true;
ArrayList result = new ArrayList();
foreach(string arg in ExpandResponseFiles(args))
{
if (arg.Length > 0)
{
if (ParsingOptions)
{
if (endOptionProcessingWithDoubleDash && (arg == "--"))
{
ParsingOptions = false;
continue;
}
if ((parsingMode & OptionsParsingMode.Linux) > 0 &&
arg[0] == '-' && arg[1] != '-' &&
breakSingleDashManyLettersIntoManyOptions)
{
foreach(char c in arg.Substring(1)) // many single-letter options
result.Add("-" + c); // expand into individualized options
continue;
}
if (MaybeAnOption(arg))
{
result.AddRange(arg.Split(':','='));
continue;
}
}
else
{
argumentsTail.Add(arg);
continue;
}
// if nothing else matches then it get here
result.Add(arg);
}
}
return (string[])result.ToArray(typeof(string));
}
public string[] ProcessArgs(string[] args)
{
string arg;
string nextArg;
bool OptionWasProcessed;
list.Sort();
args = NormalizeArgs(args);
try
{
int argc = args.Length;
for (int i = 0; i < argc; i++)
{
arg = args[i];
if (i+1 < argc)
nextArg = args[i+1];
else
nextArg = null;
OptionWasProcessed = false;
if (arg.StartsWith("-") || arg.StartsWith("/"))
{
foreach(OptionDetails option in list)
{
OptionProcessingResult result = option.ProcessArgument(arg, nextArg);
if (result != OptionProcessingResult.NotThisOption)
{
OptionWasProcessed = true;
if (result == OptionProcessingResult.OptionConsumedParameter)
i++;
break;
}
}
}
if (!OptionWasProcessed)
{
if (OptionDetails.Verbose)
Console.WriteLine("argument [" + arg + "]");
arguments.Add(arg);
}
}
foreach(OptionDetails option in list)
option.TransferValues();
foreach(string argument in argumentsTail)
arguments.Add(argument);
if (argumentProcessor == null)
return (string[])arguments.ToArray(typeof(string));
foreach(string argument in arguments)
argumentProcessor.Invoke(optionBundle, new object[] { argument });
}
catch (Exception ex)
{
System.Console.WriteLine(ex.ToString());
System.Environment.Exit(1);
}
return null;
}
#endregion
}
}
|