-
Notifications
You must be signed in to change notification settings - Fork 1
/
ConfigParser.cs
404 lines (344 loc) · 15.5 KB
/
ConfigParser.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using UnityEngine;
namespace PolkaDOTS.Configuration
{
/// <summary>
/// Class to parse configuration parameters from arguments. Called by <see cref="CmdArgsReader"/>
/// </summary>
public static class CommandLineParser
{
internal delegate bool TryParseDelegate<T>(string[] arguments, string argumentName, out T result);
public abstract class BaseArgument<T> : IArgument
{
/// <summary>
///
/// </summary>
public string ArgumentName { get; }
/// <summary>
///
/// </summary>
public bool Defined => m_defined;
/// <summary>
///
/// </summary>
public readonly bool Required;
/// <summary>
///
/// </summary>
public T Value
{
get { return m_value; }
set
{
if (m_defined)
{
Debug.LogWarning($"Overwriting argument {ArgumentName}: was {m_value}, is {value}");
}
m_value = value;
}
}
/// <summary>
///
/// </summary>
protected T Default;
protected bool m_defined;
protected T m_value;
readonly TryParseDelegate<T> m_parser;
protected abstract bool DefaultParser(string[] arguments, string argumentName, out T parsedResult);
public bool TryParse(string[] arguments)
{
m_defined =
m_parser != null &&
m_parser(arguments, ArgumentName, out m_value);
/*if (!m_defined)
{
m_value = Default;
}*/
return m_defined;
}
public string GetArgumentName()
{
return ArgumentName;
}
internal BaseArgument(string argumentName, T defaultValue, bool required = false)
{
Required = required;
ArgumentName = argumentName;
Default = defaultValue;
m_parser = DefaultParser;
}
public override string ToString()
{
return m_value.ToString();
}
}
public class StringArgument : BaseArgument<string>
{
protected override bool DefaultParser(string[] arguments, string argumentName, out string parsedResult) => TryParseStringArgument(arguments, argumentName, out parsedResult, Default, Required);
public StringArgument(string argumentName, string defaultVal, bool required = false) : base(argumentName, defaultVal, required) { }
//public static implicit operator string(StringArgument argument) => !argument.Defined ? argument.Default : argument.Value;
public static implicit operator string(StringArgument argument) => argument.Value;
}
public class EnumArgument<T> : BaseArgument<T> where T : struct
{
protected override bool DefaultParser(string[] arguments, string argumentName, out T parsedResult) => TryParseEnumArgument(arguments, argumentName, out parsedResult, Default, Required);
public EnumArgument(string argumentName, T defaultVal, bool required = false) : base(argumentName, defaultVal, required) { }
public static implicit operator T(EnumArgument<T> argument) => argument.Value;
}
public class StringArrayArgument : BaseArgument<string[]>
{
protected override bool DefaultParser(string[] arguments, string argumentName, out string[] parsedResult) => TryParseStringArrayArgument(arguments, argumentName, out parsedResult, Default, Required);
public StringArrayArgument(string argumentName, string[] defaultVal, bool required = false) : base(argumentName, defaultVal, required) { }
public static implicit operator string[](StringArrayArgument argument) => argument.Value;
public override string ToString()
{
var s = string.Join(",", m_value);
return $"[{s}]";
}
}
public class IntArgument : BaseArgument<int>
{
protected override bool DefaultParser(string[] arguments, string argumentName, out int parsedResult) => TryParseIntArgument(arguments, argumentName, out parsedResult, Default, Required);
public IntArgument(string argumentName, int defaultVal, bool required = false) : base(argumentName, defaultVal, required) { }
public static implicit operator int(IntArgument argument) => argument.Value;
}
public class FlagArgument : BaseArgument<bool>
{
protected override bool DefaultParser(string[] arguments, string argumentName, out bool parsedResult) => TryParseFlagArgument(arguments, argumentName, out parsedResult, Required);
public FlagArgument(string argumentName, bool defaultVal, bool required = false) : base(argumentName, defaultVal, required) { }
public static implicit operator bool(FlagArgument argument) => argument.Value;
}
public class JsonFileArgument<T> : BaseArgument<T?> where T : struct
{
protected override bool DefaultParser(string[] arguments, string argumentName, out T? parsedResult) => TryParseJsonFileArgument(arguments, argumentName, out parsedResult, Required);
public JsonFileArgument(string argumentName, T? defaultVal, bool required = false) : base(argumentName, defaultVal, required) { }
public static implicit operator T?(JsonFileArgument<T> argument) => argument.Value;
}
/*public class JsonFileArgumentClass<T> : BaseArgument<T> where T : class
{
protected override bool DefaultParser(string[] arguments, string argumentName, out T parsedResult) => TryParseJsonFileArgumentClass(arguments, argumentName, out parsedResult, Required);
public JsonFileArgumentClass(string argumentName, T defaultVal, bool required = false) : base(argumentName, defaultVal, required) { }
public static implicit operator T(JsonFileArgumentClass<T> argument) => argument.Value;
}*/
public class FilePathArgument : BaseArgument<string>
{
protected override bool DefaultParser(string[] arguments, string argumentName, out string parsedResult) => TryParseFilePathArgument(arguments, argumentName, out parsedResult, Default);
public FilePathArgument(string argumentName, string defaultVal, bool required = false) : base(argumentName, defaultVal, required) { }
public static implicit operator string(FilePathArgument argument) => argument.Value;
}
static bool TryParseStringArgument(string[] arguments, string argumentName, out string argumentValue, string def, bool required = false)
{
var startIndex = System.Array.FindIndex(arguments, x => x == argumentName);
if (startIndex < 0)
{
argumentValue = def;
return !required;
}
if (startIndex + 1 >= arguments.Length)
{
argumentValue = def;
return false;
}
argumentValue = arguments[startIndex + 1];
return !string.IsNullOrEmpty(argumentValue);
}
static bool TryParseEnumArgument<T>(string[] arguments, string argumentName, out T argumentValue, T def,
bool required = false) where T : struct
{
bool result = TryParseStringArgument(arguments, argumentName, out string value, "", required);
if (result && !string.IsNullOrEmpty(value))
{
if (Enum.TryParse(value, true, out T enumValue))
{
argumentValue = enumValue;
return true;
}
result = false;
}
argumentValue = def;
return result;
}
static bool TryParseIntArgument(string[] arguments, string argumentName, out int argumentValue, int def, bool required = false)
{
var startIndex = System.Array.FindIndex(arguments, x => x == argumentName);
if (startIndex < 0)
{
argumentValue = def;
return !required;
}
if (startIndex + 1 >= arguments.Length)
{
argumentValue = def;
return false;
}
if (!int.TryParse(arguments[startIndex + 1], out var result))
{
argumentValue = def;
return false;
}
argumentValue = result;
return true;
}
static bool TryParseFlagArgument(string[] arguments, string argumentName, out bool argumentValue, bool required = false)
{
var startIndex = System.Array.FindIndex(arguments, x => x == argumentName);
if (startIndex < 0)
argumentValue = false;
else
argumentValue = true;
return true;
}
static bool TryParseStringArrayArgument(string[] arguments, string argumentName, out string[] argumentValue, string[] def, bool required = false)
{
List<string> list = new List<string>();
for (int i = 0; i < arguments.Length;)
{
var startIndex = Array.FindIndex(arguments, i, x => x == argumentName);
if (startIndex < 0)
break;
if (startIndex + 1 >= arguments.Length)
break;
list.Add(arguments[startIndex + 1]);
i = startIndex + 2;
}
if (list.Count == 0 && required)
{
argumentValue = def;
return false;
}
argumentValue = list.ToArray();
return true;
}
static bool TryParseJsonFileArgument<T>(string[] arguments, string argumentName, out T? argumentValue,
bool required = false) where T : struct
{
bool result = TryParseFilePathArgument(arguments, argumentName, out string value, "");
if (result && !string.IsNullOrEmpty(value))
{
string text = File.ReadAllText(value);
try
{
//argumentValue = JsonUtility.FromJson<T>(text);
argumentValue = JsonConvert.DeserializeObject<T>(text);
return true;
}
catch (Exception)
{
result = false;
}
}
else if (required)
result = false;
argumentValue = null;
return result;
}
/*static bool TryParseJsonFileArgumentClass<T>(string[] arguments, string argumentName, out T argumentValue,
bool required = false) where T : class
{
bool result = TryParseFilePathArgument(arguments, argumentName, out string value);
if (result && !string.IsNullOrEmpty(value))
{
string text = File.ReadAllText(value);
try
{
//argumentValue = JsonUtility.FromJson<T>(text);
argumentValue = JsonConvert.DeserializeObject<T>(text);
return true;
}
catch (Exception)
{
result = false;
}
}
else if (required)
result = false;
argumentValue = null;
return result;
}*/
static bool TryParseFilePathArgument(string[] arguments, string argumentName, out string argumentValue, string def)
{
bool ret = TryParseStringArgument(arguments, argumentName, out string value, "");
if (!ret)
{
argumentValue = def;
return false;
}
if (string.IsNullOrEmpty(value))
{
argumentValue = def;
return true;
}
/*if (!File.Exists(value))
{
argumentValue = null;
return false;
}*/
argumentValue = value;
return true;
}
/// <summary>
/// Finds all classes with a particular attribute type
/// </summary>
/// <param name="inherit">Whether to includes class that indirectly inherent the attribute</param>
/// <returns>List of Types with the given attribute.</returns>
/// <remarks>See https://stackoverflow.com/questions/720157/finding-all-classes-with-a-particular-attribute</remarks>
public static IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit = false) where TAttribute : Attribute
{
var output = new List<Type>();
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
var assembly_types = assembly.GetTypes();
foreach (var type in assembly_types)
{
if (type.IsDefined(typeof(TAttribute), inherit))
output.Add(type);
}
}
return output;
}
/// <summary>
/// Calls TryParse on all Argument objects in all classes marked with ArgumentClass
/// </summary>
/// <param name="commandLineArgs">List of string arguments from command line</param>
/// <returns>True if all arguments parsed successfully</returns>
/// <remarks>See https://stackoverflow.com/questions/5976216/how-to-call-an-explicitly-implemented-interface-method-on-the-base-class</remarks>
internal static bool TryParse(string[] commandLineArgs)
{
var argumentClasses = GetTypesWith<ArgumentClass>();
foreach (var argumentClassType in argumentClasses)
{
FieldInfo[] fields = argumentClassType.GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (FieldInfo field in fields)
{
var argumentField = field.GetValue(null);
var argumentFieldBaseType = field.FieldType.BaseType;
if (argumentFieldBaseType != null)
{
var methods = argumentFieldBaseType.GetMethods(BindingFlags.Public | BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (var method in methods)
{
if (method.Name.Contains("TryParse"))
{
bool ret = (bool)method.Invoke(argumentField, new object[] { commandLineArgs });
if (!ret)
{
Debug.Log($"Failed to read argument {field.Name}");
return false;
}
break;
}
}
}
}
}
return true;
}
}
}