forked from angularsen/UnitsNet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNanoFrameworkGenerator.cs
More file actions
394 lines (333 loc) · 16.4 KB
/
NanoFrameworkGenerator.cs
File metadata and controls
394 lines (333 loc) · 16.4 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
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using CodeGen.Generators.NanoFrameworkGen;
using CodeGen.Helpers;
using CodeGen.Helpers.UnitEnumValueAllocation;
using CodeGen.JsonTypes;
using NuGet.Common;
using Serilog;
using ILogger = NuGet.Common.ILogger;
namespace CodeGen.Generators
{
/// <summary>
/// Code generator for nanoFramework
/// Will generate 1 nanoFramework project per unit, a common property folder and a common package file
/// </summary>
internal static class NanoFrameworkGenerator
{
/// <summary>
/// These projects require inclusion of Math NuGet package.
/// </summary>
internal static readonly List<string> ProjectsRequiringMath = new()
{
"Angle",
"Frequency",
"Pressure",
"Turbidity",
"WarpingMomentOfInertia"
};
/// <summary>
/// Create the root folder NanoFramework
/// Create all the quantities unit and quantities file
/// Create all individual nanoFramework projects
/// Create common package file
/// Create common properties file
/// </summary>
/// <param name="rootDir">The root directory</param>
/// <param name="quantities">The quantities to create</param>
/// <param name="quantityNameToUnitEnumValues"></param>
public static void Generate(string rootDir, Quantity[] quantities, QuantityNameToUnitEnumValues quantityNameToUnitEnumValues)
{
// get latest version of .NET nanoFramework mscorlib
ILogger logger = NullLogger.Instance;
NanoFrameworkVersions versions = ParseCurrentNanoFrameworkVersions(rootDir);
logger.LogInformation($"Referencing nanoFramework.CoreLibrary {versions.MscorlibNugetVersion}");
logger.LogInformation($"Referencing nanoFramework.System.Math {versions.MathNugetVersion}");
var outputDir = Path.Combine(rootDir, "UnitsNet.NanoFramework", "GeneratedCode");
var outputQuantities = Path.Combine(outputDir, "Quantities");
var outputUnits = Path.Combine(outputDir, "Units");
var outputProperties = Path.Combine(outputDir, "Properties");
// Ensure output directories exist
Directory.CreateDirectory(outputQuantities);
Directory.CreateDirectory(outputUnits);
Directory.CreateDirectory(outputProperties);
var lengthNuspecFile = Path.Combine(outputDir, "Length", "UnitsNet.NanoFramework.Length.nuspec");
var projectVersion = ParseVersion(File.ReadAllText(lengthNuspecFile),
new Regex(@"<version>(?<version>[\d.]+)(?<suffix>-[a-z\d]+)?<\/version>", RegexOptions.IgnoreCase),
"projectVersion");
foreach (Quantity quantity in quantities)
{
var projectPath = Path.Combine(outputDir, quantity.Name);
Directory.CreateDirectory(projectPath);
GeneratePackageConfig(
projectPath,
quantity.Name,
versions.MscorlibNugetVersion,
versions.MathNugetVersion);
GenerateNuspec(
projectPath,
quantity,
versions.MscorlibNugetVersion,
versions.MathNugetVersion);
UnitEnumNameToValue unitEnumValues = quantityNameToUnitEnumValues[quantity.Name];
GenerateUnitType(quantity, Path.Combine(outputUnits, $"{quantity.Name}Unit.g.cs"), unitEnumValues);
GenerateQuantity(quantity, Path.Combine(outputQuantities, $"{quantity.Name}.g.cs"));
GenerateProject(quantity, Path.Combine(projectPath, $"{quantity.Name}.nfproj"), versions);
Log.Information("✅ {Quantity} (nanoFramework)", quantity.Name);
}
Log.Information("");
GenerateProperties(Path.Combine(outputProperties, "AssemblyInfo.cs"), projectVersion);
GenerateSolution(quantities, outputDir);
var unitCount = quantities.SelectMany(q => q.Units).Count();
Log.Information("");
Log.Information("Total of {UnitCount} units and {QuantityCount} quantities (nanoFramework)", unitCount, quantities.Length);
Log.Information("");
}
/// <summary>
/// Updates existing nanoFramework projects and nuspec files with the latest versions.
/// </summary>
/// <param name="rootDir">The root directory</param>
/// <param name="quantities">The quantities to update nuspec files</param>
public static bool UpdateNanoFrameworkDependencies(
string rootDir,
Quantity[] quantities)
{
// working path
var path = Path.Combine(rootDir, "UnitsNet.NanoFramework\\GeneratedCode");
Log.Information("");
Log.Information("Restoring .NET nanoFramework projects");
// run nuget CLI
using var nugetRestore = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = Path.Combine(rootDir, ".tools/nuget.exe"),
Arguments = $"restore {path}\\UnitsNet.nanoFramework.sln",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true
}
};
// start nuget CLI and wait for exit
if (!nugetRestore.Start())
{
Log.Information("");
Log.Information("Failed to start nuget CLI to restore .NET nanoFramework projects");
Log.Information("");
}
else
{
// wait for exit, within 2 minutes
if (!nugetRestore.WaitForExit((int)TimeSpan.FromMinutes(2).TotalMilliseconds))
{
Log.Information("");
Log.Information("Failed to complete execution of nuget CLI to restore .NET nanoFramework projects");
Log.Information("");
}
else
{
if (nugetRestore.ExitCode == 0)
{
Log.Information("Done!");
Log.Information("");
}
else
{
Log.Information("");
Log.Information("nuget CLI executed with {ExitCode} exit code", nugetRestore.ExitCode);
Log.Information("{StandardError}", nugetRestore.StandardError.ReadToEnd());
return false;
}
}
}
Log.Information("");
Log.Information("Updating .NET nanoFramework references using nuget CLI");
// run nuget CLI to perform update
using var nugetUpdate = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = Path.Combine(rootDir, ".tools/NuGet.exe"),
Arguments = $"update {path}\\UnitsNet.nanoFramework.sln -PreRelease",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true
}
};
// start nuget CLI and wait for exit
if (!nugetUpdate.Start())
{
Log.Information("");
Log.Information("Failed to start nuget CLI to update .NET nanoFramework projects");
Log.Information("");
}
else
{
// wait for exit, within 2 minutes
if (!nugetUpdate.WaitForExit((int)TimeSpan.FromMinutes(2).TotalMilliseconds))
{
Log.Information("");
Log.Information("Failed to complete execution of nuget CLI to update .NET nanoFramework projects");
Log.Information("");
}
else
{
if (nugetUpdate.ExitCode == 0)
{
Log.Information("Done!");
Log.Information("");
Log.Information("Updating .NET nanoFramework nuspec files");
Log.Information("");
foreach (Quantity quantity in quantities)
{
var projectPath = Path.Combine(path, quantity.Name);
// read packages.config content
var packagesConfig = Path.Combine(projectPath, "packages.config");
var packagesConfigText = File.ReadAllText(packagesConfig);
var mscorlibVersion = ParseVersion(packagesConfigText,
new Regex("CoreLibrary\\\" version=\\\"(?<version>.+)\\\" targetFramework", RegexOptions.IgnoreCase),
"projectVersion");
// don't throw on failure because not all packages have System.Math
var mathVersion = ParseVersion(packagesConfigText,
new Regex("Math\\\" version=\\\"(?<version>.+)\\\" targetFramework", RegexOptions.IgnoreCase),
"projectVersion",
false);
// update nuspec
GenerateNuspec(
projectPath,
quantity,
mscorlibVersion,
mathVersion);
Log.Information("✅ {Quantity} (nanoFramework)", quantity.Name);
}
}
else
{
Log.Information("");
Log.Information("nuget CLI executed with {ExitCode} exit code", nugetUpdate.ExitCode);
Log.Information("{StandardError}", nugetUpdate.StandardError.ReadToEnd());
return false;
}
}
}
Log.Information("");
return true;
}
private static NanoFrameworkVersions ParseCurrentNanoFrameworkVersions(string rootDir)
{
// Angle has both mscorlib and System.Math dependency
var generatedCodePath = Path.Combine(rootDir, "UnitsNet.NanoFramework", "GeneratedCode");
var angleProjectFile = Path.Combine(generatedCodePath, "Angle", "Angle.nfproj");
var projectFileContent = File.ReadAllText(angleProjectFile);
// <Reference Include="mscorlib, Version=1.10.5.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
var mscorlibVersion = ParseVersion(projectFileContent,
new Regex(@"<Reference Include=""mscorlib,\s*Version=(?<version>[\d\.]+),.*"">", RegexOptions.IgnoreCase),
"mscorlib assembly version");
// <HintPath>..\packages\nanoFramework.CoreLibrary.1.10.5-preview.18\lib\mscorlib.dll</HintPath>
var mscorlibNuGetVersion = ParseVersion(projectFileContent,
new Regex(@"<HintPath>.*[\\\/]nanoFramework\.CoreLibrary\.(?<version>.*?)[\\\/]lib[\\\/]mscorlib.dll<", RegexOptions.IgnoreCase),
"nanoFramework.CoreLibrary nuget version");
// <Reference Include="System.Math, Version=1.4.1.0, Culture=neutral, PublicKeyToken=c07d481e9758c731">
var mathVersion = ParseVersion(projectFileContent,
new Regex(@"<Reference Include=""System.Math,\s*Version=(?<version>[\d\.]+),.*"">", RegexOptions.IgnoreCase),
"System.Math assembly version");
// <HintPath>..\packages\nanoFramework.System.Math.1.4.1-preview.7\lib\System.Math.dll</HintPath>
var mathNuGetVersion = ParseVersion(projectFileContent,
new Regex(@"<HintPath>.*[\\\/]nanoFramework\.System\.Math\.(?<version>.*?)[\\\/]lib[\\\/]System.Math.dll<", RegexOptions.IgnoreCase),
"nanoFramework.System.Math nuget version");
return new NanoFrameworkVersions(mscorlibVersion, mscorlibNuGetVersion, mathVersion, mathNuGetVersion);
}
private static string ParseVersion(
string projectFileContent,
Regex versionRegex,
string descriptiveName,
bool throwOnFailure = true)
{
Match match = versionRegex.Match(projectFileContent);
if (!match.Success && throwOnFailure)
{
throw new InvalidOperationException($"Unable to parse version {descriptiveName} from project file.");
}
return match.Groups["version"].Value;
}
private static void GeneratePackageConfig(
string projectPath,
string quantityName,
string mscorlibNuGetVersion,
string mathNuGetVersion)
{
var filePath = Path.Combine(projectPath, "packages.config");
var content = GeneratePackageConfigFile(quantityName, mscorlibNuGetVersion, mathNuGetVersion);
File.WriteAllText(filePath, content);
}
private static void GenerateNuspec(
string projectPath,
Quantity quantity,
string mscorlibNuGetVersion,
string mathNuGetVersion)
{
var filePath = Path.Combine(projectPath, $"UnitsNet.NanoFramework.{quantity.Name}.nuspec");
var content = new NuspecGenerator(
quantity,
mscorlibNuGetVersion,
mathNuGetVersion).Generate();
File.WriteAllText(filePath, content);
}
private static void GenerateProperties(string filePath, string version)
{
var content = new PropertyGenerator(version).Generate();
File.WriteAllText(filePath, content);
Log.Information("✅ AssemblyInfo.cs (nanoFramework)");
}
private static void GenerateUnitType(Quantity quantity, string filePath, UnitEnumNameToValue unitEnumValues)
{
var content = new UnitTypeGenerator(quantity, unitEnumValues).Generate();
File.WriteAllText(filePath, content);
}
private static void GenerateQuantity(Quantity quantity, string filePath)
{
var content = new QuantityGenerator(quantity).Generate();
// Replace any Math.PI by the real number 3.1415926535897931
content = content.Replace("Math.PI", "3.1415926535897931");
// Replace Math.Pow(0.3048, 4) by 0.0086309748412416
content = content.Replace("Math.Pow(0.3048, 4)", "0.0086309748412416");
// Replace Math.Pow(2.54e-2, 4) by 0.0000004162314256
content = content.Replace("Math.Pow(2.54e-2, 4)", "0.0000004162314256");
File.WriteAllText(filePath, content);
}
private static void GenerateProject(Quantity quantity, string filePath, NanoFrameworkVersions versions)
{
var content = new ProjectGenerator(quantity, versions).Generate();
File.WriteAllText(filePath, content);
}
private static void GenerateSolution(Quantity[] quantities, string outputDir)
{
var content = new SolutionGenerator(quantities).Generate();
var filePath = Path.Combine(outputDir, "UnitsNet.nanoFramework.sln");
File.WriteAllText(filePath, content);
Log.Information("✅ UnitsNet.nanoFramework.sln (nanoFramework)");
}
private static string GeneratePackageConfigFile(
string quantityName,
string mscorlibNuGetVersion,
string mathNuGetVersion)
{
MyTextWriter writer = new();
writer.WL($@"
<?xml version=""1.0"" encoding=""utf-8""?>
<packages>
<package id=""nanoFramework.CoreLibrary"" version=""{mscorlibNuGetVersion}"" targetFramework=""netnanoframework10"" />");
if (ProjectsRequiringMath.Contains(quantityName))
{
writer.WL($@"
<package id=""nanoFramework.System.Math"" version=""{mathNuGetVersion}"" targetFramework=""netnanoframework10"" />");
}
writer.WL($@"</packages>");
return writer.ToString();
}
}
}