/
ConfigFileFinder.cs
213 lines (173 loc) · 7.4 KB
/
ConfigFileFinder.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
public static class ConfigFileFinder
{
const string FodyWeaversConfigFileName = "FodyWeavers.xml";
static readonly XNamespace schemaNamespace = XNamespace.Get("http://www.w3.org/2001/XMLSchema");
static readonly XNamespace schemaInstanceNamespace = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
public static IEnumerable<WeaverConfigFile> FindWeaverConfigFiles(string solutionDirectoryPath, string projectDirectory, ILogger logger)
{
var solutionConfigFilePath = Path.Combine(solutionDirectoryPath, FodyWeaversConfigFileName);
if (File.Exists(solutionConfigFilePath))
{
logger.LogDebug($"Found path to weavers file '{solutionConfigFilePath}'.");
yield return new WeaverConfigFile(solutionConfigFilePath) {IsGlobal = true};
}
var projectConfigFilePath = Path.Combine(projectDirectory, FodyWeaversConfigFileName);
if (File.Exists(projectConfigFilePath))
{
logger.LogDebug($"Found path to weavers file '{projectConfigFilePath}'.");
yield return new WeaverConfigFile(projectConfigFilePath);
}
}
public static Dictionary<string, WeaverConfigEntry> ParseWeaverConfigEntries(IEnumerable<WeaverConfigFile> configFiles)
{
var entries = new Dictionary<string, WeaverConfigEntry>(StringComparer.OrdinalIgnoreCase);
var executionOrders = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var configFile in configFiles)
{
foreach (var element in configFile.Document.Root.Elements())
{
var elementName = element.Name.LocalName;
if (!executionOrders.TryGetValue(elementName, out var executionOrder))
{
executionOrders.Add(elementName, executionOrder = executionOrders.Count);
}
entries[elementName] = new WeaverConfigEntry
{
ExecutionOrder = executionOrder,
ConfigFile = configFile,
ElementName = elementName,
Content = element.ToString()
};
}
}
return entries;
}
public static WeaverConfigFile GenerateDefault(string projectDirectory, List<WeaverEntry> weaverEntries, bool generateXsd)
{
var projectConfigFilePath = Path.Combine(projectDirectory, FodyWeaversConfigFileName);
if (File.Exists(projectConfigFilePath))
{
return new WeaverConfigFile(projectConfigFilePath);
}
var root = new XElement("Weavers", SchemaInstanceAttributes);
var weaverConfig = new XDocument(root);
var elements = weaverEntries
.Select(entry => new XElement(entry.ElementName))
.ToArray();
root.Add(elements);
weaverConfig.Save(projectConfigFilePath);
var writerSettings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
Indent = true
};
using (var writer = XmlWriter.Create(projectConfigFilePath, writerSettings))
{
weaverConfig.Save(writer);
}
if (generateXsd)
{
CreateSchemaForConfig(projectConfigFilePath, weaverEntries);
}
return new WeaverConfigFile(projectConfigFilePath);
}
static void CreateSchemaForConfig(string projectConfigFilePath, IEnumerable<WeaverEntry> weavers)
{
var schema = XDocument.Parse(Fody.Properties.Resources.FodyWeavers_SchemaTemplate);
var baseNode = schema.Descendants().First(item => item.Name == schemaNamespace.GetName("all"));
var fragments = weavers.Select(CreateItemFragment);
baseNode.Add(fragments);
var filePath = Path.ChangeExtension(projectConfigFilePath, ".xsd");
const SaveOptions saveOptions = SaveOptions.OmitDuplicateNamespaces | SaveOptions.DisableFormatting;
if (File.Exists(filePath))
{
try
{
var existing = XDocumentEx.Load(filePath).ToString(saveOptions);
if (string.Equals(existing, schema.ToString(saveOptions)))
{
// don't touch existing file if it is up to date
return;
}
}
catch
{
// invalid xsd, overwrite always...
}
}
schema.Save(filePath, SaveOptions.OmitDuplicateNamespaces);
}
static XElement CreateItemFragment(WeaverEntry weaver)
{
var elementName = weaver.ElementName;
var weaverFile = weaver.AssemblyPath;
var element = new XElement(schemaNamespace.GetName("element"),
new XAttribute("name", elementName),
new XAttribute("minOccurs", 0),
new XAttribute("maxOccurs", 1));
var fragmentFile = Path.ChangeExtension(weaverFile, ".xcf");
if (File.Exists(fragmentFile))
{
try
{
element.Add(XElement.Parse(File.ReadAllText(fragmentFile)));
return element;
}
catch (Exception exception)
{
throw new WeavingException($"The fragment file ({fragmentFile}) could not be read. Exception message: {exception.Message}");
}
}
element.Add(new XAttribute("type", "xs:anyType"));
return element;
}
public static void EnsureSchemaIsUpToDate(string solutionDirectory, string projectDirectory, IEnumerable<WeaverEntry> weavers, bool defaultGenerateXsd)
{
var projectConfigFilePath = Path.Combine(projectDirectory, FodyWeaversConfigFileName);
var solutionConfigFilePath = Path.Combine(solutionDirectory, FodyWeaversConfigFileName);
try
{
if (!File.Exists(projectConfigFilePath) && File.Exists(solutionConfigFilePath))
return;
var doc = XDocumentEx.Load(projectConfigFilePath);
if (!ShouldGenerateXsd(doc, defaultGenerateXsd))
{
return;
}
var hasNamespace = doc.Root.Attributes()
.Any(attr => !attr.IsNamespaceDeclaration &&
attr.Name.LocalName == "noNamespaceSchemaLocation" &&
string.Equals(attr.Value, "FodyWeavers.xsd", StringComparison.OrdinalIgnoreCase));
if (!hasNamespace)
{
doc.Root.Add(SchemaInstanceAttributes);
doc.Save(projectConfigFilePath);
}
CreateSchemaForConfig(projectConfigFilePath, weavers);
}
catch (Exception exception)
{
throw new WeavingException($"Failed to update schema for ({projectConfigFilePath}). Exception message: {exception.Message}");
}
}
static bool ShouldGenerateXsd(XDocument doc, bool defaultGenerateXsd)
{
if (doc.Root.TryReadBool("GenerateXsd", out var generateXsd))
{
return generateXsd;
}
return defaultGenerateXsd;
}
static XAttribute[] SchemaInstanceAttributes =>
new[]
{
new XAttribute(XNamespace.Xmlns + "xsi", schemaInstanceNamespace.NamespaceName),
new XAttribute(schemaInstanceNamespace.GetName("noNamespaceSchemaLocation"), "FodyWeavers.xsd"),
};
}