-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConfigurableApplication.cs
295 lines (272 loc) · 8.59 KB
/
ConfigurableApplication.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
using IS4.SFI.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
namespace IS4.SFI.Application
{
/// <summary>
/// An abstract base application class that supports loading config
/// to and from XML files using the option mechanism.
/// </summary>
public abstract class ConfigurableApplication : CommandApplication
{
readonly XNamespace configNs;
readonly XName configRoot;
static readonly XName nil = XName.Get("nil", XmlSchema.InstanceNamespace);
/// <summary>
/// Creates a new instance of the application.
/// </summary>
/// <param name="configNs">The namespace that holds the option elements.</param>
public ConfigurableApplication(XNamespace configNs)
{
this.configNs = configNs;
configRoot = configNs + "options";
}
/// <inheritdoc/>
protected override OptionArgumentFlags OptionFound(string option)
{
var flags = base.OptionFound(option);
if((flags & OptionArgumentFlags.HasArgument) == 0)
{
StoreOption(GetCanonicalOption(option), null, flags);
}
return flags;
}
/// <inheritdoc/>
protected override void OptionArgumentFound(string option, string? argument, OptionArgumentFlags flags)
{
base.OptionArgumentFound(option, argument, flags);
StoreOption(GetCanonicalOption(option), argument, flags);
}
/// <summary>
/// Loadfs configuration from a file.
/// </summary>
/// <param name="name">The name of the file.</param>
/// <param name="configFile">The file instance.</param>
/// <exception cref="ApplicationException">The configuration cannot be loaded.</exception>
public void LoadConfigXml(string name, IFileInfo configFile)
{
LogWriter.WriteLine($"Loading configuration from {configFile.Name}...");
using var stream = configFile.Open();
var doc = XDocument.Load(stream);
var root = doc.Root;
if(root.Name != configRoot)
{
throw new ApplicationException($"{name}: expected {configRoot} as root element, found {root.Name}.");
}
foreach(var elem in AttributeElements(root).Concat(root.Elements()))
{
LoadConfigElement(elem, null);
}
}
void LoadConfigElement(XElement element, string? prefix)
{
if(element.Name.Namespace != configNs)
{
// Ignore foreign elements
return;
}
var optionName = DecodeName(element.Name.LocalName);
if(prefix != null)
{
optionName = prefix + optionName;
}
bool? isNil = null;
if(element.Attribute(nil)?.Value is string nilValue)
{
isNil = XmlConvert.ToBoolean(nilValue);
}
var content = AttributeElements(element).Concat(element.Nodes());
if(!content.Any(n => n is XText or XElement))
{
var flags = OnOptionFound(optionName);
if((element.IsEmpty && isNil != false) || (isNil == true))
{
// Must be a switch or null optional argument
if((flags & OptionArgumentFlags.HasArgument) != 0)
{
if((flags & OptionArgumentFlags.RequiredArgument) == OptionArgumentFlags.RequiredArgument)
{
throw ArgumentExpected(optionName);
}
OnOptionArgumentFound(optionName, null, flags);
}
}else{
// May be a switch or empty string
if((flags & OptionArgumentFlags.HasArgument) != 0)
{
OnOptionArgumentFound(optionName, "", flags);
}
}
}else if(isNil == true)
{
throw new ApplicationException($"Option {optionName} is set to nil but it has content.");
}
var innerPrefix = optionName + ":";
foreach(var child in content)
{
switch(child)
{
case XText childText:
var flags = OnOptionFound(optionName);
if((flags & OptionArgumentFlags.HasArgument) == 0)
{
throw ArgumentNotExpected(optionName);
}
OnOptionArgumentFound(optionName, childText.Value, flags);
break;
case XElement childElement:
LoadConfigElement(childElement, innerPrefix);
break;
}
}
}
static IEnumerable<XElement> AttributeElements(XElement element)
{
return element.Attributes()
.Where(a => !a.IsNamespaceDeclaration && a.Name.Namespace == XNamespace.None)
.Select(a => new XElement(element.Name.Namespace + a.Name.LocalName, a.Value));
}
CapturedOptions? capturedOptions;
class CapturedOptions
{
public XDocument Document { get; }
public XElement Root { get; }
public ConditionalWeakTable<XElement, object?> MustRemainElements { get; }
public CapturedOptions(XName rootName)
{
Document = new XDocument
(
Root = new XElement(rootName)
);
MustRemainElements = new();
}
}
/// <summary>
/// Call to start capturing provided options to save as XML.
/// </summary>
protected void CaptureOptions()
{
capturedOptions = new(configRoot);
}
static string EncodeName(string name)
{
var encoded = XmlConvert.EncodeLocalName(name);
if(encoded.StartsWith("xml", StringComparison.OrdinalIgnoreCase))
{
// These names are reserved in XML
return $"_x{(int)encoded[0]:X4}_{encoded.Substring(1)}";
}
return encoded;
}
static string DecodeName(string name)
{
return XmlConvert.DecodeName(name);
}
void StoreOption(string option, string? argument, OptionArgumentFlags flags)
{
if(capturedOptions != null)
{
var path = option.Split(':');
var elem = capturedOptions.Root;
foreach(var component in path)
{
elem.Add(elem = new XElement(configNs + EncodeName(component)));
}
if((flags & OptionArgumentFlags.AllowMultiple) != 0)
{
capturedOptions.MustRemainElements.Add(elem, null);
}
if(argument != null)
{
elem.Value = argument;
if(String.IsNullOrWhiteSpace(argument))
{
elem.Add(new XAttribute(XNamespace.Xml + "space", "preserve"));
}
}
}
}
void SimplifyOptions(XElement elem, bool root)
{
if(!root)
{
while(elem.NextNode is XElement nextElem && nextElem.Name == elem.Name)
{
// Merge content with the following element
foreach(var attr in nextElem.Attributes())
{
elem.Add(attr);
}
foreach(var elem2 in nextElem.Elements())
{
elem.Add(elem2);
}
nextElem.Remove();
}
}
foreach(var inner in elem.Elements().ToList())
{
var name = inner.Name;
if(name.Namespace != configNs)
{
// In case some non-config elements get added
continue;
}
if(inner.IsEmpty && !inner.Attributes().Any(a => a.Name.NamespaceName == XNamespace.None))
{
// Can't simplify switches
continue;
}
var localName = name.LocalName;
if(!inner.Elements().Any())
{
// This is a normal option
if(capturedOptions!.MustRemainElements.TryGetValue(inner, out _))
{
// Don't change this to an attribute
continue;
}
if(elem.Attribute(localName) == null)
{
elem.Add(new XAttribute(localName, inner.Value));
inner.Remove();
}
}else{
// Container for options
SimplifyOptions(inner, false);
}
}
}
/// <summary>
/// Serializase the current options into a stream.
/// </summary>
/// <param name="stream">The stream to write the XML to.</param>
/// <exception cref="InvalidOperationException">
/// There are no options to save to the stream.
/// </exception>
public void SaveConfigXml(Stream stream)
{
if(capturedOptions == null)
{
throw new InvalidOperationException("No options were stored.");
}
SimplifyOptions(capturedOptions.Root, true);
var settings = new XmlWriterSettings
{
Encoding = new UTF8Encoding(false),
CloseOutput = false,
Indent = true,
OmitXmlDeclaration = true
};
using var writer = XmlWriter.Create(stream, settings);
capturedOptions.Document.Save(writer);
}
}
}