-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathProgram.cs
More file actions
311 lines (265 loc) · 11.7 KB
/
Program.cs
File metadata and controls
311 lines (265 loc) · 11.7 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Text.RegularExpressions;
using System.Xml;
using Common;
using log4net;
using ServiceStack;
namespace PluginTester
{
public class Program
{
private static ILog _log;
public static void Main(string[] args)
{
Environment.ExitCode = 1;
try
{
ConfigureLogging();
var program = new Program();
program.ParseArgs(args);
program.Run();
Environment.ExitCode = 0;
}
catch (ExpectedException exception)
{
_log.Error(exception.Message);
}
catch (Exception exception)
{
_log.Error("Unhandled exception", exception);
}
}
private static void ConfigureLogging()
{
using (var stream = new MemoryStream(LoadEmbeddedResource("log4net.config")))
using (var reader = new StreamReader(stream))
{
var xml = new XmlDocument();
xml.LoadXml(reader.ReadToEnd());
log4net.Config.XmlConfigurator.Configure(xml.DocumentElement);
_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
}
}
private static byte[] LoadEmbeddedResource(string path)
{
// ReSharper disable once PossibleNullReferenceException
var resourceName = $"{MethodBase.GetCurrentMethod().DeclaringType.Namespace}.{path}";
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
if (stream == null)
throw new ExpectedException($"Can't load '{resourceName}' as embedded resource.");
return stream.ReadFully();
}
}
private Context Context { get; } = new Context();
private void ParseArgs(string[] args)
{
var options = new[]
{
new CommandLineOption { Description = "Specify the plugin to be tested" },
new CommandLineOption
{
Key = "Plugin",
Setter = value => Context.PluginPath = value,
Getter = () => Context.PluginPath,
Description = "Path to the plugin assembly. Can be a folder, a DLL, or a packaged *.plugin file."
},
new CommandLineOption
{
Key = nameof(Context.Verbose),
Setter = value => Context.Verbose = bool.Parse(value),
Getter = () => $"{Context.Verbose}",
Description = "Enables verbose logging of assembly loading logic."
},
new CommandLineOption
{
Key = nameof(Context.FrameworkAssemblyPath),
Setter = value => Context.FrameworkAssemblyPath = value,
Getter = () => Context.FrameworkAssemblyPath,
Description = "Optional path to the FieldDataPluginFramework.dll assembly. [default: Test using the latest framework version]"
},
new CommandLineOption(), new CommandLineOption { Description = "Test data settings" },
new CommandLineOption
{
Key = "Data",
Setter = value => AddDataPath(Context, value),
Getter = () => string.Empty,
Description = "Path to the data file to be parsed. Can be set more than once."
},
new CommandLineOption
{
Key = nameof(Context.RecursiveSearch),
Setter = value => Context.RecursiveSearch = bool.Parse(value),
Getter = () => $"{Context.RecursiveSearch}",
Description = "Search /Data directories recursively. -R shortcut is also supported."
},
new CommandLineOption
{
Key = "Setting",
Setter = value => AddSetting(Context, value),
Getter = () => string.Empty,
Description = "Supply plugin settings as 'key=text' or 'key=@pathToTextFile' values."
},
new CommandLineOption(), new CommandLineOption { Description = "Plugin context settings" },
new CommandLineOption
{
Key = "Location",
Setter = value => Context.LocationIdentifier = value,
Getter = () => Context.LocationIdentifier,
Description = "Optional location identifier context"
},
new CommandLineOption
{
Key = "UtcOffset",
Setter = value => Context.LocationUtcOffset = TimeSpan.Parse(value),
Getter = () => Context.LocationUtcOffset.ToString(),
Description = "UTC offset in .NET TimeSpan format."
},
new CommandLineOption(), new CommandLineOption { Description = "Output settings" },
new CommandLineOption
{
Key = "Json",
Setter = value => Context.JsonPath = value,
Getter = () => Context.JsonPath,
Description = "Optional path (file or folder) to write the appended results as JSON."
},
new CommandLineOption(), new CommandLineOption { Description = "Expected response settings" },
new CommandLineOption
{
Key = nameof(Context.ExpectedError),
Setter = value => Context.ExpectedError = value,
Getter = () => Context.ExpectedError,
Description = "Expected error message"
},
new CommandLineOption
{
Key = nameof(Context.ExpectedStatus),
Setter = value => Context.ExpectedStatus = (StatusType)Enum.Parse(typeof(StatusType), value, true),
Getter = () => Context.ExpectedStatus.ToString(),
Description = $"Expected parse status. One of {string.Join(", ", Enum.GetNames(typeof(StatusType)))}"
},
};
var usageMessage = CommandLineUsage.ComposeUsageText(
"Parse a file using a field data plugin, logging the results.", options);
var optionResolver = new CommandLineOptionResolver();
optionResolver.Resolve(args, options, usageMessage, arg => PositionalArgumentResolver(Context, arg));
if (string.IsNullOrEmpty(Context.PluginPath))
throw new ExpectedException("No plugin assembly specified.");
if (!Context.DataPaths.Any())
throw new ExpectedException("No data file specified.");
}
private bool PositionalArgumentResolver(Context context, string arg)
{
if (RecursiveShortcuts.Contains(arg))
{
Context.RecursiveSearch = true;
return true;
}
var match = SettingRegex.Match(arg);
if (match.Success)
{
AddSetting(context, arg);
return true;
}
return false;
}
private static readonly HashSet<string> RecursiveShortcuts =
new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
{
"-r",
"/r"
};
private static void AddSetting(Context context, string value)
{
var match = SettingRegex.Match(value);
if (!match.Success)
throw new ExpectedException($"'{value}' does not match a key=text or key=@pathToTextFile setting.");
var key = match.Groups["key"].Value;
var text = match.Groups["text"].Value;
var pathToText = match.Groups["pathToTextFile"].Value;
context.Settings[key] = !string.IsNullOrWhiteSpace(pathToText)
? File.ReadAllText(pathToText)
: text;
}
private static readonly Regex SettingRegex = new Regex(@"^\s*(?<key>[^=]+)\s*=\s*(@(?<pathToTextFile>.+)|(?<text>.+))$");
private static void AddDataPath(Context context, string dataPath)
{
foreach (var path in ExpandDataPath(context, dataPath))
{
context.DataPaths.Add(path);
}
}
private static IEnumerable<string> ExpandDataPath(Context context, string path)
{
var dir = Path.GetDirectoryName(path);
var filename = Path.GetFileName(path);
if (string.IsNullOrEmpty(dir) || string.IsNullOrEmpty(filename))
{
yield return path;
}
else
{
var searchDepth = context.RecursiveSearch
? SearchOption.AllDirectories
: SearchOption.TopDirectoryOnly;
foreach (var expandedPath in Directory.GetFiles(dir, filename, searchDepth))
{
yield return expandedPath;
}
}
}
private void Run()
{
LoadFrameworkAssembly();
new Tester {Context = Context}
.Run();
}
private void LoadFrameworkAssembly()
{
if (string.IsNullOrWhiteSpace(Context.FrameworkAssemblyPath))
return;
if (!File.Exists(Context.FrameworkAssemblyPath))
throw new ExpectedException($"Can't find framework assembly at '{Context.FrameworkAssemblyPath}'.");
var assembly = LoadFrameworkAssembly(Context.FrameworkAssemblyPath);
const string targetName = "FieldDataPluginFramework.IFieldDataPlugin";
var interfaceDefinitionType = assembly.GetTypes()
.FirstOrDefault(type => type.FullName == targetName);
if (interfaceDefinitionType == null)
throw new ExpectedException($"Can't find {targetName} in '{Context.FrameworkAssemblyPath}'");
_log.Info($"Loaded external framework assembly '{assembly.FullName}' from '{Context.FrameworkAssemblyPath}'.");
}
private Assembly LoadFrameworkAssembly(string path)
{
try
{
return Assembly.LoadFile(path);
}
catch (Exception exception)
{
switch (exception)
{
case ReflectionTypeLoadException loadException:
throw new ExpectedException($"Can't load '{path}': {SummarizeLoaderExceptions(loadException)}");
case BadImageFormatException _:
case FileLoadException _:
case SecurityException _:
throw new ExpectedException($"Can't load '{path}': {exception.Message}");
default:
_log.Error($"Unexpected Assembly.LoadFile('{path}') exception: {exception.GetType().Name}: {exception.Message}");
throw;
}
}
}
private static string SummarizeLoaderExceptions(ReflectionTypeLoadException exception)
{
if (exception.LoaderExceptions == null)
return string.Empty;
return string.Join("\n", exception.LoaderExceptions.Select(e => e.Message));
}
}
}