-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
GZipCompress.cs
75 lines (62 loc) · 2.91 KB
/
GZipCompress.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO.Compression;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Microsoft.NET.Sdk.BlazorWebAssembly
{
public class GZipCompress : Task
{
[Required]
public ITaskItem[] FilesToCompress { get; set; }
[Output]
public ITaskItem[] CompressedFiles { get; set; }
[Required]
public string OutputDirectory { get; set; }
public override bool Execute()
{
CompressedFiles = new ITaskItem[FilesToCompress.Length];
Directory.CreateDirectory(OutputDirectory);
System.Threading.Tasks.Parallel.For(0, FilesToCompress.Length, i =>
{
var file = FilesToCompress[i];
var inputFullPath = file.GetMetadata("FullPath");
var relativePath = file.GetMetadata("RelativePath");
var outputRelativePath = Path.Combine(
OutputDirectory,
BrotliCompress.CalculateTargetPath(inputFullPath, ".gz"));
var outputItem = new TaskItem(outputRelativePath, file.CloneCustomMetadata());
outputItem.SetMetadata("RelativePath", relativePath + ".gz");
outputItem.SetMetadata("OriginalItemSpec", file.ItemSpec);
CompressedFiles[i] = outputItem;
if (!File.Exists(outputRelativePath))
{
Log.LogMessage(MessageImportance.Low, "Compressing '{0}' because compressed file '{1}' does not exist.", file.ItemSpec, outputRelativePath);
}
else if (File.GetLastWriteTimeUtc(inputFullPath) < File.GetLastWriteTimeUtc(outputRelativePath))
{
// Incrementalism. If input source doesn't exist or it exists and is not newer than the expected output, do nothing.
Log.LogMessage(MessageImportance.Low, "Skipping '{0}' because '{1}' is newer than '{2}'.", file.ItemSpec, outputRelativePath, file.ItemSpec);
return;
}
else
{
Log.LogMessage(MessageImportance.Low, "Compressing '{0}' because file is newer than '{1}'.", inputFullPath, outputRelativePath);
}
try
{
using var sourceStream = File.OpenRead(file.ItemSpec);
using var fileStream = File.Create(outputRelativePath);
using var stream = new GZipStream(fileStream, CompressionLevel.Optimal);
sourceStream.CopyTo(stream);
}
catch (Exception e)
{
Log.LogErrorFromException(e);
return;
}
});
return !Log.HasLoggedErrors;
}
}
}