forked from tertle/com.bovinelabs.analyzers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProjectFilesGeneration.cs
201 lines (172 loc) · 6.94 KB
/
ProjectFilesGeneration.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
// <copyright file="ProjectFilesGeneration.cs" company="Timothy Raines">
// Copyright (c) Timothy Raines. All rights reserved.
// </copyright>
namespace BovineLabs.Analyzers
{
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using UnityEditor;
/// <summary>
/// Customize the project file generation with Roslyn Analyzers and custom c# version.
/// </summary>
[InitializeOnLoad]
public class ProjectFilesGeneration : AssetPostprocessor
{
#if ENABLE_VSTU
private const string CSharpVersion = "7.3";
#endif
static ProjectFilesGeneration()
{
#if ENABLE_VSTU
SyntaxTree.VisualStudio.Unity.Bridge.ProjectFilesGenerator.ProjectFileGeneration += (name, contents) =>
{
XDocument xml = XDocument.Parse(contents);
UpgradeProjectFile(xml);
// Write to the csproj file:
using (Utf8StringWriter str = new Utf8StringWriter())
{
xml.Save(str);
return str.ToString();
}
};
#else
}
private static string OnGeneratedCSProject(string path, string contents)
{
XDocument xml = XDocument.Parse(contents);
UpgradeProjectFile(xml);
// Write to the csproj file:
using (Utf8StringWriter str = new Utf8StringWriter())
{
xml.Save(str);
return str.ToString();
}
#endif
}
private static void UpgradeProjectFile(XDocument doc)
{
var projectContentElement = doc.Root;
if (projectContentElement != null)
{
XNamespace xmlns = projectContentElement.Name.NamespaceName; // do not use var
SetRoslynAnalyzers(projectContentElement, xmlns);
#if UNITY_VTSU
SetCSharpVersion(projectContentElement, xmlns);
#endif
}
}
/// <summary>
/// Add everything from root RoslynAnalyzers folder and packages RoslynAnalyzers to csproj.
/// </summary>
private static void SetRoslynAnalyzers(XElement projectContentElement, XNamespace xmlns)
{
var currentDirectory = Directory.GetCurrentDirectory();
var request = UnityEditor.PackageManager.Client.List(offlineMode: true);
while (!request.IsCompleted) { }
var itemGroup = new XElement(xmlns + "ItemGroup");
ProcessFolder(currentDirectory);
foreach (var file in request.Result)
ProcessFolder(file.assetPath);
projectContentElement.Add(itemGroup);
void ProcessFolder(string folder)
{
foreach (var folderPartial in Util.GetDirectory().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
var roslynAnalyzerBaseDir = new DirectoryInfo(Path.Combine(folder, folderPartial));
if (!roslynAnalyzerBaseDir.Exists)
{
//Debug.LogWarning($"Directory {roslynAnalyzerBaseDir} does not exist, please place analyzers in correct location.");
return;
}
var relPaths = roslynAnalyzerBaseDir.GetFiles("*", SearchOption.AllDirectories)
.Select(x => x.FullName.Substring(folder.Length + 1));
foreach (var file in relPaths)
AddFileToProject(file);
}
}
void AddFileToProject(string file)
{
var extension = new FileInfo(file).Extension;
switch (extension)
{
case ".dll":
{
var reference = new XElement(xmlns + "Analyzer");
reference.Add(new XAttribute("Include", file));
itemGroup.Add(reference);
break;
}
case ".json":
{
var reference = new XElement(xmlns + "AdditionalFiles");
reference.Add(new XAttribute("Include", file));
itemGroup.Add(reference);
break;
}
case ".ruleset":
{
SetOrUpdateProperty(projectContentElement, xmlns, "CodeAnalysisRuleSet", existing => file);
break;
}
}
}
}
// Don't need to do this for Rider as it has built in support for setting c# version.
#if UNITY_VTSU
private static void SetCSharpVersion(XContainer projectContentElement, XNamespace ns)
{
// Find all PropertyGroups with Condition defining a Configuration and a Platform:
XElement[] nodes = projectContentElement.Descendants()
.Where(child =>
child.Name.LocalName == "PropertyGroup"
&& (child.Attributes().FirstOrDefault(attr => attr.Name.LocalName == "Condition")?.Value
.Contains("'$(Configuration)|$(Platform)'") ?? false))
.ToArray();
// Add <LangVersion>7.3</LangVersion> to these PropertyGroups:
foreach (XElement node in nodes)
{
node.Add(new XElement(ns + "LangVersion", CSharpVersion));
}
}
#endif
private static void SetOrUpdateProperty(
XContainer root,
XNamespace xmlns,
string name,
Func<string, string> updater)
{
var element = root.Elements(xmlns + "PropertyGroup").Elements(xmlns + name).FirstOrDefault();
if (element != null)
{
var result = updater(element.Value);
if (result != element.Value)
{
element.SetValue(result);
}
}
else
{
AddProperty(root, xmlns, name, updater(string.Empty));
}
}
// Adds a property to the first property group without a condition
private static void AddProperty(XContainer root, XNamespace xmlns, string name, string content)
{
var propertyGroup = root.Elements(xmlns + "PropertyGroup")
.FirstOrDefault(e => !e.Attributes(xmlns + "Condition").Any());
if (propertyGroup == null)
{
propertyGroup = new XElement(xmlns + "PropertyGroup");
root.AddFirst(propertyGroup);
}
propertyGroup.Add(new XElement(xmlns + name, content));
}
private class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
}
}