|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +#if !NETFRAMEWORK |
| 5 | +using System; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.IO; |
| 8 | +using System.Linq; |
| 9 | +using System.Runtime.InteropServices; |
| 10 | +using System.Security.Cryptography; |
| 11 | + |
| 12 | +namespace Microsoft.DotNet.Build.Tasks |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// Deduplicates files in a directory by replacing duplicates with hardlinks. |
| 16 | + /// Files are grouped by content hash, and a deterministic "master" file is selected |
| 17 | + /// (closest to root, alphabetically first). All other duplicates are replaced with hardlinks. |
| 18 | + /// </summary> |
| 19 | + public sealed class DeduplicateFilesWithHardLinks : Task |
| 20 | + { |
| 21 | + /// <summary> |
| 22 | + /// The root directory to scan for duplicate files. |
| 23 | + /// </summary> |
| 24 | + [Required] |
| 25 | + public string LayoutDirectory { get; set; } = null!; |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Minimum file size in bytes to consider for deduplication (default: 1024). |
| 29 | + /// Small files have minimal impact on archive size. |
| 30 | + /// </summary> |
| 31 | + public int MinimumFileSize { get; set; } = 1024; |
| 32 | + |
| 33 | + [Output] |
| 34 | + public int FilesDeduplicatedCount { get; set; } |
| 35 | + |
| 36 | + [Output] |
| 37 | + public long BytesSaved { get; set; } |
| 38 | + |
| 39 | + public override bool Execute() |
| 40 | + { |
| 41 | + if (!Directory.Exists(LayoutDirectory)) |
| 42 | + { |
| 43 | + Log.LogError($"LayoutDirectory '{LayoutDirectory}' does not exist."); |
| 44 | + return false; |
| 45 | + } |
| 46 | + |
| 47 | + Log.LogMessage(MessageImportance.High, $"Scanning for duplicate files in '{LayoutDirectory}'..."); |
| 48 | + |
| 49 | + // Find all eligible files |
| 50 | + var files = Directory.GetFiles(LayoutDirectory, "*", SearchOption.AllDirectories) |
| 51 | + .Where(f => new FileInfo(f).Length >= MinimumFileSize) |
| 52 | + .ToList(); |
| 53 | + |
| 54 | + Log.LogMessage(MessageImportance.Normal, $"Found {files.Count} files eligible for deduplication (>= {MinimumFileSize} bytes)."); |
| 55 | + |
| 56 | + if (files.Count == 0) |
| 57 | + { |
| 58 | + return true; |
| 59 | + } |
| 60 | + |
| 61 | + // Hash all files and group by hash |
| 62 | + var filesByHash = new Dictionary<string, List<FileEntry>>(); |
| 63 | + |
| 64 | + foreach (var filePath in files) |
| 65 | + { |
| 66 | + try |
| 67 | + { |
| 68 | + var fileInfo = new FileInfo(filePath); |
| 69 | + var hash = ComputeFileHash(filePath); |
| 70 | + var entry = new FileEntry |
| 71 | + { |
| 72 | + Path = filePath, |
| 73 | + Hash = hash, |
| 74 | + Size = fileInfo.Length, |
| 75 | + Depth = GetPathDepth(filePath, LayoutDirectory) |
| 76 | + }; |
| 77 | + |
| 78 | + if (!filesByHash.ContainsKey(hash)) |
| 79 | + { |
| 80 | + filesByHash[hash] = new List<FileEntry>(); |
| 81 | + } |
| 82 | + |
| 83 | + filesByHash[hash].Add(entry); |
| 84 | + } |
| 85 | + catch (Exception ex) |
| 86 | + { |
| 87 | + Log.LogWarning($"Failed to hash file '{filePath}': {ex.Message}"); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + // Process groups with duplicates |
| 92 | + var duplicateGroups = filesByHash.Values.Where(g => g.Count > 1).ToList(); |
| 93 | + |
| 94 | + Log.LogMessage(MessageImportance.Normal, $"Found {duplicateGroups.Count} groups of duplicate files."); |
| 95 | + |
| 96 | + int totalFilesDeduped = 0; |
| 97 | + long totalBytesSaved = 0; |
| 98 | + |
| 99 | + foreach (var group in duplicateGroups) |
| 100 | + { |
| 101 | + // Sort deterministically: by depth (ascending), then alphabetically |
| 102 | + var sorted = group.OrderBy(f => f.Depth).ThenBy(f => f.Path).ToList(); |
| 103 | + |
| 104 | + // First file is the "master" |
| 105 | + var master = sorted[0]; |
| 106 | + var duplicates = sorted.Skip(1).ToList(); |
| 107 | + |
| 108 | + Log.LogMessage(MessageImportance.Low, $"Master file: {master.Path}"); |
| 109 | + |
| 110 | + foreach (var duplicate in duplicates) |
| 111 | + { |
| 112 | + try |
| 113 | + { |
| 114 | + if (CreateHardLink(duplicate.Path, master.Path)) |
| 115 | + { |
| 116 | + totalFilesDeduped++; |
| 117 | + totalBytesSaved += duplicate.Size; |
| 118 | + Log.LogMessage(MessageImportance.Low, $" Linked: {duplicate.Path}"); |
| 119 | + } |
| 120 | + } |
| 121 | + catch (Exception ex) |
| 122 | + { |
| 123 | + Log.LogWarning($"Failed to create hardlink from '{duplicate.Path}' to '{master.Path}': {ex.Message}"); |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + FilesDeduplicatedCount = totalFilesDeduped; |
| 129 | + BytesSaved = totalBytesSaved; |
| 130 | + |
| 131 | + Log.LogMessage(MessageImportance.High, |
| 132 | + $"Deduplication complete: {totalFilesDeduped} files replaced with hardlinks, saving {totalBytesSaved / (1024.0 * 1024.0):F2} MB."); |
| 133 | + |
| 134 | + return true; |
| 135 | + } |
| 136 | + |
| 137 | + private string ComputeFileHash(string filePath) |
| 138 | + { |
| 139 | + using var sha256 = SHA256.Create(); |
| 140 | + using var stream = File.OpenRead(filePath); |
| 141 | + var hashBytes = sha256.ComputeHash(stream); |
| 142 | + return BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); |
| 143 | + } |
| 144 | + |
| 145 | + private int GetPathDepth(string filePath, string rootDirectory) |
| 146 | + { |
| 147 | + var relativePath = Path.GetRelativePath(rootDirectory, filePath); |
| 148 | + return relativePath.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Length - 1; |
| 149 | + } |
| 150 | + |
| 151 | + private bool CreateHardLink(string duplicateFilePath, string masterFilePath) |
| 152 | + { |
| 153 | + // TODO: Replace P/Invoke with File.CreateHardLink() when SDK targets .NET 11+ |
| 154 | + // See: https://github.com/dotnet/runtime/issues/69030 |
| 155 | + |
| 156 | + // Delete the duplicate file first |
| 157 | + File.Delete(duplicateFilePath); |
| 158 | + |
| 159 | + // Create hardlink |
| 160 | + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) |
| 161 | + { |
| 162 | + return CreateHardLinkWindows(duplicateFilePath, masterFilePath); |
| 163 | + } |
| 164 | + else |
| 165 | + { |
| 166 | + return CreateHardLinkUnix(duplicateFilePath, masterFilePath); |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + private bool CreateHardLinkWindows(string linkPath, string targetPath) |
| 171 | + { |
| 172 | + bool result = CreateHardLinkWin32(linkPath, targetPath, IntPtr.Zero); |
| 173 | + if (!result) |
| 174 | + { |
| 175 | + int errorCode = Marshal.GetLastWin32Error(); |
| 176 | + throw new InvalidOperationException($"CreateHardLink failed with error code {errorCode}"); |
| 177 | + } |
| 178 | + return result; |
| 179 | + } |
| 180 | + |
| 181 | + private bool CreateHardLinkUnix(string linkPath, string targetPath) |
| 182 | + { |
| 183 | + int result = link(targetPath, linkPath); |
| 184 | + if (result != 0) |
| 185 | + { |
| 186 | + int errorCode = Marshal.GetLastWin32Error(); |
| 187 | + throw new InvalidOperationException($"link() failed with error code {errorCode}"); |
| 188 | + } |
| 189 | + return true; |
| 190 | + } |
| 191 | + |
| 192 | + // P/Invoke declarations |
| 193 | + [DllImport("kernel32.dll", EntryPoint = "CreateHardLinkW", CharSet = CharSet.Unicode, SetLastError = true)] |
| 194 | + private static extern bool CreateHardLinkWin32( |
| 195 | + string lpFileName, |
| 196 | + string lpExistingFileName, |
| 197 | + IntPtr lpSecurityAttributes); |
| 198 | + |
| 199 | + [DllImport("libc", SetLastError = true)] |
| 200 | + private static extern int link(string oldpath, string newpath); |
| 201 | + |
| 202 | + private class FileEntry |
| 203 | + { |
| 204 | + public required string Path { get; set; } |
| 205 | + public required string Hash { get; set; } |
| 206 | + public long Size { get; set; } |
| 207 | + public int Depth { get; set; } |
| 208 | + } |
| 209 | + } |
| 210 | +} |
| 211 | +#endif |
0 commit comments