|
| 1 | +using Microsoft.Build.Evaluation; |
| 2 | + |
| 3 | +namespace Nimbleways.Tools.Subset; |
| 4 | +internal static class RestoreSubset |
| 5 | +{ |
| 6 | + public static void Execute(string mainProjectPath, string rootFolder, string destinationFolder) |
| 7 | + { |
| 8 | + if (!IsSameOrUnder(rootFolder, mainProjectPath)) |
| 9 | + { |
| 10 | + throw new ArgumentException($"Project '${mainProjectPath}' must be under the root folder '{rootFolder}'"); |
| 11 | + } |
| 12 | + Directory.CreateDirectory(destinationFolder); |
| 13 | + |
| 14 | + using var projectCollection = new ProjectCollection(); |
| 15 | + var projectsByFullPath = new Dictionary<string, Project>(); |
| 16 | + VisitAllProjects(projectCollection, rootFolder, mainProjectPath, projectsByFullPath); |
| 17 | + var projectListAsString = string.Join(Environment.NewLine + " - ", projectsByFullPath.Keys); |
| 18 | + Console.WriteLine($"Found {projectsByFullPath.Count} project(s) to copy:{Environment.NewLine + " - "}{projectListAsString}"); |
| 19 | + var filesInvolvedInRestore = projectsByFullPath.Values.SelectMany(project => GetFilesInvolvedInRestore(rootFolder, project)); |
| 20 | + var nugetConfigFiles = GetNugetConfigFiles(rootFolder, projectsByFullPath); |
| 21 | + var allFilesToCopy = filesInvolvedInRestore.Concat(nugetConfigFiles).Distinct().OrderBy(f => f).ToArray(); |
| 22 | + |
| 23 | + int copiedFilesCount = 0; |
| 24 | + foreach (var file in allFilesToCopy) |
| 25 | + { |
| 26 | + var destinationFile = Path.Combine(destinationFolder, Path.GetRelativePath(rootFolder, file)); |
| 27 | + Directory.CreateDirectory(Path.GetDirectoryName(destinationFile)!); |
| 28 | + if (!File.Exists(destinationFile)) |
| 29 | + { |
| 30 | + File.Copy(file, destinationFile); |
| 31 | + ++copiedFilesCount; |
| 32 | + } |
| 33 | + else if (!AreFilesIdentical(file, destinationFile)) |
| 34 | + { |
| 35 | + string errorMessage = $"ERROR: cannot copy '{file}' to '{destinationFile}': destination file already exist but have different content from source file"; |
| 36 | + Console.WriteLine(errorMessage); |
| 37 | + throw new ArgumentException(errorMessage); |
| 38 | + } |
| 39 | + } |
| 40 | + Console.WriteLine($"Copied {copiedFilesCount} file(s) to '{destinationFolder}'. {allFilesToCopy.Length - copiedFilesCount} file(s) already exist in destination."); |
| 41 | + } |
| 42 | + |
| 43 | + private static bool IsSameOrUnder(string rootFolder, string path) |
| 44 | + { |
| 45 | + var relativePath = Path.GetRelativePath(rootFolder, path); |
| 46 | + return relativePath != ".." && !relativePath.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal) && !Path.IsPathRooted(relativePath); |
| 47 | + } |
| 48 | + |
| 49 | + private static string GetFullPathWithOriginalCase(string path, string? basePath = null) |
| 50 | + { |
| 51 | + var fullFilePath = basePath != null ? Path.GetFullPath(path, basePath) : Path.GetFullPath(path); |
| 52 | + if (!File.Exists(fullFilePath)) |
| 53 | + { |
| 54 | + return fullFilePath; |
| 55 | + } |
| 56 | + |
| 57 | + var folder = Path.GetDirectoryName(fullFilePath) ?? throw new ArgumentException("GetDirectoryName returns null", nameof(path)); |
| 58 | + return Directory.EnumerateFiles(folder, Path.GetFileName(fullFilePath)).First(); |
| 59 | + } |
| 60 | + |
| 61 | + private static void VisitAllProjects(ProjectCollection projectCollection, string rootFolder, string projectPath, Dictionary<string, Project> projects) |
| 62 | + { |
| 63 | + if (!Path.IsPathRooted(projectPath)) |
| 64 | + { |
| 65 | + throw new ArgumentException($"projectPath must be absolute: '{projectPath}"); |
| 66 | + } |
| 67 | + var fullPath = GetFullPathWithOriginalCase(projectPath); |
| 68 | + if (projects.ContainsKey(fullPath) || !IsSameOrUnder(rootFolder, fullPath)) |
| 69 | + { |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + var project = projectCollection.LoadProject(fullPath); |
| 74 | + projects.Add(fullPath, project); |
| 75 | + var r = project.GetItems("ProjectReference"); |
| 76 | + foreach (var projectReference in r) |
| 77 | + { |
| 78 | + var path = Path.IsPathRooted(projectReference.EvaluatedInclude) ? projectReference.EvaluatedInclude : Path.Combine(Path.GetDirectoryName(fullPath)!, projectReference.EvaluatedInclude); |
| 79 | + VisitAllProjects(projectCollection, rootFolder, path, projects); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + private static string? GetPackagesLockFile(string projectFolder, Project project) |
| 84 | + { |
| 85 | + var candidateFilenames = new List<string>(); |
| 86 | + var nuGetLockFilePathPropertyValue = project.GetPropertyValue("NuGetLockFilePath"); |
| 87 | + if (!string.IsNullOrEmpty(nuGetLockFilePathPropertyValue)) |
| 88 | + { |
| 89 | + candidateFilenames.Add(nuGetLockFilePathPropertyValue); |
| 90 | + } |
| 91 | + var projectNameWithoutSpaces = Path |
| 92 | + .GetFileNameWithoutExtension(project.FullPath) |
| 93 | + .Replace(" ", "_", StringComparison.OrdinalIgnoreCase); |
| 94 | + candidateFilenames.Add($"packages.{projectNameWithoutSpaces}.lock.json"); |
| 95 | + candidateFilenames.Add("packages.lock.json"); |
| 96 | + return candidateFilenames |
| 97 | + .Select(name => GetFullPathWithOriginalCase(name, projectFolder)) |
| 98 | + .FirstOrDefault(File.Exists); |
| 99 | + } |
| 100 | + private static IEnumerable<string> GetFilesInvolvedInRestore(string rootFolder, Project project) |
| 101 | + { |
| 102 | + yield return project.FullPath; |
| 103 | + |
| 104 | + var projectFolder = Path.GetDirectoryName(project.FullPath); |
| 105 | + if (projectFolder is null || !Directory.Exists(projectFolder)) |
| 106 | + { |
| 107 | + throw new ArgumentException($"'{rootFolder}' doesn't exist"); |
| 108 | + } |
| 109 | + |
| 110 | + var packagesLockFile = GetPackagesLockFile(projectFolder, project); |
| 111 | + if (packagesLockFile is not null) |
| 112 | + { |
| 113 | + yield return packagesLockFile; |
| 114 | + } |
| 115 | + |
| 116 | + foreach (var import in project.Imports) |
| 117 | + { |
| 118 | + if (IsSameOrUnder(rootFolder, import.ImportedProject.FullPath)) |
| 119 | + { |
| 120 | + yield return import.ImportedProject.FullPath; |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + private static IEnumerable<string> GetNugetConfigFiles(string rootFolder, Dictionary<string, Project> projects) |
| 125 | + { |
| 126 | + static void GetNugetConfigFiles(string rootFolder, DirectoryInfo folder, IDictionary<string, string> nugetConfigFiles) |
| 127 | + { |
| 128 | + if (nugetConfigFiles.ContainsKey(folder.FullName) || !IsSameOrUnder(rootFolder, folder.FullName)) |
| 129 | + { |
| 130 | + return; |
| 131 | + } |
| 132 | + |
| 133 | + var f = new[] { "nuget.config", "NuGet.config", "NuGet.Config" } |
| 134 | + .Select(name => GetFullPathWithOriginalCase(name, folder.FullName)) |
| 135 | + .FirstOrDefault(File.Exists); |
| 136 | + if (f is not null) |
| 137 | + { |
| 138 | + nugetConfigFiles.Add(folder.FullName, f); |
| 139 | + } |
| 140 | + |
| 141 | + GetNugetConfigFiles(rootFolder, folder.Parent!, nugetConfigFiles); |
| 142 | + } |
| 143 | + var nugetConfigFilesByFolder = new Dictionary<string, string>(); |
| 144 | + var csprojDefinedNugetConfigFiles = new List<string>(); |
| 145 | + foreach (var (projectPath, project) in projects) |
| 146 | + { |
| 147 | + var restoreConfigFilePropertyValue = project.GetPropertyValue("RestoreConfigFile"); |
| 148 | + if (!string.IsNullOrEmpty(restoreConfigFilePropertyValue)) |
| 149 | + { |
| 150 | + var fullPath = GetFullPathWithOriginalCase(restoreConfigFilePropertyValue); |
| 151 | + if (IsSameOrUnder(rootFolder, fullPath)) |
| 152 | + { |
| 153 | + if (File.Exists(fullPath)) |
| 154 | + { |
| 155 | + csprojDefinedNugetConfigFiles.Add(fullPath); |
| 156 | + } |
| 157 | + else |
| 158 | + { |
| 159 | + string errorMessage = $"ERROR: cannot find the file '{restoreConfigFilePropertyValue}' defined in the property 'RestoreConfigFile' of the project '{projectPath}'"; |
| 160 | + errorMessage += $"{Environment.NewLine}If the path is relative, it is resolved by NuGet against the current working directy, not the project directory"; |
| 161 | + Console.WriteLine(errorMessage); |
| 162 | + throw new ArgumentException(errorMessage); |
| 163 | + } |
| 164 | + } |
| 165 | + } |
| 166 | + else |
| 167 | + { |
| 168 | + GetNugetConfigFiles(rootFolder, Directory.GetParent(projectPath)!, nugetConfigFilesByFolder); |
| 169 | + } |
| 170 | + } |
| 171 | + return nugetConfigFilesByFolder.Values.Concat(csprojDefinedNugetConfigFiles); |
| 172 | + } |
| 173 | + private static bool AreFilesIdentical(string file1, string file2) |
| 174 | + { |
| 175 | + const int bytesToRead = 1024 * 10; |
| 176 | + |
| 177 | + using FileStream fs1 = File.Open(file1, FileMode.Open); |
| 178 | + using FileStream fs2 = File.Open(file2, FileMode.Open); |
| 179 | + |
| 180 | + if (fs1.Length != fs2.Length) |
| 181 | + { |
| 182 | + return false; |
| 183 | + } |
| 184 | + |
| 185 | + var buffer1 = new byte[bytesToRead]; |
| 186 | + var buffer2 = new byte[bytesToRead]; |
| 187 | + var buffer1ReadOnlySpan = (ReadOnlySpan<byte>)buffer1; |
| 188 | + var buffer2ReadOnlySpan = (ReadOnlySpan<byte>)buffer2; |
| 189 | + int len1, len2; |
| 190 | + do |
| 191 | + { |
| 192 | + len1 = fs1.Read(buffer1, 0, bytesToRead); |
| 193 | + len2 = fs2.Read(buffer2, 0, bytesToRead); |
| 194 | + |
| 195 | + if (!buffer1ReadOnlySpan.SequenceEqual(buffer2ReadOnlySpan)) |
| 196 | + { |
| 197 | + return false; |
| 198 | + } |
| 199 | + } |
| 200 | + while (len1 == 0 || len2 == 0); |
| 201 | + |
| 202 | + return true; |
| 203 | + } |
| 204 | +} |
0 commit comments