-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathResolveCompressedAssets.cs
296 lines (246 loc) · 10.9 KB
/
ResolveCompressedAssets.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable
using Microsoft.AspNetCore.StaticWebAssets.Tasks.Utils;
using Microsoft.Build.Framework;
namespace Microsoft.AspNetCore.StaticWebAssets.Tasks;
public class ResolveCompressedAssets : Task
{
private static readonly char[] PatternSeparator = [';'];
private const string GzipAssetTraitValue = "gzip";
private const string BrotliAssetTraitValue = "br";
private const string GzipFormatName = "gzip";
private const string BrotliFormatName = "brotli";
public ITaskItem[] CandidateAssets { get; set; }
public string Formats { get; set; }
public string IncludePatterns { get; set; }
public string ExcludePatterns { get; set; }
public ITaskItem[] ExplicitAssets { get; set; }
[Required]
public string OutputPath { get; set; }
[Output]
public ITaskItem[] AssetsToCompress { get; set; }
public override bool Execute()
{
if (CandidateAssets is null)
{
Log.LogMessage(
MessageImportance.Low,
"Skipping task '{0}' because no candidate assets for compression were specified.",
nameof(ResolveCompressedAssets));
return true;
}
if (string.IsNullOrEmpty(Formats))
{
Log.LogMessage(
MessageImportance.Low,
"Skipping task '{0}' because no compression formats were specified.",
nameof(ResolveCompressedAssets));
return true;
}
var candidates = StaticWebAsset.FromTaskItemGroup(CandidateAssets).ToArray();
var explicitAssets = ExplicitAssets == null ? [] : StaticWebAsset.FromTaskItemGroup(ExplicitAssets);
var existingCompressionFormatsByAssetItemSpec = CollectCompressedAssets(candidates);
var includePatterns = SplitPattern(IncludePatterns);
var excludePatterns = SplitPattern(ExcludePatterns);
var matcher = new StaticWebAssetGlobMatcherBuilder()
.AddIncludePatterns(includePatterns)
.AddExcludePatterns(excludePatterns)
.Build();
var matchingCandidateAssets = new List<StaticWebAsset>();
var matchContext = StaticWebAssetGlobMatcher.CreateMatchContext();
// Add each candidate asset to each compression configuration with a matching pattern.
foreach (var asset in candidates)
{
if (IsCompressedAsset(asset))
{
Log.LogMessage(
MessageImportance.Low,
"Ignoring asset '{0}' for compression because it is already compressed asset for '{1}'.",
asset.Identity,
asset.RelatedAsset);
continue;
}
var relativePath = asset.ComputePathWithoutTokens(asset.RelativePath);
matchContext.SetPathAndReinitialize(relativePath.AsSpan());
var match = matcher.Match(matchContext);
if (!match.IsMatch)
{
Log.LogMessage(
MessageImportance.Low,
"Asset '{0}' with relative path '{1}' did not match include pattern '{2}' or matched exclude pattern '{3}'.",
asset.Identity,
relativePath,
IncludePatterns,
ExcludePatterns);
continue;
}
Log.LogMessage(
MessageImportance.Low,
"Asset '{0}' with relative path '{1}' matched include pattern '{2}' and did not match exclude pattern '{3}'.",
asset.Identity,
relativePath,
IncludePatterns,
ExcludePatterns);
matchingCandidateAssets.Add(asset);
}
// Consider each explicitly-provided asset to be a matching asset.
matchingCandidateAssets.AddRange(explicitAssets);
// Process the final set of candidate assets, deduplicating assets to be compressed in the same format multiple times and
// generating new a static web asset definition for each compressed item.
var formats = SplitPattern(Formats);
var assetsToCompress = new List<ITaskItem>();
var outputPath = Path.GetFullPath(OutputPath);
foreach (var format in formats)
{
foreach (var asset in matchingCandidateAssets)
{
var itemSpec = asset.Identity;
if (!existingCompressionFormatsByAssetItemSpec.TryGetValue(itemSpec, out var existingFormats))
{
existingFormats = [];
existingCompressionFormatsByAssetItemSpec.Add(itemSpec, existingFormats);
}
if (existingFormats.Contains(format))
{
Log.LogMessage(
"Ignoring asset '{0}' because it was already resolved with format '{1}'.",
itemSpec,
format);
continue;
}
if (TryCreateCompressedAsset(asset, outputPath, format, out var compressedAsset))
{
assetsToCompress.Add(compressedAsset);
existingFormats.Add(format);
Log.LogMessage(
"Accepted compressed asset '{0}' for '{1}'.",
compressedAsset.ItemSpec,
itemSpec);
}
else
{
Log.LogError(
"Could not create compressed asset for original asset '{0}'.",
itemSpec);
}
}
}
Log.LogMessage(
"Resolved {0} compressed assets for {1} candidate assets.",
assetsToCompress.Count,
matchingCandidateAssets.Count);
AssetsToCompress = [.. assetsToCompress];
return !Log.HasLoggedErrors;
}
private Dictionary<string, HashSet<string>> CollectCompressedAssets(StaticWebAsset[] candidates)
{
// Scan the provided candidate assets and determine which ones have already been detected for compression and in which formats.
var existingCompressionFormatsByAssetItemSpec = new Dictionary<string, HashSet<string>>();
foreach (var asset in candidates)
{
if (!IsCompressedAsset(asset))
{
Log.LogMessage(
MessageImportance.Low,
"Asset '{0}' is not compressed.",
asset.Identity);
continue;
}
var relatedAssetItemSpec = asset.RelatedAsset;
if (string.IsNullOrEmpty(relatedAssetItemSpec))
{
Log.LogError(
"The asset '{0}' was detected as compressed but didn't specify a related asset.",
asset.Identity);
continue;
}
if (!existingCompressionFormatsByAssetItemSpec.TryGetValue(relatedAssetItemSpec, out var existingFormats))
{
existingFormats = [];
existingCompressionFormatsByAssetItemSpec.Add(relatedAssetItemSpec, existingFormats);
}
string assetFormat;
if (string.Equals(asset.AssetTraitValue, GzipAssetTraitValue, StringComparison.OrdinalIgnoreCase))
{
assetFormat = GzipFormatName;
}
else if (string.Equals(asset.AssetTraitValue, BrotliAssetTraitValue, StringComparison.OrdinalIgnoreCase))
{
assetFormat = BrotliFormatName;
}
else
{
Log.LogError(
"The asset '{0}' has an unknown compression format '{1}'.",
asset.Identity,
asset.AssetTraitValue);
continue;
}
Log.LogMessage(
"The asset '{0}' with related asset '{1}' was detected as already compressed with format '{2}'.",
asset.Identity,
relatedAssetItemSpec,
assetFormat);
existingFormats.Add(assetFormat);
}
return existingCompressionFormatsByAssetItemSpec;
}
private static bool IsCompressedAsset(StaticWebAsset asset)
=> string.Equals("Content-Encoding", asset.AssetTraitName, StringComparison.Ordinal);
private static string[] SplitPattern(string pattern)
=> string.IsNullOrEmpty(pattern) ? [] : pattern
.Split(PatternSeparator, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Trim())
.ToArray();
private bool TryCreateCompressedAsset(StaticWebAsset asset, string outputPath, string format, out ITaskItem result)
{
result = null;
string fileExtension;
string assetTraitValue;
if (string.Equals(GzipFormatName, format, StringComparison.OrdinalIgnoreCase))
{
fileExtension = ".gz";
assetTraitValue = GzipAssetTraitValue;
}
else if (string.Equals(BrotliFormatName, format, StringComparison.OrdinalIgnoreCase))
{
fileExtension = ".br";
assetTraitValue = BrotliAssetTraitValue;
}
else
{
Log.LogError(
"Unknown compression format '{0}' for '{1}'.",
format,
asset.Identity);
return false;
}
var originalItemSpec = asset.OriginalItemSpec;
var relativePath = asset.EmbedTokens(asset.RelativePath);
// Make the hash name more unique by including source id, base path, asset kind and relative path.
// This combination must be unique across all assets, so this will avoid collisions when two files on
// the same project have the same contents, when it happens across different projects or between Build/Publish
// assets.
var pathHash = FileHasher.HashString(asset.SourceId + asset.BasePath + asset.AssetKind + asset.RelativePath);
var fileName = $"{pathHash}-{asset.Fingerprint}{fileExtension}";
var itemSpec = Path.GetFullPath(Path.Combine(OutputPath, fileName));
var res = new StaticWebAsset(asset)
{
Identity = itemSpec,
RelativePath = $"{relativePath}{fileExtension}",
OriginalItemSpec = asset.Identity,
RelatedAsset = asset.Identity,
AssetRole = "Alternative",
AssetTraitName = "Content-Encoding",
AssetTraitValue = assetTraitValue,
ContentRoot = outputPath,
// Set integrity and fingerprint to null so that they get recalculated for the compressed asset.
Fingerprint = null,
Integrity = null,
};
result = res.ToTaskItem();
result.SetMetadata("RelatedAssetOriginalItemSpec", originalItemSpec);
return true;
}
}