-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
AspNetSdkBaselineTest.cs
530 lines (458 loc) · 26.2 KB
/
AspNetSdkBaselineTest.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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.RegularExpressions;
using FluentAssertions;
using Microsoft.AspNetCore.Razor.Tasks;
using Microsoft.NET.TestFramework;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.NET.Sdk.Razor.Tests
{
[Trait("AspNetCore", "BaselineTest")]
public class AspNetSdkBaselineTest : AspNetSdkTest
{
private static readonly JsonSerializerOptions BaselineSerializationOptions = new() { WriteIndented = true };
protected static readonly string DotNetJSHashRegexPattern = "\\.[a-z0-9]{10}\\.js";
protected static readonly string DotNetJSHashTemplate = ".[[hash]].js";
private string _baselinesFolder;
#if GENERATE_SWA_BASELINES
public static bool GenerateBaselines = true;
#else
public static bool GenerateBaselines = false;
#endif
private bool _generateBaselines = GenerateBaselines;
// This allows templatizing paths that don't have a deterministic name, for example the files we gzip or brotli as part
// of Blazor compilations. We only need to do this for the manifest since the tests for files don't use the original
// path. Returning null avoids any transformation
protected Func<StaticWebAsset, string, StaticWebAsset, string> PathTemplatizer { get; set; } = (asset, originalValue, related) => null;
public AspNetSdkBaselineTest(ITestOutputHelper log) : base(log)
{
TestAssembly = Assembly.GetCallingAssembly();
var testAssemblyMetadata = TestAssembly.GetCustomAttributes<AssemblyMetadataAttribute>();
RuntimeVersion = testAssemblyMetadata.SingleOrDefault(a => a.Key == "NetCoreAppRuntimePackageVersion").Value;
DefaultPackageVersion = testAssemblyMetadata.SingleOrDefault(a => a.Key == "DefaultTestBaselinePackageVersion").Value;
}
public AspNetSdkBaselineTest(ITestOutputHelper log, bool generateBaselines) : this(log)
{
_generateBaselines = generateBaselines;
}
public TestAsset ProjectDirectory { get; set; }
public string RuntimeVersion { get; set; }
public string DefaultPackageVersion { get; set; }
public string BaselinesFolder =>
_baselinesFolder ??= ComputeBaselineFolder();
protected Assembly TestAssembly { get; }
protected virtual string ComputeBaselineFolder() =>
Path.Combine(TestContext.GetRepoRoot() ?? AppContext.BaseDirectory, "src", "Tests", "Microsoft.NET.Sdk.Razor.Tests", "StaticWebAssetsBaselines");
protected virtual string EmbeddedResourcePrefix => string.Join('.', "Microsoft.NET.Sdk.Razor.Tests", "StaticWebAssetsBaselines");
public StaticWebAssetsManifest LoadBuildManifest(string suffix = "", [CallerMemberName] string name = "")
{
if (_generateBaselines)
{
return default;
}
else
{
using var stream = GetManifestEmbeddedResource(suffix, name, "Build");
var manifest = StaticWebAssetsManifest.FromStream(stream);
return manifest;
}
}
public StaticWebAssetsManifest LoadPublishManifest(string suffix = "", [CallerMemberName] string name = "")
{
if (_generateBaselines)
{
return default;
}
else
{
using var stream = GetManifestEmbeddedResource(suffix, name, "Publish");
var manifest = StaticWebAssetsManifest.FromStream(stream);
return manifest;
}
}
private void ApplyTemplatizerToAssets(StaticWebAssetsManifest manifest)
{
var assets = manifest.Assets;
var assetsById = manifest.Assets.ToDictionary(a => a.Identity);
for (int i = 0; i < assets.Length; i++)
{
var asset = assets[i];
RemoveHashFromAsset(asset);
var relatedAsset = string.IsNullOrEmpty(asset.RelatedAsset) || !assetsById.TryGetValue(asset.RelatedAsset, out var related) ?
null : related;
asset.Identity = PathTemplatizer(asset, asset.Identity, null) ?? asset.Identity;
asset.RelatedAsset = PathTemplatizer(asset, asset.RelatedAsset, relatedAsset) ?? asset.RelatedAsset;
asset.OriginalItemSpec = PathTemplatizer(asset, asset.OriginalItemSpec, null) ?? asset.OriginalItemSpec;
}
}
private void RemoveHashFromAsset(StaticWebAsset asset)
{
asset.RelativePath = Regex.Replace(asset.RelativePath, DotNetJSHashRegexPattern, DotNetJSHashTemplate);
asset.Identity = Regex.Replace(asset.Identity, DotNetJSHashRegexPattern, DotNetJSHashTemplate);
asset.OriginalItemSpec = Regex.Replace(asset.OriginalItemSpec, DotNetJSHashRegexPattern, DotNetJSHashTemplate);
asset.RelatedAsset = Regex.Replace(asset.RelatedAsset, DotNetJSHashRegexPattern, DotNetJSHashTemplate);
}
private void UpdateCustomPackageVersions(string restorePath, StaticWebAssetsManifest manifest)
{
foreach (var asset in manifest.Assets)
{
asset.Identity = UpdateAssetVersion(restorePath, asset.Identity);
asset.ContentRoot = UpdateAssetVersion(restorePath, asset.ContentRoot);
asset.ContentRoot = asset.ContentRoot.EndsWith(Path.DirectorySeparatorChar) ? asset.ContentRoot : asset.ContentRoot + Path.DirectorySeparatorChar;
asset.OriginalItemSpec = UpdateAssetVersion(restorePath, asset.OriginalItemSpec);
asset.RelatedAsset = UpdateAssetVersion(restorePath, asset.RelatedAsset);
}
string UpdateAssetVersion(string restorePath, string property)
{
if (property.Contains(restorePath))
{
var segments = property.Substring(restorePath.Length).Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
ref var versionSegment = ref segments[1];
if (versionSegment != RuntimeVersion && versionSegment != DefaultPackageVersion)
{
versionSegment = "[[CustomPackageVersion]]";
property = Path.Combine(segments.Prepend(restorePath).ToArray());
}
}
return property;
}
}
protected void AssertBuildAssets(
StaticWebAssetsManifest manifest,
string outputFolder,
string intermediateOutputPath,
string suffix = "",
[CallerMemberName] string name = "")
{
var fileEnumerationOptions = new EnumerationOptions { RecurseSubdirectories = true };
var wwwRootFolder = Path.Combine(outputFolder, "wwwroot");
var wwwRootFiles = Directory.Exists(wwwRootFolder) ?
Directory.GetFiles(wwwRootFolder, "*", fileEnumerationOptions) :
Array.Empty<string>();
var computedFiles = manifest.Assets
.Where(a => a.SourceType is StaticWebAsset.SourceTypes.Computed &&
a.AssetKind is not StaticWebAsset.AssetKinds.Publish);
// We keep track of assets that need to be copied to the output folder.
// In addition to that, we copy assets that are defined somewhere different
// from their content root folder when the content root does not match the output folder.
// We do this to allow copying things like Publish assets to temporary locations during the
// build process if they are later on going to be transformed.
var copyToOutputDirectoryFiles = manifest.Assets
.Where(a => a.ShouldCopyToOutputDirectory())
.Select(a => Path.GetFullPath(Path.Combine(outputFolder, "wwwroot", a.RelativePath)))
.Concat(manifest.Assets
.Where(a => !a.HasContentRoot(Path.Combine(outputFolder, "wwwroot")) && File.Exists(a.Identity) && !File.Exists(Path.Combine(a.ContentRoot, a.RelativePath)))
.Select(a => Path.GetFullPath(Path.Combine(a.ContentRoot, a.RelativePath))))
.ToArray();
if (!_generateBaselines)
{
var expected = LoadExpectedFilesBaseline(manifest.ManifestType, outputFolder, intermediateOutputPath, suffix, name)
.OrderBy(f => f, StringComparer.Ordinal);
var existingFiles = wwwRootFiles.Concat(computedFiles.Select(a => PathTemplatizer(a, a.Identity, null) ?? a.Identity)).Concat(copyToOutputDirectoryFiles)
.Distinct()
.Select(f => Regex.Replace(f, DotNetJSHashRegexPattern, DotNetJSHashTemplate))
.OrderBy(f => f, StringComparer.Ordinal)
.ToArray();
existingFiles.ShouldBeEquivalentTo(expected);
}
else
{
var templatizedFiles = TemplatizeExpectedFiles(
wwwRootFiles
.Concat(computedFiles.Select(a => PathTemplatizer(a, a.Identity, null) ?? a.Identity))
.Concat(copyToOutputDirectoryFiles)
.Distinct()
.OrderBy(f => f, StringComparer.Ordinal)
.ToArray(),
TestContext.Current.NuGetCachePath,
outputFolder,
ProjectDirectory.TestRoot,
intermediateOutputPath)
.OrderBy(o => o, StringComparer.Ordinal);
File.WriteAllText(
GetExpectedFilesPath(suffix, name, manifest.ManifestType),
JsonSerializer.Serialize(templatizedFiles, BaselineSerializationOptions));
}
}
protected void AssertPublishAssets(
StaticWebAssetsManifest manifest,
string publishFolder,
string intermediateOutputPath,
string suffix = "",
[CallerMemberName] string name = "")
{
var fileEnumerationOptions = new EnumerationOptions { RecurseSubdirectories = true };
string wwwRootFolder = Path.Combine(publishFolder, "wwwroot");
var wwwRootFiles = Directory.Exists(wwwRootFolder) ?
Directory.GetFiles(wwwRootFolder, "*", fileEnumerationOptions) :
Array.Empty<string>();
// Computed publish assets must exist on disk (we do this check to quickly identify when something is not being
// generated vs when its being copied to the wrong place)
var computedFiles = manifest.Assets
.Where(a => a.SourceType is StaticWebAsset.SourceTypes.Computed &&
a.AssetKind is not StaticWebAsset.AssetKinds.Build);
// For assets that are copied to the publish folder, the path is always based on
// the wwwroot folder, the relative path and the base path for project or package
// assets.
var copyToPublishDirectoryFiles = manifest.Assets
.Where(a => !string.Equals(a.SourceId, manifest.Source, StringComparison.Ordinal) ||
!string.Equals(a.AssetMode, StaticWebAsset.AssetModes.Reference))
.Select(a => Path.Combine(wwwRootFolder, a.ComputeTargetPath("", Path.DirectorySeparatorChar)));
var existingFiles = wwwRootFiles.Concat(computedFiles.Select(f => PathTemplatizer(f, f.Identity, null) ?? f.Identity)).Concat(copyToPublishDirectoryFiles)
.Distinct()
.OrderBy(f => f, StringComparer.Ordinal)
.ToArray();
if (!_generateBaselines)
{
existingFiles = existingFiles.Select(f => Regex.Replace(f, DotNetJSHashRegexPattern, DotNetJSHashTemplate)).ToArray();
var expected = LoadExpectedFilesBaseline(manifest.ManifestType, publishFolder, intermediateOutputPath, suffix, name);
existingFiles.ShouldBeEquivalentTo(expected);
}
else
{
var templatizedFiles = TemplatizeExpectedFiles(
wwwRootFiles
.Concat(computedFiles.Select(f => PathTemplatizer(f, f.Identity, null) ?? f.Identity))
.Concat(copyToPublishDirectoryFiles)
.Distinct()
.OrderBy(f => f, StringComparer.Ordinal)
.ToArray(),
TestContext.Current.NuGetCachePath,
publishFolder,
ProjectDirectory.TestRoot,
intermediateOutputPath);
File.WriteAllText(
GetExpectedFilesPath(suffix, name, manifest.ManifestType),
JsonSerializer.Serialize(templatizedFiles, BaselineSerializationOptions));
}
}
public string[] LoadExpectedFilesBaseline(
string type,
string buildOrPublishPath,
string intermediateOutputPath,
string suffix,
string name)
{
if (!_generateBaselines)
{
using var filesBaselineStream = GetExpectedFilesEmbeddedResource(suffix, name, type);
return ApplyPathsToTemplatedFilePaths(
JsonSerializer.Deserialize<string[]>(filesBaselineStream),
TestContext.Current.NuGetCachePath,
buildOrPublishPath,
ProjectDirectory.TestRoot,
intermediateOutputPath)
.ToArray();
}
else
{
return Array.Empty<string>();
}
}
private IEnumerable<string> TemplatizeExpectedFiles(
IEnumerable<string> files,
string restorePath,
string buildOrPublishFolder,
string projectPath,
string intermediateOutputPath)
{
foreach (var f in files)
{
var updated = Regex.Replace(f, DotNetJSHashRegexPattern, DotNetJSHashTemplate);
updated = updated.Replace(restorePath, "${RestorePath}")
.Replace(RuntimeVersion, "${RuntimeVersion}")
.Replace(DefaultTfm, "${Tfm}")
.Replace(DefaultPackageVersion, "${PackageVersion}")
.Replace(buildOrPublishFolder, "${OutputPath}")
.Replace(projectPath, "${ProjectPath}")
.Replace(intermediateOutputPath, "${IntermediateOutputPath}")
.Replace(Path.DirectorySeparatorChar, '\\');
yield return updated;
}
}
private IEnumerable<string> ApplyPathsToTemplatedFilePaths(
IEnumerable<string> files,
string restorePath,
string buildOrPublishFolder,
string projectPath,
string intermediateOutputPath) =>
files.Select(f => f.Replace("${RestorePath}", restorePath)
.Replace("${RuntimeVersion}", RuntimeVersion)
.Replace("${Tfm}", DefaultTfm)
.Replace("${PackageVersion}", DefaultPackageVersion)
.Replace("${OutputPath}", buildOrPublishFolder)
.Replace("${IntermediateOutputPath}", intermediateOutputPath)
.Replace("${ProjectPath}", projectPath)
.Replace('\\', Path.DirectorySeparatorChar));
internal void AssertManifest(
StaticWebAssetsManifest manifest,
StaticWebAssetsManifest expected,
string suffix = "",
[CallerMemberName] string name = "")
{
if (!_generateBaselines)
{
ApplyPathsToAssets(expected, ProjectDirectory.TestRoot, TestContext.Current.NuGetCachePath);
ApplyTemplatizerToAssets(manifest);
UpdateCustomPackageVersions(TestContext.Current.NuGetCachePath, manifest);
//Many of the properties in the manifest contain full paths, to avoid flakiness on the tests, we don't compare the full paths.
manifest.Version.Should().Be(expected.Version);
manifest.Source.Should().Be(expected.Source);
manifest.BasePath.Should().Be(expected.BasePath);
manifest.Mode.Should().Be(expected.Mode);
manifest.ManifestType.Should().Be(expected.ManifestType);
manifest.ReferencedProjectsConfiguration.OrderBy(cm => cm.Identity)
.Should()
.BeEquivalentTo(expected.ReferencedProjectsConfiguration.OrderBy(cm => cm.Identity));
manifest.DiscoveryPatterns.OrderBy(dp => dp.Name).ShouldBeEquivalentTo(expected.DiscoveryPatterns.OrderBy(dp => dp.Name));
manifest.Assets.OrderBy(a => a.BasePath).ThenBy(a => a.RelativePath).ThenBy(a => a.AssetKind)
.ShouldBeEquivalentTo(expected.Assets.OrderBy(a => a.BasePath).ThenBy(a => a.RelativePath).ThenBy(a => a.AssetKind));
}
else
{
var template = Templatize(manifest, ProjectDirectory.Path, TestContext.Current.NuGetCachePath);
if (!Directory.Exists(Path.Combine(BaselinesFolder)))
{
Directory.CreateDirectory(Path.Combine(BaselinesFolder));
}
File.WriteAllText(GetManifestPath(suffix, name, manifest.ManifestType), template);
}
}
private string GetManifestPath(string suffix, string name, string manifestType)
=> Path.Combine(BaselinesFolder, $"{name}{(!string.IsNullOrEmpty(suffix) ? $"_{suffix}" : "")}.{manifestType}.staticwebassets.json");
private Stream GetManifestEmbeddedResource(string suffix, string name, string manifestType)
=> TestAssembly.GetManifestResourceStream(string.Join('.', EmbeddedResourcePrefix, $"{name}{(!string.IsNullOrEmpty(suffix) ? $"_{suffix}" : "")}.{manifestType}.staticwebassets.json"));
private string GetExpectedFilesPath(string suffix, string name, string manifestType)
=> Path.Combine(BaselinesFolder, $"{name}{(!string.IsNullOrEmpty(suffix) ? $"_{suffix}" : "")}.{manifestType}.files.json");
private Stream GetExpectedFilesEmbeddedResource(string suffix, string name, string manifestType)
=> TestAssembly.GetManifestResourceStream(string.Join('.', EmbeddedResourcePrefix, $"{name}{(!string.IsNullOrEmpty(suffix) ? $"_{suffix}" : "")}.{manifestType}.files.json"));
private void ApplyPathsToAssets(
StaticWebAssetsManifest manifest,
string projectRoot,
string restorePath)
{
foreach (var asset in manifest.Assets)
{
asset.Identity = asset.Identity.Replace("${ProjectRoot}", projectRoot);
asset.Identity = ReplaceRestorePath(restorePath, asset.Identity);
asset.RelativePath = asset.RelativePath.Replace("${RuntimeVersion}", RuntimeVersion);
asset.ContentRoot = asset.ContentRoot.Replace("${ProjectRoot}", projectRoot);
asset.ContentRoot = ReplaceRestorePath(restorePath, asset.ContentRoot);
asset.RelatedAsset = asset.RelatedAsset.Replace("${ProjectRoot}", projectRoot);
asset.RelatedAsset = ReplaceRestorePath(restorePath, asset.RelatedAsset);
asset.OriginalItemSpec = asset.OriginalItemSpec.Replace("${ProjectRoot}", projectRoot);
asset.OriginalItemSpec = ReplaceRestorePath(restorePath, asset.OriginalItemSpec);
}
foreach (var discovery in manifest.DiscoveryPatterns)
{
discovery.ContentRoot = discovery.ContentRoot.Replace("${ProjectRoot}", projectRoot);
discovery.ContentRoot = discovery.ContentRoot
.Replace('\\', Path.DirectorySeparatorChar);
discovery.Name = discovery.Name.Replace('\\', Path.DirectorySeparatorChar);
discovery.Pattern.Replace('\\', Path.DirectorySeparatorChar);
}
foreach (var relatedConfiguration in manifest.ReferencedProjectsConfiguration)
{
relatedConfiguration.Identity = relatedConfiguration.Identity.Replace("${ProjectRoot}", projectRoot).Replace('\\', Path.DirectorySeparatorChar);
}
string ReplaceRestorePath(string restorePath, string property)
{
return property
.Replace("${RestorePath}", restorePath)
.Replace("${Tfm}", DefaultTfm)
.Replace("${RuntimeVersion}", RuntimeVersion)
.Replace("${PackageVersion}", DefaultPackageVersion)
.Replace('\\', Path.DirectorySeparatorChar);
}
}
private string Templatize(StaticWebAssetsManifest manifest, string projectRoot, string restorePath)
{
manifest.Hash = "__hash__";
var assetsByIdentity = manifest.Assets.ToDictionary(a => a.Identity);
foreach (var asset in manifest.Assets)
{
TemplatizeAsset(projectRoot, restorePath, asset);
if (!string.IsNullOrEmpty(asset.RelatedAsset))
{
var relatedAsset = string.IsNullOrEmpty(asset.RelatedAsset) || !assetsByIdentity.TryGetValue(asset.RelatedAsset, out var related) ?
null : related;
if (relatedAsset != null)
{
TemplatizeAsset(projectRoot, restorePath, relatedAsset);
}
TemplatizeAsset(projectRoot, restorePath, asset);
asset.RelatedAsset = PathTemplatizer(asset, asset.RelatedAsset, relatedAsset) ?? asset.RelatedAsset;
}
asset.OriginalItemSpec = asset.OriginalItemSpec.Replace(projectRoot, "${ProjectRoot}");
asset.OriginalItemSpec = TemplatizeRestorePath(restorePath, asset.OriginalItemSpec);
asset.OriginalItemSpec = PathTemplatizer(asset, asset.OriginalItemSpec, null) ?? asset.OriginalItemSpec;
}
foreach (var discovery in manifest.DiscoveryPatterns)
{
discovery.ContentRoot = discovery.ContentRoot.Replace(projectRoot, "${ProjectRoot}");
discovery.ContentRoot = discovery.ContentRoot
.Replace(Path.DirectorySeparatorChar, '\\');
discovery.Name = discovery.Name.Replace(Path.DirectorySeparatorChar, '\\');
discovery.Pattern = discovery.Pattern.Replace(Path.DirectorySeparatorChar, '\\');
}
foreach (var relatedManifest in manifest.ReferencedProjectsConfiguration)
{
relatedManifest.Identity = relatedManifest.Identity.Replace(projectRoot, "${ProjectRoot}").Replace(Path.DirectorySeparatorChar, '\\');
}
// Sor everything now to ensure we produce stable baselines independent of the machine they were generated on.
Array.Sort(manifest.DiscoveryPatterns, (l, r) => StringComparer.Ordinal.Compare(l.Name, r.Name));
Array.Sort(manifest.Assets, (l, r) => StringComparer.Ordinal.Compare(l.Identity, r.Identity));
Array.Sort(manifest.ReferencedProjectsConfiguration, (l, r) => StringComparer.Ordinal.Compare(l.Identity, r.Identity));
return JsonSerializer.Serialize(manifest, BaselineSerializationOptions);
void TemplatizeAsset(string projectRoot, string restorePath, StaticWebAsset asset)
{
asset.Identity = asset.Identity.Replace(projectRoot, "${ProjectRoot}");
asset.Identity = TemplatizeRestorePath(restorePath, asset.Identity);
asset.Identity = PathTemplatizer(asset, asset.Identity, null) ?? asset.Identity;
asset.RelativePath = Regex.Replace(asset.RelativePath, DotNetJSHashRegexPattern, DotNetJSHashTemplate);
asset.RelativePath = asset.RelativePath.Replace(RuntimeVersion, "${RuntimeVersion}");
asset.ContentRoot = asset.ContentRoot.Replace(projectRoot, "${ProjectRoot}");
asset.ContentRoot = TemplatizeRestorePath(restorePath, asset.ContentRoot) + '\\';
asset.RelatedAsset = asset.RelatedAsset.Replace(projectRoot, "${ProjectRoot}");
asset.RelatedAsset = TemplatizeRestorePath(restorePath, asset.RelatedAsset);
}
string TemplatizeRestorePath(string restorePath, string property)
{
property = property
.Replace(DefaultTfm, "${Tfm}")
.Replace(restorePath, "${RestorePath}")
.Replace(Path.DirectorySeparatorChar, '\\');
var customPackageVersion = true;
var segments = property.Split('\\', StringSplitOptions.RemoveEmptyEntries);
for (var i = 0; i < segments.Length; i++)
{
ref var segment = ref segments[i];
segment = Regex.Replace(segment, DotNetJSHashRegexPattern, DotNetJSHashTemplate);
if (segment.Contains(RuntimeVersion))
{
segment = segment.Replace(RuntimeVersion, "${RuntimeVersion}");
customPackageVersion = false;
}
if (segment == DefaultPackageVersion)
{
segment = "${PackageVersion}";
customPackageVersion = false;
}
}
if (segments.Length > 0 && segments[0] == "${RestorePath}" && customPackageVersion)
{
segments[2] = "[[CustomPackageVersion]]";
}
return string.Join('\\', segments);
}
}
}
}