-
Notifications
You must be signed in to change notification settings - Fork 30
/
ValueArgument.cs
539 lines (488 loc) · 22.8 KB
/
ValueArgument.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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using CommandLineParser.Exceptions;
using CommandLineParser.Extensions;
using System.Text.RegularExpressions;
namespace CommandLineParser.Arguments
{
/// <summary>
/// Delegate for a method that converts string to a specified class
/// </summary>
/// <typeparam name="TValue">type of the converted class</typeparam>
/// <param name="stringValue">string that represents the value of TValue</param>
/// <returns>TValue loaded from string</returns>
public delegate TValue ConvertValueDelegate<TValue>(string stringValue);
/// <summary>
/// Use value argument for an argument followed by value on the command line. (e. g. --version 1.2)
/// </summary>
/// <typeparam name="TValue">type of the value of the argument.
/// Can be either builtin type or any user type (for which specific
/// conversion routine is provided - <see cref="ConvertValueHandler"/></typeparam>
/// <include file='..\Doc\CommandLineParser.xml' path='CommandLineParser/Arguments/ValueArgument/*'/>
public class ValueArgument<TValue> : Argument, IValueArgument, IArgumentWithDefaultValue
{
#region property backing fields
private string _stringValue;
private TValue _value;
private readonly List<TValue> _values = new List<TValue>();
private CultureInfo _cultureInfo = CultureInfo.InvariantCulture;
#endregion
#region constructor
/// <summary>
/// Creates new value argument with a <see cref="Argument.ShortName">short name</see>.
/// </summary>
/// <param name="shortName">Short name of the argument</param>
public ValueArgument(char shortName) : base(shortName) { }
/// <summary>
/// Creates new value argument with a <see cref="Argument.LongName">long name</see>.
/// </summary>
/// <param name="longName">Long name of the argument</param>
public ValueArgument(string longName) : base(longName) { }
/// <summary>
/// Creates new value argument with a <see cref="Argument.ShortName">short name</see>and <see cref="Argument.LongName">long name</see>.
/// </summary>
/// <param name="shortName">Short name of the argument</param>
/// <param name="longName">Long name of the argument </param>
public ValueArgument(char shortName, string longName) : base(shortName, longName) { }
/// <summary>
/// Creates new value argument with a <see cref="Argument.ShortName">short name</see>,
/// <see cref="Argument.LongName">long name</see> and <see cref="Argument.Description">description</see>.
/// </summary>
/// <param name="shortName">Short name of the argument</param>
/// <param name="longName">Long name of the argument </param>
/// <param name="description">description of the argument</param>
public ValueArgument(char shortName, string longName, string description)
: base(shortName, longName, description) { }
#endregion
/// <summary>
/// String read from command line as arguments <see cref="Value"/>. Available after <see cref="Parse"/> is called.
/// </summary>
/// <exception cref="InvalidOperationException">String value was read before ParseCommandLine was called or when</exception>
public string StringValue
{
get
{
if (Parsed)
return _stringValue;
else
return null;
}
}
/// <summary>
/// Value of the ValueArgument, for arguments with single value.
/// Can be used only if <see cref="Argument.AllowMultiple"/> is set to false.
/// </summary>
public TValue Value
{
get
{
if (AllowMultiple)
throw new InvalidOperationException("Cannot access Value field because AllowMultiple is set to true. Use Values instead.");
return _value;
}
set
{
if (AllowMultiple)
throw new InvalidOperationException("Cannot access Value field because AllowMultiple is set to true. Use Values instead.");
_value = value;
}
}
/// <summary>
/// Default value of the argument. Restored each time <see cref="Init"/> is called.
/// </summary>
public TValue DefaultValue { get; set; }
object IArgumentWithDefaultValue.DefaultValue { get { return DefaultValue; } }
/// <summary>
/// When set to true, argument can appear on the command line with or without value, e.g. both is allowed:
/// <code>
/// myexe.exe -Arg Value
/// OR
/// myexe.exe -Arg
/// </code>
/// </summary>
public bool ValueOptional { get; set; }
/// <summary>
/// Values of the ValueArgument - for arguments with multiple values allowed.
/// Can be used only if <see cref="Argument.AllowMultiple"/> is set to true.
/// </summary>
public List<TValue> Values
{
get
{
if (!AllowMultiple)
throw new InvalidOperationException("Cannot access Values field because AllowMultiple is set to false. Use Value instead.");
return _values;
}
}
/// <summary>
/// Value of the ValueArgument, for arguments with single value.
/// Can be used only if <see cref="Argument.AllowMultiple"/> is set to false.
/// </summary>
/// <value></value>
object IValueArgument.Value
{
get { return Value; }
set { Value = (TValue)value; }
}
IList<object> IValueArgument.Values
{
get
{
object[] objects = new object[Values.Count];
for (int i = 0; i < Values.Count; i++)
{
objects[i] = Values[i];
}
return objects;
}
}
/// <summary>
/// Adds an item to underlying <see cref="Values"/> collection.
/// </summary>
public void AddToValues(object value)
{
Values.Add((TValue)value);
}
/// <summary>
/// Function that converts string to <typeparamref name="TValue"/> type.
/// Necessary when non-builtin type is used as <typeparamref name="TValue"/>.
/// </summary>
public ConvertValueDelegate<TValue> ConvertValueHandler { get; set; }
/// <summary>
/// This method reads the argument and the following string representing the value of the argument.
/// This string is then converted to <typeparamref name="TValue"/> (using built-in <typeparamref name="TValue"/>.Parse
/// method for built-in types or using <see cref="ConvertValueHandler"/> for user types).
/// </summary>
/// <param name="args">command line arguments</param>
/// <param name="i">index to the args array, where this argument occured.
/// The index to the next argument after the argument is processed. </param>
/// <seealso cref="ConvertValueHandler"/>
/// <exception cref="CommandLineArgumentException">Incorrect format of the command line
/// or multiple useage of an argument that is not <see cref="Argument.AllowMultiple"/> found.</exception>
internal override void Parse(IList<string> args, ref int i)
{
base.Parse(args, ref i);
i++; // move the cursor to the value
if (args.Count - 1 < i)
{
if (ValueOptional)
{
Parsed = true;
return;
}
throw new CommandLineArgumentException(string.Format(Messages.EXC_ARG_VALUE_MISSING2, Name), Name);
}
_stringValue = args[i];
bool canParse = true;
try { Convert(_stringValue); }
catch { canParse = false; }
if (!canParse && args[i].StartsWith("-"))
{
if (ValueOptional)
{
Parsed = true;
return;
}
throw new CommandLineArgumentException(string.Format(Messages.EXC_ARG_VALUE_MISSING, Name, args[i]), Name);
}
if (!AllowMultiple)
Value = Convert(_stringValue);
else
Values.Add(Convert(_stringValue));
Parsed = true;
i++; // move to the next argument
}
/// <summary>
/// If <see cref="Argument.Bind"/> is specified, the bound field of the bound object should is updated
/// according to the value of the argument. Should be called after Parse is called. If
/// <see cref="Argument.AllowMultiple"/> is set to false, the binding fills a collection or an array with the
/// values.
/// </summary>
public override void UpdateBoundObject()
{
if (Bind == null)
return;
MemberInfo info = Bind.Value.Object.GetType().GetMember(Bind.Value.Field)[0];
Type boundType = null;
if (info is PropertyInfo) boundType = (info as PropertyInfo).PropertyType;
else if (info is FieldInfo) boundType = (info as FieldInfo).FieldType;
//multiple value argument can be bound only to a proper collection
if (AllowMultiple
&& (!(typeof(List<TValue>).IsAssignableFrom(boundType)))
&& !boundType.IsArray)
{
throw new InvalidOperationException("ValueArguments that allow multiple values can be bound only to an object implementing ICollection<TVale> and the collection must not be read only.");
}
try
{
if (!AllowMultiple || boundType.IsArray)
{
// binding of a simple value or array
object newValue;
if (!boundType.IsArray)
newValue = _value;
else
newValue = Values.ToArray();
if (info is FieldInfo)
(info as FieldInfo).SetValue(Bind.Value.Object, newValue);
if (info is PropertyInfo)
(info as PropertyInfo).SetValue(Bind.Value.Object, newValue, null);
}
else
{
ICollection<TValue> targetCollection = InitializeTargetCollection(info);
foreach (TValue value in _values)
{
targetCollection.Add(value);
}
}
}
catch (Exception e)
{
throw new CommandLineException(string.Format(Messages.EXC_BINDING, Name, Bind.Value.Field, Bind.Value.Object), e);
}
}
private ICollection<TValue> InitializeTargetCollection(MemberInfo info)
{
ICollection<TValue> targetCollection = null;
if (info is FieldInfo)
targetCollection = (ICollection<TValue>)(info as FieldInfo).GetValue(Bind.Value.Object);
else if (info is PropertyInfo)
targetCollection = (ICollection<TValue>)(info as PropertyInfo).GetValue(Bind.Value.Object, null);
if (targetCollection == null)
{
if (info is FieldInfo)
{
targetCollection = (ICollection<TValue>)Activator.CreateInstance((info as FieldInfo).FieldType);
(info as FieldInfo).SetValue(Bind.Value.Object, targetCollection);
}
else if (info is PropertyInfo)
{
targetCollection = (ICollection<TValue>)Activator.CreateInstance((info as PropertyInfo).PropertyType);
(info as PropertyInfo).SetValue(Bind.Value.Object, targetCollection, null);
}
}
targetCollection.Clear();
return targetCollection;
}
/// <summary>
/// Culture used for conversions of built-in types. InvariantCulture is used when
/// no other culture is specified.
/// </summary>
public CultureInfo CultureInfo
{
get { return _cultureInfo; }
set { _cultureInfo = value; }
}
/// <summary>
/// Converts <paramref name="stringValue"/> to <typeparamref name="TValue"/>.
/// <see cref="ConvertValueHandler"/> is called if specified, otherwise
/// <see cref="DefaultConvert"/> is called.
/// </summary>
/// <param name="stringValue">string representing the value</param>
/// <returns>value as <typeparamref name="TValue"/></returns>
/// <exception cref="InvalidConversionException">String cannot be converted to <typeparamref name="TValue"/>.</exception>
public virtual TValue Convert(string stringValue)
{
TValue tmpValue;
if (ConvertValueHandler != null)
{
tmpValue = ConvertValueHandler(stringValue);
}
else
{
tmpValue = DefaultConvert(stringValue);
}
return tmpValue;
}
/// <summary>
/// Non-generic access to <see cref="ValueArgument{TValue}.Convert"/>
/// </summary>
/// <param name="stringValue">string representing the value</param>
/// <returns>parsed value</returns>
public object Convert_obj(string stringValue)
{
return Convert(stringValue);
}
/// <summary>
/// Converts <paramref name="stringValue"/> to <typeparamref name="TValue"/>.
/// Works only for built-in types.
/// </summary>
/// <param name="stringValue">string representing the value</param>
/// <returns>value as <typeparamref name="TValue"/></returns>
/// <exception cref="InvalidConversionException">String cannot be converted to <typeparamref name="TValue"/>.</exception>
protected virtual TValue DefaultConvert(string stringValue)
{
Type valueType = typeof(TValue);
try
{
if (valueType == typeof(String)) return (TValue)(object)stringValue;
if (valueType == typeof(int)) return (TValue)(object)int.Parse(stringValue, _cultureInfo);
if (valueType == typeof(decimal)) return (TValue)(object)decimal.Parse(stringValue, _cultureInfo);
if (valueType == typeof(long)) return (TValue)(object)long.Parse(stringValue, _cultureInfo);
if (typeof(Enum).IsAssignableFrom(valueType)) return (TValue)Enum.Parse(valueType, stringValue, true);
if (valueType == typeof(short)) return (TValue)(object)short.Parse(stringValue, _cultureInfo);
if (valueType == typeof(char)) return (TValue)(object)char.Parse(stringValue);
if (valueType == typeof(bool)) return (TValue)(object)bool.Parse(stringValue);
if (valueType == typeof(byte)) return (TValue)(object)byte.Parse(stringValue, _cultureInfo);
if (valueType == typeof(sbyte)) return (TValue)(object)sbyte.Parse(stringValue, _cultureInfo);
if (valueType == typeof(double)) return (TValue)(object)double.Parse(stringValue, _cultureInfo);
if (valueType == typeof(float)) return (TValue)(object)float.Parse(stringValue, _cultureInfo);
if (valueType == typeof(uint)) return (TValue)(object)uint.Parse(stringValue, _cultureInfo);
if (valueType == typeof(ulong)) return (TValue)(object)ulong.Parse(stringValue, _cultureInfo);
if (valueType == typeof(ushort)) return (TValue)(object)ushort.Parse(stringValue, _cultureInfo);
if (valueType == typeof(DateTime)) return (TValue)(object)DateTime.Parse(stringValue, _cultureInfo);
if (valueType == typeof(TimeSpan)) return (TValue)(object)DateTime.Parse(stringValue, _cultureInfo);
if (valueType == typeof(Guid))
{
#if NET20 || NET35
return (TValue)(object)new Guid(stringValue);
#else
return (TValue)(object)Guid.Parse(stringValue);
#endif
}
MethodInfo mi = typeof(TValue).GetMethod("Parse", new [] { typeof(string), typeof(CultureInfo)});
if (mi != null)
{
if (mi.IsStatic && mi.ReturnType == typeof(TValue))
return (TValue)mi.Invoke(null, new object[] { stringValue, _cultureInfo });
}
}
catch (FormatException)
{
throw new InvalidConversionException(string.Format(Messages.EXC_ARG_VALUE_STANDARD_CONVERT_FAILED, stringValue, valueType), Name);
}
throw new InvalidConversionException(string.Format(Messages.EXC_ARG_VALUE_USER_CONVERT_MISSING, valueType, stringValue), Name);
}
/// <summary>
/// Initializes the argument.
/// </summary>
public override void Init()
{
base.Init();
_value = DefaultValue;
_values.Clear();
_stringValue = string.Empty;
}
/// <summary>
/// Prints information about the argument value to the console.
/// </summary>
public override void PrintValueInfo()
{
if (!AllowMultiple)
{
Console.WriteLine(Messages.EXC_ARG_VALUE_PRINT, Name, _stringValue, _value, typeof(TValue).Name);
}
else
{
string valuesString = string.Join(", ", _values.Select(v => v.ToString()).ToArray());
Console.WriteLine(Messages.EXC_ARG_VALUE_PRINT_MULTIPLE, Name, Values.Count, valuesString, typeof(TValue).Name);
}
}
}
/// <summary>
/// <para>
/// Attribute for declaring a class' field a <see cref="ValueArgument{TValue}"/> and
/// thus binding a field's value to a certain command line switch argument.
/// </para>
/// <para>
/// Instead of creating an argument explicitly, you can assign a class' field an argument
/// attribute and let the CommandLineParse take care of binding the attribute to the field.
/// </para>
/// </summary>
/// <remarks>Appliable to fields and properties (public).</remarks>
/// <remarks>Use <see cref="CommandLineParser.ExtractArgumentAttributes"/> for each object
/// you where you have delcared argument attributes.</remarks>
public class ValueArgumentAttribute : ArgumentAttribute
{
private static Type underlyingValueArgument;
/// <summary>
/// Creates proper generic <see cref="ValueArgument{TValue}"/> type for <paramref name="type"/>.
/// </summary>
/// <param name="type">type of the argument value</param>
/// <returns>generic type</returns>
private static Type CreateProperValueArgumentType(Type type)
{
Type genericType = typeof(ValueArgument<>);
Type constructedType = genericType.MakeGenericType(type);
underlyingValueArgument = constructedType;
return underlyingValueArgument;
}
/// <summary>
/// Creates new instance of ValueArgument. ValueArgument
/// uses underlying <see cref="ValueArgument{TValue}"/>.
/// </summary>
/// <param name="type">Type of the generic parameter of <see cref="ValueArgument{TValue}"/>. </param>
/// <param name="shortName"><see cref="Argument.ShortName">short name</see> of the underlying argument</param>
/// <remarks>
/// Parameter <paramref name="type"/> has to be either built-in
/// type or has to define a static Parse(String, CultureInfo)
/// method for reading the value from string.
/// </remarks>
public ValueArgumentAttribute(Type type, char shortName)
: base(CreateProperValueArgumentType(type), shortName) { }
/// <summary>
/// Creates new instance of ValueArgument. ValueArgument
/// uses underlying <see cref="ValueArgument{TValue}"/>.
/// </summary>
/// <param name="type">Type of the generic parameter of <see cref="ValueArgument{TValue}"/>. </param>
/// <param name="longName"><see cref="Argument.LongName">long name</see> of the underlying argument</param>
/// <remarks>
/// Parameter <paramref name="type"/> has to be either built-in
/// type or has to define a static Parse(String, CultureInfo)
/// method for reading the value from string.
/// </remarks>
public ValueArgumentAttribute(Type type, string longName)
: base(CreateProperValueArgumentType(type), longName) { }
/// <summary>
/// Creates new instance of ValueArgument. ValueArgument
/// uses underlying <see cref="ValueArgument{TValue}"/>.
/// </summary>
/// <param name="type">Type of the generic parameter of <see cref="ValueArgument{TValue}"/>.</param>
/// <param name="shortName"><see cref="Argument.ShortName">short name</see> of the underlying argument</param>
/// <param name="longName"><see cref="Argument.LongName">long name</see> of the underlying argument</param>
/// <remarks>
/// Parameter <paramref name="type"/> has to be either built-in
/// type or has to define a static Parse(String, CultureInfo)
/// method for reading the value from string.
/// </remarks>
public ValueArgumentAttribute(Type type, char shortName, string longName)
: base(CreateProperValueArgumentType(type), shortName, longName) { }
/// <summary>
/// Default value
/// </summary>
public object DefaultValue
{
get
{
return underlyingValueArgument.GetPropertyValue<object>("DefaultValue", Argument);
}
set
{
underlyingValueArgument.SetPropertyValue("DefaultValue", Argument, value);
}
}
/// <summary>
/// When set to true, argument can appear on the command line with or without value, e.g. both is allowed:
/// <code>
/// myexe.exe -Arg Value
/// OR
/// myexe.exe -Arg
/// </code>
/// </summary>
public bool ValueOptional
{
get
{
return underlyingValueArgument.GetPropertyValue<bool>("ValueOptional", Argument);
}
set
{
underlyingValueArgument.SetPropertyValue("ValueOptional", Argument, value);
}
}
}
}