Repository navigation
Expand file tree
/
Copy pathCompactor.cs
More file actions
204 lines (158 loc) · 7.32 KB
/
Copy pathCompactor.cs
File metadata and controls
204 lines (158 loc) · 7.32 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
using CompactGUI.Logging.Core;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using Windows.Win32;
namespace CompactGUI.Core;
public sealed class Compactor : ICompressor, IDisposable
{
private readonly string workingDirectory;
private readonly HashSet<string> exclusionList;
private readonly WOFCompressionAlgorithm wofCompressionAlgorithm;
private readonly bool bypassLowDiskSpaceProtection;
private readonly ParallelFileRunner<FileDetails> runner;
private ILogger<Compactor> _logger;
private Analyser _analyser;
public Compactor(string folderPath, WOFCompressionAlgorithm compressionLevel, string[] excludedFileTypes, Analyser analyser, bool bypassLowDiskSpaceProtection, ILogger<Compactor>? logger = null)
{
workingDirectory = folderPath;
exclusionList = new HashSet<string>(excludedFileTypes, StringComparer.OrdinalIgnoreCase);
wofCompressionAlgorithm = compressionLevel;
this.bypassLowDiskSpaceProtection = bypassLowDiskSpaceProtection;
_logger = logger ?? NullLogger<Compactor>.Instance;
_analyser = analyser;
runner = new ParallelFileRunner<FileDetails>(new ParallelFileRunnerOptions<FileDetails>
{
GetFileName = file => file.FileName,
GetProgressWeight = file => file.UncompressedSize,
ProcessFile = file => WOFCompressFile(file.FileName),
OnProcessing = file => CompactorLog.ProcessingFile(_logger, file.FileName, file.UncompressedSize),
RecoveryMode = DiskSpaceRecoveryMode.RepeatWhileProgress
});
}
public async Task<bool> RunAsync(IProgress<CompressionProgress>? progressMonitor = null, int maxParallelism = 1)
{
if (runner.IsCancellationRequested) return false;
CompactorLog.BuildingWorkingFilesList(_logger, workingDirectory);
var workingFiles = await BuildWorkingFilesList().ConfigureAwait(false);
if (workingFiles is null)
{
CompactorLog.CompressionFailed(_logger, "Unable to build the compression file list.");
return false;
}
long totalFilesSize = workingFiles.Sum((f) => f.UncompressedSize);
if (totalFilesSize == 0)
{
CompactorLog.CompressionCompleted(_logger, 0);
progressMonitor?.Report(new CompressionProgress(100, ""));
return true;
}
var sw = Stopwatch.StartNew();
maxParallelism = GetWorkerCount(maxParallelism, workingFiles, bypassLowDiskSpaceProtection);
Debug.WriteLine($"Compactor: Using {maxParallelism} parallel workers for compression.");
CompactorLog.StartingCompression(_logger, workingDirectory, wofCompressionAlgorithm.ToString(), maxParallelism);
int failedFileCount;
try
{
failedFileCount = await runner.RunAsync(workingFiles, totalFilesSize, maxParallelism, progressMonitor).ConfigureAwait(false);
}
catch (OperationCanceledException){
CompactorLog.CompressionCanceled(_logger);
runner.ReportProgress(progressMonitor, force: true);
return false;
}
catch (Exception ex){
CompactorLog.CompressionFailed(_logger, ex.Message);
return false;
}
finally { sw.Stop();}
if (failedFileCount > 0)
{
CompactorLog.CompressionFailed(_logger, $"{failedFileCount} file operation(s) failed.");
runner.ReportProgress(progressMonitor, force: true);
return true;
}
CompactorLog.CompressionCompleted(_logger, Math.Round(sw.Elapsed.TotalSeconds, 3));
runner.ReportProgress(progressMonitor, force: true);
return true;
}
private unsafe FileOperationResult WOFCompressFile(string filePath)
{
const int ErrorCompressionNotBeneficialHResult = unchecked((int)0x80070158);
try
{
using (SafeFileHandle fs = File.OpenHandle(filePath))
{
WOFHelper.WOF_FILE_COMPRESSION_INFO_V1 compressionInfo = new()
{
Algorithm = (uint)wofCompressionAlgorithm,
Flags = 0
};
int result = PInvoke.WofSetFileDataLocation(fs,(uint)WOFHelper.WOF_PROVIDER_FILE, &compressionInfo, (uint)sizeof(WOFHelper.WOF_FILE_COMPRESSION_INFO_V1));
if (result >= 0 || result == ErrorCompressionNotBeneficialHResult) return FileOperationResult.Success;
if (FileOperationRecovery.IsInsufficientDiskSpaceHResult(result)) return FileOperationResult.InsufficientDiskSpace;
return FileOperationResult.Failed;
}
}
catch (Exception)
{
return FileOperationResult.Failed;
}
}
public async Task<List<FileDetails>?> BuildWorkingFilesList()
{
uint clusterSize = SharedMethods.GetClusterSize(workingDirectory);
var analysedFiles = await _analyser.GetAnalysedFilesAsync(runner.Token);
if (analysedFiles is null) return null;
var excludedFiles = SkipListMatcher.GetExcludedFiles(workingDirectory, analysedFiles.Select(f => f.FileName), exclusionList);
return [.. analysedFiles
.Where(fl =>
fl.CompressionMode != wofCompressionAlgorithm
&& fl.UncompressedSize > clusterSize
&& !fl.Attributes.HasFlag(FileAttributes.SparseFile)
&& !excludedFiles.Contains(fl.FileName)
)
.Select(fl => new FileDetails(fl.FileName, fl.UncompressedSize, fl.CompressedSize))];
}
private int GetWorkerCount(int requestedWorkerCount, IReadOnlyList<FileDetails> files, bool bypassLowDiskSpaceProtection)
{
int workerCount = requestedWorkerCount <= 0 ? Environment.ProcessorCount : requestedWorkerCount;
if (bypassLowDiskSpaceProtection) return workerCount;
long totalAllocatedSize = 0;
long largestAllocatedSize = 0;
bool containsDiskImage = false;
foreach (FileDetails file in files)
{
totalAllocatedSize = checked(totalAllocatedSize + file.AllocatedSize);
largestAllocatedSize = Math.Max(largestAllocatedSize, file.AllocatedSize);
containsDiskImage |= SharedMethods.IsDiskImage(file.FileName);
}
try
{
var root = Path.GetPathRoot(workingDirectory);
if (string.IsNullOrWhiteSpace(root)) return workerCount;
long reserveBytes = totalAllocatedSize / 2 + largestAllocatedSize;
bool lowFreeSpace = new DriveInfo(root).AvailableFreeSpace < reserveBytes * 2;
return lowFreeSpace || containsDiskImage ? 1 : workerCount;
}
catch (IOException)
{
return containsDiskImage ? 1 : workerCount;
}
}
public void Pause()
{
CompactorLog.CompressionPaused(_logger);
runner.Pause();
}
public void Resume()
{
runner.Resume();
CompactorLog.CompressionResumed(_logger);
}
public int Cancel() => runner.Cancel();
public void Dispose() => runner.Dispose();
public readonly record struct FileDetails(string FileName, long UncompressedSize, long AllocatedSize);
}