From a92004bb12dc9bc35b0e2357ce6357b047f6a28b Mon Sep 17 00:00:00 2001 From: Jonathan Peppers Date: Mon, 30 Nov 2026 15:33:33 -0600 Subject: [PATCH] [Microsoft.Android.Build.BaseTasks] Remove process state from `Files` Context: https://github.com/dotnet/maui/pull/40614 `Files` in `Microsoft.Android.Build.BaseTasks` is a shared helper that most of our MSBuild tasks call. Two parts of it are not safe when MSBuild runs tasks on several threads in one process (`-mt`): * `GetFileWriteRetryAttempts ()` and `GetFileWriteRetryDelay ()` read `DOTNET_ANDROID_FILE_WRITE_RETRY_ATTEMPTS` and `DOTNET_ANDROID_FILE_WRITE_RETRY_DELAY_MS` from the process environment and keep the values in static fields. The `CopyIfChanged ()`, `CopyIfStreamChanged ()`, and `ExtractAll ()` overloads without a `TaskEnvironment` use them. * Path parameters are `string`, so a relative path resolves against the process working directory, not the project directory. `GetArchiveExtractionPath ()`, `EnumerateArchiveFiles ()`, and `ExtractAll ()` also call `Path.GetFullPath ()`. `Microsoft.Build.TaskAuthoring.Analyzer` is already enabled for this assembly, but it reports neither problem. It follows calls only inside one compilation, and `Microsoft.Android.Build.BaseTasks` has no multithreaded tasks. Callers in `Xamarin.Android.Build.Tasks` and `Microsoft.Android.Build.Tasks` do not get diagnostics from `Files`. All current `[MSBuildMultiThreadableTask]` tasks already use the `TaskEnvironment` overloads, so there is no known bug today. This change makes the compiler and analyzer catch new ones. ### Changes * Mark `Files` with `[MSBuildMultiThreadableTaskAnalyzed]`, so the analyzer checks the class itself. `Microsoft.Build.Framework` does not ship this attribute; the analyzer finds it by name, so it is declared as an internal type. * Take the retry settings from a `TaskEnvironment` parameter, as dotnet/maui#40614 does. Remove the overloads that read the process environment. * Change path parameters from `string` to `AbsolutePath`. There is no implicit conversion from `string`, so each caller must root the path. Multithreaded tasks use `TaskEnvironment.GetAbsolutePath ()`, which their own analyzer checks. Other tasks use `TaskEnvironment.Fallback.GetAbsolutePath ()`, which resolves against the process working directory, as before. `Path.GetFullPath ()` calls become `AbsolutePath.GetCanonicalForm ()`, which calls `Path.GetFullPath ()` on the rooted path, so the archive path-traversal checks do not change. * `CleanBOM ()` used `Path.GetTempFileName ()`, which the analyzer reports. It now writes `{guid}.tmp` in the same directory, and only when the file has a BOM. * Remove `Archive ()`, `ArchiveZip ()`, `ArchiveZipUpdate ()`, and the `[Obsolete]` `ExtractAll ()` overload. Nothing in this repository calls them. * Remove the `CopyIfZipChanged_BareFileName` test. An `AbsolutePath` is always rooted, so a bare file name cannot get to `CopyIfZipChanged ()` now. ### Validation * `dotnet build` of `Microsoft.Android.Build.BaseTasks`, `Microsoft.Android.Build.Tasks`, `Xamarin.Android.Build.Tasks`, `Microsoft.Android.Build.BaseTasks-Tests`, and `Xamarin.Android.Build.Tests`: 0 errors. `.editorconfig` makes analyzer rules MSBuildTask0002 to MSBuildTask0005 errors. * `dotnet test --project tests/Microsoft.Android.Build.BaseTasks-Tests/Microsoft.Android.Build.BaseTasks-Tests.csproj`: 161 passed, 8 skipped, 1 failed. The failure is `FailedAndroidToolTaskShouldLogOutputAsError ("--info",True,"")`: `dotnet --info` fails with the local .NET 12 SDK used for this run (`The given key 'android-deps' was not present in the dictionary`). It is not related to this change. * Not run locally: full-build tests (`Xamarin.Android.Build.Tests`) and device tests. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- Documentation/guides/MSBuildBestPractices.md | 4 + .../CheckApiCompatibility.cs | 4 +- .../UnzipDirectoryChildren.cs | 4 +- .../SymbolWriter.cs | 2 +- .../Files.cs | 263 ++++++------------ ...ildMultiThreadableTaskAnalyzedAttribute.cs | 11 + .../Tasks/Aapt2Compile.cs | 4 +- .../Tasks/Aapt2Link.cs | 6 +- .../Tasks/GenerateMissingTypeMapStubs.cs | 2 +- .../GenerateNativeApplicationConfigSources.cs | 2 +- .../Tasks/GenerateTrimmableTypeMap.cs | 4 +- .../Tasks/GetAssetPacks.cs | 2 +- .../Utilities/AssemblyCompressor.cs | 3 +- .../RuntimeProviderSourceGenerator.cs | 2 +- .../Utilities/ZipArchiveEx.cs | 3 +- .../Tasks/ConvertResourcesCases.cs | 4 +- .../Tasks/CopyGeneratedJavaResourceClasses.cs | 2 +- .../Tasks/CopyIfChanged.cs | 4 +- .../Tasks/ExtractJarsFromAar.cs | 10 +- .../Tasks/GenerateLayoutBindings.cs | 2 +- .../Tasks/GenerateProguardConfiguration.cs | 2 +- .../Tasks/GenerateResourceDesigner.cs | 2 +- ...nerateResourceDesignerIntermediateClass.cs | 2 +- .../Tasks/ManifestMerger.cs | 2 +- .../Tasks/PreTrimmingFixLegacyBindings.cs | 4 +- .../Tasks/RemoveDirFixed.cs | 10 +- .../Tasks/RemoveUnknownFiles.cs | 4 +- .../Tasks/ResolveLibraryProjectImports.cs | 22 +- .../IncrementalBuildTest.cs | 26 +- .../Utilities/AndroidResource.cs | 3 +- .../MonoAndroidHelper.JavaLibraries.cs | 4 +- .../Utilities/MonoAndroidHelper.cs | 16 +- .../Utilities/RtxtWriter.cs | 3 +- .../FilesTests.cs | 130 ++++----- .../FilesHashBenchmarks.cs | 5 +- 35 files changed, 246 insertions(+), 327 deletions(-) create mode 100644 src/Microsoft.Android.Build.BaseTasks/MSBuildMultiThreadableTaskAnalyzedAttribute.cs diff --git a/Documentation/guides/MSBuildBestPractices.md b/Documentation/guides/MSBuildBestPractices.md index abd139fa189..b469bb33e14 100644 --- a/Documentation/guides/MSBuildBestPractices.md +++ b/Documentation/guides/MSBuildBestPractices.md @@ -89,6 +89,10 @@ unsafe environment APIs, relative file access, unsafe source helper calls, and invalid task declarations are build errors. The analyzer follows source calls within one compilation. Review helpers in referenced assemblies separately. +To check a shared helper class directly, mark it with +`[MSBuildMultiThreadableTaskAnalyzed]`, as `Files` in +`Microsoft.Android.Build.BaseTasks` does. Give its path parameters the +`AbsolutePath` type, so that callers in other assemblies must root each path. For example, pass `TaskEnvironment` to `AndroidRidAbiHelper.GetNativeLibraryAbi` so relative `Link` metadata and item paths use the project's directory. For generated files, use `Files.CopyIfStreamChanged` with a resolved diff --git a/build-tools/Xamarin.Android.Tools.BootstrapTasks/Xamarin.Android.Tools.BootstrapTasks/CheckApiCompatibility.cs b/build-tools/Xamarin.Android.Tools.BootstrapTasks/Xamarin.Android.Tools.BootstrapTasks/CheckApiCompatibility.cs index 59874197c82..57ace703108 100644 --- a/build-tools/Xamarin.Android.Tools.BootstrapTasks/Xamarin.Android.Tools.BootstrapTasks/CheckApiCompatibility.cs +++ b/build-tools/Xamarin.Android.Tools.BootstrapTasks/Xamarin.Android.Tools.BootstrapTasks/CheckApiCompatibility.cs @@ -139,11 +139,11 @@ public override bool Execute () using (var zip = ZipFile.OpenRead (zipFile)) { var entries = zip.Entries.Select (entry => { var isDirectory = entry.FullName.EndsWith ("/", StringComparison.Ordinal) || entry.FullName.EndsWith ("\\", StringComparison.Ordinal); - Files.GetArchiveExtractionPath (referenceContractPath.FullName, entry.FullName, isDirectory); + Files.GetArchiveExtractionPath (new AbsolutePath (referenceContractPath.FullName), entry.FullName, isDirectory); return (Entry: entry, IsDirectory: isDirectory); }).ToArray (); foreach (var (entry, isDirectory) in entries) { - var path = Files.GetArchiveExtractionPath (referenceContractPath.FullName, entry.FullName, isDirectory); + var path = Files.GetArchiveExtractionPath (new AbsolutePath (referenceContractPath.FullName), entry.FullName, isDirectory); if (isDirectory) { Directory.CreateDirectory (path); continue; diff --git a/build-tools/Xamarin.Android.Tools.BootstrapTasks/Xamarin.Android.Tools.BootstrapTasks/UnzipDirectoryChildren.cs b/build-tools/Xamarin.Android.Tools.BootstrapTasks/Xamarin.Android.Tools.BootstrapTasks/UnzipDirectoryChildren.cs index ee2c9fd87fb..07ecdc47009 100644 --- a/build-tools/Xamarin.Android.Tools.BootstrapTasks/Xamarin.Android.Tools.BootstrapTasks/UnzipDirectoryChildren.cs +++ b/build-tools/Xamarin.Android.Tools.BootstrapTasks/Xamarin.Android.Tools.BootstrapTasks/UnzipDirectoryChildren.cs @@ -58,7 +58,7 @@ public override bool Execute () var sourceFile = SourceFiles [i]; var relativeDestDir = sourceFile.GetMetadata ("DestDir"); var enc = encoding; - var destFolder = DestinationFolder.ItemSpec; + var destFolder = TaskEnvironment.Fallback.GetAbsolutePath (DestinationFolder.ItemSpec); tasks [i] = TTask.Run (() => ExtractFile (sourceFile.ItemSpec, relativeDestDir, destFolder, enc, filesToExtract)); } @@ -67,7 +67,7 @@ public override bool Execute () return !Log.HasLoggedErrors; } - void ExtractFile (string sourceFile, string relativeDestDir, string destinationFolder, Encoding encoding, HashSet filesToExtract) + void ExtractFile (string sourceFile, string relativeDestDir, AbsolutePath destinationFolder, Encoding encoding, HashSet filesToExtract) { relativeDestDir = relativeDestDir?.Replace ('\\', Path.DirectorySeparatorChar); diff --git a/src-ThirdParty/android-platform-tools-base/SymbolWriter.cs b/src-ThirdParty/android-platform-tools-base/SymbolWriter.cs index 774a023ff80..aa44635272d 100644 --- a/src-ThirdParty/android-platform-tools-base/SymbolWriter.cs +++ b/src-ThirdParty/android-platform-tools-base/SymbolWriter.cs @@ -88,7 +88,7 @@ void GenerateJava (Package package) writer.Flush (); var r_java = Path.Combine (output_directory, package.Name.Replace ('.', Path.DirectorySeparatorChar), "R.java"); - if (Files.CopyIfStreamChanged (writer.BaseStream, r_java)) { + if (Files.CopyIfStreamChanged (writer.BaseStream, TaskEnvironment.Fallback.GetAbsolutePath (r_java), TaskEnvironment.Fallback)) { LogDebugMessage ($"Writing: {r_java}"); } else { LogDebugMessage ($"Up to date: {r_java}"); diff --git a/src/Microsoft.Android.Build.BaseTasks/Files.cs b/src/Microsoft.Android.Build.BaseTasks/Files.cs index 8372ab10dd6..15feaf87cb9 100644 --- a/src/Microsoft.Android.Build.BaseTasks/Files.cs +++ b/src/Microsoft.Android.Build.BaseTasks/Files.cs @@ -18,6 +18,7 @@ namespace Microsoft.Android.Build.Tasks { + [MSBuildMultiThreadableTaskAnalyzed] public static class Files { const int ERROR_ACCESS_DENIED = -2147024891; @@ -36,9 +37,6 @@ public static class Files ? (Func) getter.CreateDelegate (typeof (Func)) : null; - static int fileWriteRetry = -1; - static int fileWriteRetryDelay = -1; - /// /// Windows has a MAX_PATH limit of 260 characters /// See: https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation @@ -54,36 +52,31 @@ public static class Files readonly static byte[] Utf8Preamble = Encoding.UTF8.GetPreamble (); /// - /// Checks for the environment variable DOTNET_ANDROID_FILE_WRITE_RETRY_ATTEMPTS to - /// see if a custom value for the number of times to retry writing a file has been - /// set. + /// Reads DOTNET_ANDROID_FILE_WRITE_RETRY_ATTEMPTS from the task environment. /// /// The value of DOTNET_ANDROID_FILE_WRITE_RETRY_ATTEMPTS or the default of DEFAULT_FILE_WRITE_RETRY_ATTEMPTS - public static int GetFileWriteRetryAttempts () + public static int GetFileWriteRetryAttempts (TaskEnvironment taskEnvironment) { - if (fileWriteRetry == -1) { - var retryVariable = Environment.GetEnvironmentVariable ("DOTNET_ANDROID_FILE_WRITE_RETRY_ATTEMPTS"); - if (string.IsNullOrEmpty (retryVariable) || !int.TryParse (retryVariable, out fileWriteRetry)) - fileWriteRetry = DEFAULT_FILE_WRITE_RETRY_ATTEMPTS; - } - return fileWriteRetry; + if (taskEnvironment == null) + throw new ArgumentNullException (nameof (taskEnvironment)); + + return int.TryParse (taskEnvironment.GetEnvironmentVariable ("DOTNET_ANDROID_FILE_WRITE_RETRY_ATTEMPTS"), + NumberStyles.Integer, CultureInfo.InvariantCulture, out var retries) ? retries : DEFAULT_FILE_WRITE_RETRY_ATTEMPTS; } /// - /// Checks for the environment variable DOTNET_ANDROID_FILE_WRITE_RETRY_DELAY_MS to - /// see if a custom value for the delay between trying to write a file has been - /// set. + /// Reads DOTNET_ANDROID_FILE_WRITE_RETRY_DELAY_MS from the task environment. /// /// The value of DOTNET_ANDROID_FILE_WRITE_RETRY_DELAY_MS or the default of DEFAULT_FILE_WRITE_RETRY_DELAY_MS - public static int GetFileWriteRetryDelay () + public static int GetFileWriteRetryDelay (TaskEnvironment taskEnvironment) { - if (fileWriteRetryDelay == -1) { - var delayVariable = Environment.GetEnvironmentVariable ("DOTNET_ANDROID_FILE_WRITE_RETRY_DELAY_MS"); - if (string.IsNullOrEmpty (delayVariable) || !int.TryParse (delayVariable, out fileWriteRetryDelay)) - fileWriteRetryDelay = DEFAULT_FILE_WRITE_RETRY_DELAY_MS; - } - return fileWriteRetryDelay; - } + if (taskEnvironment == null) + throw new ArgumentNullException (nameof (taskEnvironment)); + + return int.TryParse (taskEnvironment.GetEnvironmentVariable ("DOTNET_ANDROID_FILE_WRITE_RETRY_DELAY_MS"), + NumberStyles.Integer, CultureInfo.InvariantCulture, out var milliseconds) ? milliseconds : DEFAULT_FILE_WRITE_RETRY_DELAY_MS; + } + /// /// Converts a full path to a \\?\ prefixed path that works on all Windows machines when over 260 characters /// NOTE: requires a *full path*, use sparingly @@ -97,7 +90,7 @@ public static string ToLongPath (string fullPath) return LongPathPrefix + fullPath; } - public static void SetWriteable (string source, bool checkExists = true) + public static void SetWriteable (AbsolutePath source, bool checkExists = true) { if (checkExists && !File.Exists (source)) return; @@ -107,7 +100,7 @@ public static void SetWriteable (string source, bool checkExists = true) File.SetAttributes (source, attributes & ~FileAttributes.ReadOnly); } - public static void SetDirectoryWriteable (string directory) + public static void SetDirectoryWriteable (AbsolutePath directory) { if (!Directory.Exists (directory)) return; @@ -117,61 +110,17 @@ public static void SetDirectoryWriteable (string directory) dirInfo.Attributes &= ~FileAttributes.ReadOnly; foreach (var dir in Directory.EnumerateDirectories (directory, "*", SearchOption.AllDirectories)) { - dirInfo = new DirectoryInfo (dir); + dirInfo = new DirectoryInfo (new AbsolutePath (dir)); if ((dirInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) dirInfo.Attributes &= ~FileAttributes.ReadOnly; } foreach (var file in Directory.EnumerateFiles (directory, "*", SearchOption.AllDirectories)) { - Files.SetWriteable (Path.GetFullPath (file)); - } - } - - public static bool Archive (string target, Action archiver) - { - string newTarget = target + ".new"; - - archiver (newTarget); - - bool changed = CopyIfChanged (newTarget, target); - - try { - File.Delete (newTarget); - } catch { + Files.SetWriteable (new AbsolutePath (file)); } - - return changed; } - public static bool ArchiveZipUpdate (string target, Action archiver) - { - var lastWrite = File.Exists (target) ? File.GetLastWriteTimeUtc (target) : DateTime.MinValue; - archiver (target); - return lastWrite < File.GetLastWriteTimeUtc (target); - } - - public static bool ArchiveZip (string target, Action archiver) - { - string newTarget = target + ".new"; - - archiver (newTarget); - - bool changed = CopyIfZipChanged (newTarget, target); - - try { - File.Delete (newTarget); - } catch { - } - - return changed; - } - - public static bool CopyIfChanged (string source, string destination) - { - return CopyIfChanged (source, destination, GetFileWriteRetryAttempts (), GetFileWriteRetryDelay ()); - } - - public static bool CopyIfChanged (string source, string destination, TaskEnvironment taskEnvironment) + public static bool CopyIfChanged (AbsolutePath source, AbsolutePath destination, TaskEnvironment taskEnvironment) { if (taskEnvironment == null) throw new ArgumentNullException (nameof (taskEnvironment)); @@ -179,7 +128,7 @@ public static bool CopyIfChanged (string source, string destination, TaskEnviron return CopyIfChanged (source, destination, GetFileWriteRetryAttempts (taskEnvironment), GetFileWriteRetryDelay (taskEnvironment)); } - static bool CopyIfChanged (string source, string destination, int attempts, int delay) + static bool CopyIfChanged (AbsolutePath source, AbsolutePath destination, int attempts, int delay) { int retryCount = 0; while (retryCount <= attempts) { @@ -204,12 +153,10 @@ static bool CopyIfChanged (string source, string destination, int attempts, int return false; } - public static bool CopyIfChangedOnce (string source, string destination) + public static bool CopyIfChangedOnce (AbsolutePath source, AbsolutePath destination) { if (HasFileChanged (source, destination)) { - var directory = Path.GetDirectoryName (destination); - if (!string.IsNullOrEmpty (directory)) - Directory.CreateDirectory (directory); + CreateParentDirectory (destination); if (!Directory.Exists (source)) { if (File.Exists (destination)) { @@ -226,19 +173,24 @@ public static bool CopyIfChangedOnce (string source, string destination) return false; } - public static bool CopyIfStringChanged (string contents, string destination) + static void CreateParentDirectory (AbsolutePath path) + { + var directory = Path.GetDirectoryName (path); + if (!string.IsNullOrEmpty (directory)) + Directory.CreateDirectory (new AbsolutePath (directory)); + } + + public static bool CopyIfStringChanged (string contents, AbsolutePath destination) { //NOTE: this is not optimal since it allocates a byte[]. We can improve this down the road with Span or System.Buffers. var bytes = Encoding.UTF8.GetBytes (contents); return CopyIfBytesChanged (bytes, destination); } - public static bool CopyIfBytesChanged (byte[] bytes, string destination) + public static bool CopyIfBytesChanged (byte[] bytes, AbsolutePath destination) { if (HasBytesChanged (bytes, destination)) { - var directory = Path.GetDirectoryName (destination); - if (!string.IsNullOrEmpty (directory)) - Directory.CreateDirectory (directory); + CreateParentDirectory (destination); if (File.Exists (destination)) { SetWriteable (destination, checkExists: false); @@ -250,12 +202,7 @@ public static bool CopyIfBytesChanged (byte[] bytes, string destination) return false; } - public static bool CopyIfStreamChanged (Stream stream, string destination) - { - return CopyIfStreamChanged (stream, destination, GetFileWriteRetryAttempts (), GetFileWriteRetryDelay ()); - } - - public static bool CopyIfStreamChanged (Stream stream, string destination, TaskEnvironment taskEnvironment) + public static bool CopyIfStreamChanged (Stream stream, AbsolutePath destination, TaskEnvironment taskEnvironment) { if (taskEnvironment == null) throw new ArgumentNullException (nameof (taskEnvironment)); @@ -263,21 +210,7 @@ public static bool CopyIfStreamChanged (Stream stream, string destination, TaskE return CopyIfStreamChanged (stream, destination, GetFileWriteRetryAttempts (taskEnvironment), GetFileWriteRetryDelay (taskEnvironment)); } - static int GetFileWriteRetryAttempts (TaskEnvironment taskEnvironment) => - int.TryParse (taskEnvironment.GetEnvironmentVariable ("DOTNET_ANDROID_FILE_WRITE_RETRY_ATTEMPTS"), - NumberStyles.Integer, CultureInfo.InvariantCulture, out var retries) ? retries : DEFAULT_FILE_WRITE_RETRY_ATTEMPTS; - - static int GetFileWriteRetryDelay (TaskEnvironment taskEnvironment) => - int.TryParse (taskEnvironment.GetEnvironmentVariable ("DOTNET_ANDROID_FILE_WRITE_RETRY_DELAY_MS"), - NumberStyles.Integer, CultureInfo.InvariantCulture, out var milliseconds) ? milliseconds : DEFAULT_FILE_WRITE_RETRY_DELAY_MS; - - public static bool CopyIfStreamChanged (Stream stream, AbsolutePath destination, TaskEnvironment taskEnvironment) - { - string destinationPath = destination; - return CopyIfStreamChanged (stream, destinationPath, taskEnvironment); - } - - static bool CopyIfStreamChanged (Stream stream, string destination, int attempts, int delay) + static bool CopyIfStreamChanged (Stream stream, AbsolutePath destination, int attempts, int delay) { int retryCount = 0; while (retryCount <= attempts) { @@ -302,12 +235,10 @@ static bool CopyIfStreamChanged (Stream stream, string destination, int attempts return false; } - public static bool CopyIfStreamChangedOnce (Stream stream, string destination) + public static bool CopyIfStreamChangedOnce (Stream stream, AbsolutePath destination) { if (HasStreamChanged (stream, destination)) { - var directory = Path.GetDirectoryName (destination); - if (!string.IsNullOrEmpty (directory)) - Directory.CreateDirectory (directory); + CreateParentDirectory (destination); if (File.Exists (destination)) { SetWriteable (destination, checkExists: false); @@ -322,12 +253,10 @@ public static bool CopyIfStreamChangedOnce (Stream stream, string destination) return false; } - public static bool CopyIfZipChanged (Stream source, string destination) + public static bool CopyIfZipChanged (Stream source, AbsolutePath destination) { if (HasZipChanged (source, destination, out _)) { - var directory = Path.GetDirectoryName (destination); - if (!string.IsNullOrEmpty (directory)) - Directory.CreateDirectory (directory); + CreateParentDirectory (destination); source.Position = 0; using (var f = File.Create (destination)) { source.CopyTo (f); @@ -340,12 +269,10 @@ public static bool CopyIfZipChanged (Stream source, string destination) return false; } - public static bool CopyIfZipChanged (string source, string destination) + public static bool CopyIfZipChanged (AbsolutePath source, AbsolutePath destination) { if (HasZipChanged (source, destination, out _)) { - var directory = Path.GetDirectoryName (destination); - if (!string.IsNullOrEmpty (directory)) - Directory.CreateDirectory (directory); + CreateParentDirectory (destination); File.Copy (source, destination, true); File.SetLastWriteTimeUtc (destination, DateTime.UtcNow); @@ -355,7 +282,7 @@ public static bool CopyIfZipChanged (string source, string destination) return false; } - public static bool HasZipChanged (Stream source, string destination, out string? hash) + public static bool HasZipChanged (Stream source, AbsolutePath destination, out string? hash) { hash = null; @@ -372,7 +299,7 @@ public static bool HasZipChanged (Stream source, string destination, out string? return src_hash != dst_hash; } - public static bool HasZipChanged (string source, string destination, out string? hash) + public static bool HasZipChanged (AbsolutePath source, AbsolutePath destination, out string? hash) { hash = null; if (!File.Exists (source)) @@ -394,7 +321,7 @@ public static bool HasZipChanged (string source, string destination, out string? // This is for if the file contents have changed. Often we have to // regenerate a file, but we don't want to update it if hasn't changed // so that incremental build is as efficient as possible - public static bool HasFileChanged (string source, string destination) + public static bool HasFileChanged (AbsolutePath source, AbsolutePath destination) { // If either are missing, that's definitely a change if (!File.Exists (source) || !File.Exists (destination)) @@ -410,7 +337,7 @@ public static bool HasFileChanged (string source, string destination) return false; } - public static bool HasStreamChanged (Stream source, string destination) + public static bool HasStreamChanged (Stream source, AbsolutePath destination) { //If destination is missing, that's definitely a change if (!File.Exists (destination)) @@ -426,7 +353,7 @@ public static bool HasStreamChanged (Stream source, string destination) return false; } - public static bool HasBytesChanged (byte [] bytes, string destination) + public static bool HasBytesChanged (byte [] bytes, AbsolutePath destination) { //If destination is missing, that's definitely a change if (!File.Exists (destination)) @@ -460,12 +387,13 @@ public static bool HasBytesChanged (byte [] bytes, string destination) } } - static string? HashZip (string filename) + static string? HashZip (AbsolutePath filename) { try { // check cache - if (File.Exists (filename + ".hash")) - return File.ReadAllText (filename + ".hash"); + var hashFile = new AbsolutePath (filename.Value + ".hash"); + if (File.Exists (hashFile)) + return File.ReadAllText (hashFile); using var zip = ReadZipFile (filename); return HashZip (zip); @@ -498,7 +426,7 @@ public static uint GetZipEntryCrc32 (ZipArchiveEntry entry) return crc.GetCurrentHashAsUInt32 (); } - public static ZipArchive ReadZipFile (string filename) + public static ZipArchive ReadZipFile (AbsolutePath filename) { return ZipFile.OpenRead (filename); } @@ -507,16 +435,12 @@ public static ZipArchive ReadZipFile (string filename) /// Resolves a relative archive path under the destination, rejecting parent traversal, rooted names and linked descendants. /// The caller-selected destination itself may be a junction or symbolic link. /// - public static string GetArchiveExtractionPath (string destinationDirectory, string relativePath, bool isDirectory = false) + public static AbsolutePath GetArchiveExtractionPath (AbsolutePath destinationDirectory, string relativePath, bool isDirectory = false) { - if (destinationDirectory == null) - throw new ArgumentNullException (nameof (destinationDirectory)); if (relativePath == null) throw new ArgumentNullException (nameof (relativePath)); - if (destinationDirectory.Length == 0) - throw new ArgumentException ("The destination directory must not be empty.", nameof (destinationDirectory)); - var root = Path.GetFullPath (destinationDirectory); + var root = destinationDirectory.GetCanonicalForm ().Value; var volumeRoot = Path.GetPathRoot (root); if (volumeRoot != null && root.Length > volumeRoot.Length) root = root.TrimEnd (Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); @@ -533,7 +457,7 @@ public static string GetArchiveExtractionPath (string destinationDirectory, stri throw UnsafeArchiveEntry (relativePath, root); } - var path = Path.GetFullPath (Path.Combine (root, normalizedPath)); + var path = new AbsolutePath (Path.Combine (root, normalizedPath)).GetCanonicalForm ().Value; var pathRoot = Path.GetPathRoot (path); if (pathRoot != null && path.Length > pathRoot.Length) path = path.TrimEnd (Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); @@ -544,14 +468,14 @@ public static string GetArchiveExtractionPath (string destinationDirectory, stri throw UnsafeArchiveEntry (relativePath, root); if (isRootDirectoryEntry) - return path; + return new AbsolutePath (path); // The caller-selected root may be a junction, but archive-controlled descendants must not follow links. var current = root; foreach (var component in path.Substring (prefix.Length).Split (Path.DirectorySeparatorChar)) { current = Path.Combine (current, component); try { - if ((File.GetAttributes (current) & FileAttributes.ReparsePoint) != 0) + if ((File.GetAttributes (new AbsolutePath (current)) & FileAttributes.ReparsePoint) != 0) throw UnsafeArchiveEntry (relativePath, root); } catch (FileNotFoundException) { break; @@ -559,44 +483,40 @@ public static string GetArchiveExtractionPath (string destinationDirectory, stri break; } } - return path; + return new AbsolutePath (path); } static InvalidDataException UnsafeArchiveEntry (string entryName, string destination) => new InvalidDataException (string.Format (CultureInfo.CurrentCulture, Properties.Resources.UnsafeArchiveEntry, entryName, destination)); - public static IEnumerable<(string FilePath, string ArchivePath)> EnumerateArchiveFiles (string folder) + public static IEnumerable<(string FilePath, string ArchivePath)> EnumerateArchiveFiles (AbsolutePath folder) { - folder = Path.GetFullPath (folder.Replace ('\\', Path.DirectorySeparatorChar).Replace ('/', Path.DirectorySeparatorChar)); - var prefixLength = folder.EndsWith (Path.DirectorySeparatorChar.ToString (), StringComparison.Ordinal) ? folder.Length : folder.Length + 1; - foreach (var directory in Enumerable.Repeat (folder, 1).Concat (Directory.EnumerateDirectories (folder, "*", SearchOption.AllDirectories))) { - if (directory != folder && (File.GetAttributes (directory) & FileAttributes.Hidden) != 0) + var root = new AbsolutePath (folder.Value.Replace ('\\', Path.DirectorySeparatorChar).Replace ('/', Path.DirectorySeparatorChar)).GetCanonicalForm ().Value; + var prefixLength = root.EndsWith (Path.DirectorySeparatorChar.ToString (), StringComparison.Ordinal) ? root.Length : root.Length + 1; + foreach (var directory in Enumerable.Repeat (root, 1).Concat (Directory.EnumerateDirectories (new AbsolutePath (root), "*", SearchOption.AllDirectories))) { + if (directory != root && (File.GetAttributes (new AbsolutePath (directory)) & FileAttributes.Hidden) != 0) continue; - foreach (var file in Directory.EnumerateFiles (directory)) { - if ((File.GetAttributes (file) & FileAttributes.Hidden) != 0) + foreach (var file in Directory.EnumerateFiles (new AbsolutePath (directory))) { + if ((File.GetAttributes (new AbsolutePath (file)) & FileAttributes.Hidden) != 0) continue; yield return (file, file.Substring (prefixLength).Replace ('\\', '/')); } } } - public static bool ZipAny (string filename, Func filter) + public static bool ZipAny (AbsolutePath filename, Func filter) { using (var zip = ReadZipFile (filename)) { return zip.Entries.Any (filter); } } - [Obsolete ("Use the overload that accepts a TaskLoggingHelper parameter.")] - public static bool ExtractAll (ZipArchive zip, string destination, Action? progressCallback, - Func? modifyCallback, Func? deleteCallback, Func? skipCallback) - { - return ExtractAll (zip, destination, progressCallback, modifyCallback, deleteCallback, skipCallback, log: null); - } - - public static bool ExtractAll (ZipArchive zip, string destination, Action? progressCallback = null, Func? modifyCallback = null, + public static bool ExtractAll (ZipArchive zip, AbsolutePath destination, TaskEnvironment taskEnvironment, Action? progressCallback = null, Func? modifyCallback = null, Func? deleteCallback = null, Func? skipCallback = null, TaskLoggingHelper? log = null) { + if (taskEnvironment == null) + throw new ArgumentNullException (nameof (taskEnvironment)); + int i = 0; int total = zip.Entries.Count; bool updated = false; @@ -630,21 +550,21 @@ public static bool ExtractAll (ZipArchive zip, string destination, Action hash) return HexUtilities.ToHexString (hash); } - public static void DeleteFile (string filename, object log) + public static void DeleteFile (AbsolutePath filename, object log) { try { File.Delete (filename); @@ -758,18 +678,18 @@ public static void DeleteFile (string filename, object log) } } - public static void TryDeleteFile (string filename, Action log) + public static void TryDeleteFile (AbsolutePath filename, Action log) { try { File.Delete (filename); } catch (Exception ex) { - log ($"Could not delete '{filename}': {ex}"); + log ($"Could not delete '{filename.Value}': {ex}"); } } const uint ppdb_signature = 0x424a5342; - public static bool IsPortablePdb (string filename) + public static bool IsPortablePdb (AbsolutePath filename) { try { using (var fs = new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { @@ -786,12 +706,12 @@ public static bool IsPortablePdb (string filename) /// /// Open a file given its path and remove the 3 bytes UTF-8 BOM if there is one /// - public static void CleanBOM (string filePath) + public static void CleanBOM (AbsolutePath filePath) { - if (string.IsNullOrEmpty (filePath) || !File.Exists (filePath)) + if (!File.Exists (filePath)) return; - string? temp = null; + AbsolutePath? temp = null; try { using (var input = File.OpenRead (filePath)) { // Check if the file actually has a BOM @@ -803,18 +723,17 @@ public static void CleanBOM (string filePath) return; } - temp = Path.GetTempFileName (); - using (var stream = File.OpenWrite (temp)) + temp = new AbsolutePath (Path.Combine (Path.GetDirectoryName (filePath), $"{Guid.NewGuid ():N}.tmp")); + using (var stream = File.Create (temp.Value)) input.CopyTo (stream); } Files.SetWriteable (filePath); File.Delete (filePath); - File.Copy (temp, filePath); + File.Copy (temp.Value, filePath); } finally { - if (temp != null) { - File.Delete (temp); - } + if (temp.HasValue) + File.Delete (temp.Value); } } } diff --git a/src/Microsoft.Android.Build.BaseTasks/MSBuildMultiThreadableTaskAnalyzedAttribute.cs b/src/Microsoft.Android.Build.BaseTasks/MSBuildMultiThreadableTaskAnalyzedAttribute.cs new file mode 100644 index 00000000000..cad0344b731 --- /dev/null +++ b/src/Microsoft.Android.Build.BaseTasks/MSBuildMultiThreadableTaskAnalyzedAttribute.cs @@ -0,0 +1,11 @@ +using System; + +namespace Microsoft.Build.Framework +{ + // Microsoft.Build.TaskAuthoring.Analyzer finds this attribute by name and then checks the helper class. + // Microsoft.Build.Framework does not ship it. + [AttributeUsage (AttributeTargets.Class, Inherited = false)] + internal sealed class MSBuildMultiThreadableTaskAnalyzedAttribute : Attribute + { + } +} diff --git a/src/Microsoft.Android.Build.Tasks/Tasks/Aapt2Compile.cs b/src/Microsoft.Android.Build.Tasks/Tasks/Aapt2Compile.cs index 0855820b971..d79ecb322ec 100644 --- a/src/Microsoft.Android.Build.Tasks/Tasks/Aapt2Compile.cs +++ b/src/Microsoft.Android.Build.Tasks/Tasks/Aapt2Compile.cs @@ -59,7 +59,7 @@ public async override System.Threading.Tasks.Task RunTaskAsync () } } finally { foreach (var archive in temporaryArchives) { - Files.TryDeleteFile (archive, LogDebugMessage); + Files.TryDeleteFile (TaskEnvironment.Fallback.GetAbsolutePath (archive), LogDebugMessage); } temporaryArchives.Clear (); } @@ -96,7 +96,7 @@ void ProcessDirectory (ITaskItem item, object lockObject) lock (lockObject) temporaryArchives.Add (temporaryArchive); using (var zip = ZipFile.Open (temporaryArchive, ZipArchiveMode.Create)) { - foreach (var (filename, archivePath) in Files.EnumerateArchiveFiles (fileOrDirectory)) + foreach (var (filename, archivePath) in Files.EnumerateArchiveFiles (TaskEnvironment.Fallback.GetAbsolutePath (fileOrDirectory))) zip.CreateEntryFromFile (filename, "res/" + archivePath); } fileOrDirectory = temporaryArchive; diff --git a/src/Microsoft.Android.Build.Tasks/Tasks/Aapt2Link.cs b/src/Microsoft.Android.Build.Tasks/Tasks/Aapt2Link.cs index 5d123abbecb..b182a528e58 100644 --- a/src/Microsoft.Android.Build.Tasks/Tasks/Aapt2Link.cs +++ b/src/Microsoft.Android.Build.Tasks/Tasks/Aapt2Link.cs @@ -123,7 +123,7 @@ public async override System.Threading.Tasks.Task RunTaskAsync () if (File.Exists (tmpfile)) { if (aaptResult) { LogDebugMessage ($"Copying {tmpfile} to {currentResourceOutputFile}"); - Files.CopyIfZipChanged (tmpfile, currentResourceOutputFile); + Files.CopyIfZipChanged (TaskEnvironment.Fallback.GetAbsolutePath (tmpfile), TaskEnvironment.Fallback.GetAbsolutePath (currentResourceOutputFile)); } File.Delete (tmpfile); } @@ -145,10 +145,10 @@ public async override System.Threading.Tasks.Task RunTaskAsync () sb.AppendLine (line); } } - Files.CopyIfStringChanged (sb.ToString (), GetFullPath (ProguardRuleOutput)); + Files.CopyIfStringChanged (sb.ToString (), TaskEnvironment.Fallback.GetAbsolutePath (GetFullPath (ProguardRuleOutput))); } if (!ResourceSymbolsTextFile.IsNullOrEmpty ()) - Files.CopyIfChanged (resourceSymbolsTextFileTemp, GetFullPath (ResourceSymbolsTextFile)); + Files.CopyIfChanged (TaskEnvironment.Fallback.GetAbsolutePath (resourceSymbolsTextFileTemp), TaskEnvironment.Fallback.GetAbsolutePath (GetFullPath (ResourceSymbolsTextFile)), TaskEnvironment.Fallback); } finally { lock (tempFiles) { foreach (var temp in tempFiles) { diff --git a/src/Microsoft.Android.Build.Tasks/Tasks/GenerateMissingTypeMapStubs.cs b/src/Microsoft.Android.Build.Tasks/Tasks/GenerateMissingTypeMapStubs.cs index 64a524a8e5c..7c1702b318c 100644 --- a/src/Microsoft.Android.Build.Tasks/Tasks/GenerateMissingTypeMapStubs.cs +++ b/src/Microsoft.Android.Build.Tasks/Tasks/GenerateMissingTypeMapStubs.cs @@ -67,7 +67,7 @@ public override bool RunTask () using var stream = new MemoryStream (); generator.GenerateEmpty (stream, name); - Files.CopyIfStreamChanged (stream, linkedPath); + Files.CopyIfStreamChanged (stream, TaskEnvironment.Fallback.GetAbsolutePath (linkedPath), TaskEnvironment.Fallback); Log.LogDebugMessage ($"Generated empty typemap stub for trimmed assembly '{name}'."); stubs.Add (new TaskItem (linkedPath)); } diff --git a/src/Microsoft.Android.Build.Tasks/Tasks/GenerateNativeApplicationConfigSources.cs b/src/Microsoft.Android.Build.Tasks/Tasks/GenerateNativeApplicationConfigSources.cs index 0ab610c70a5..9b8d1e7c61d 100644 --- a/src/Microsoft.Android.Build.Tasks/Tasks/GenerateNativeApplicationConfigSources.cs +++ b/src/Microsoft.Android.Build.Tasks/Tasks/GenerateNativeApplicationConfigSources.cs @@ -180,7 +180,7 @@ static bool ShouldSkipAssembly (ITaskItem assembly) var stream = MemoryStreamPool.Shared.Rent (); try { bootstrapBuilder.Write (stream); - Files.CopyIfStreamChanged (stream, bootstrapPath); + Files.CopyIfStreamChanged (stream, TaskEnvironment.Fallback.GetAbsolutePath (bootstrapPath), TaskEnvironment.Fallback); } finally { MemoryStreamPool.Shared.Return (stream); } diff --git a/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTrimmableTypeMap.cs b/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTrimmableTypeMap.cs index d1bbedfb86e..3229c146e85 100644 --- a/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTrimmableTypeMap.cs +++ b/src/Microsoft.Android.Build.Tasks/Tasks/GenerateTrimmableTypeMap.cs @@ -441,7 +441,7 @@ ITaskItem [] CopyJavaSourcesFromInputDirectory (IReadOnlyList javaSour var items = new List (); foreach (var source in javaSources) { string outputPath = Path.Combine (JavaSourceOutputDirectory, source.RelativePath); - string physicalOutputPath = TaskEnvironment.GetAbsolutePath (outputPath); + AbsolutePath physicalOutputPath = TaskEnvironment.GetAbsolutePath (outputPath); string? dir = Path.GetDirectoryName (physicalOutputPath); if (!string.IsNullOrEmpty (dir)) { Directory.CreateDirectory (dir); diff --git a/src/Microsoft.Android.Build.Tasks/Tasks/GetAssetPacks.cs b/src/Microsoft.Android.Build.Tasks/Tasks/GetAssetPacks.cs index 6de53d435de..93d48610031 100644 --- a/src/Microsoft.Android.Build.Tasks/Tasks/GetAssetPacks.cs +++ b/src/Microsoft.Android.Build.Tasks/Tasks/GetAssetPacks.cs @@ -78,7 +78,7 @@ public override bool RunTask () } sw.WriteLine (deliveryType); sw.Flush (); - Files.CopyIfStreamChanged (sw.BaseStream, cacheFile); + Files.CopyIfStreamChanged (sw.BaseStream, TaskEnvironment.Fallback.GetAbsolutePath (cacheFile), TaskEnvironment.Fallback); } } diff --git a/src/Microsoft.Android.Build.Tasks/Utilities/AssemblyCompressor.cs b/src/Microsoft.Android.Build.Tasks/Utilities/AssemblyCompressor.cs index 11cd5f35822..e297bff2ac6 100644 --- a/src/Microsoft.Android.Build.Tasks/Utilities/AssemblyCompressor.cs +++ b/src/Microsoft.Android.Build.Tasks/Utilities/AssemblyCompressor.cs @@ -5,6 +5,7 @@ using System.IO.Compression; using Microsoft.Android.Build.Tasks; +using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Microsoft.Android.Tasks; @@ -94,7 +95,7 @@ static CompressionResult Compress (string sourcePath, string outputFilePath, uin bw.Write (destBytes, 0, encodedLength); bw.Flush (); bw.BaseStream.Position = 0; - Files.CopyIfStreamChanged (bw.BaseStream, outputFilePath); + Files.CopyIfStreamChanged (bw.BaseStream, TaskEnvironment.Fallback.GetAbsolutePath (outputFilePath), TaskEnvironment.Fallback); } } finally { if (sourceBytes != null) diff --git a/src/Microsoft.Android.Build.Tasks/Utilities/RuntimeProviderSourceGenerator.cs b/src/Microsoft.Android.Build.Tasks/Utilities/RuntimeProviderSourceGenerator.cs index d08cabdcb5b..5af978a455b 100644 --- a/src/Microsoft.Android.Build.Tasks/Utilities/RuntimeProviderSourceGenerator.cs +++ b/src/Microsoft.Android.Build.Tasks/Utilities/RuntimeProviderSourceGenerator.cs @@ -31,7 +31,7 @@ internal static string [] WriteAdditionalRuntimeProviderSources ( string path = isCoreCLR ? Path.Combine (outputDirectory, "src", "mono", provider + ".java") : Path.Combine (outputDirectory, "src", "net", "dot", "jni", "nativeaot", provider + ".java"); - string absolutePath = taskEnvironment.GetAbsolutePath (path); + AbsolutePath absolutePath = taskEnvironment.GetAbsolutePath (path); if (preserveTimestamp) { Files.CopyIfStringChanged (contents, absolutePath); } else { diff --git a/src/Microsoft.Android.Build.Tasks/Utilities/ZipArchiveEx.cs b/src/Microsoft.Android.Build.Tasks/Utilities/ZipArchiveEx.cs index 3e12b52c4e8..bc9ae8af915 100644 --- a/src/Microsoft.Android.Build.Tasks/Utilities/ZipArchiveEx.cs +++ b/src/Microsoft.Android.Build.Tasks/Utilities/ZipArchiveEx.cs @@ -5,6 +5,7 @@ using System.IO.Compression; using System.Linq; using Microsoft.Android.Build.Tasks; +using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Microsoft.Android.Tasks; @@ -37,7 +38,7 @@ public ZipArchiveEx (string archive, FileMode mode) public void AddDirectory (string folder, string folderInArchive, CompressionLevel method = CompressionLevel.Optimal) { - foreach (var (filename, relativePath) in Files.EnumerateArchiveFiles (folder)) { + foreach (var (filename, relativePath) in Files.EnumerateArchiveFiles (TaskEnvironment.Fallback.GetAbsolutePath (folder))) { var archivePath = Path.Combine (folderInArchive, relativePath).Replace ('\\', '/').TrimStart ('/'); if (SkipExistingFile (filename, archivePath, method)) continue; diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/ConvertResourcesCases.cs b/src/Xamarin.Android.Build.Tasks/Tasks/ConvertResourcesCases.cs index 0a07d513946..3e58d1ec39a 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/ConvertResourcesCases.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/ConvertResourcesCases.cs @@ -91,7 +91,7 @@ void FixupResources (ITaskItem item) continue; } Log.LogDebugMessage (" Processing: {0} {1} > {2}", file, srcmodifiedDate, lastUpdate); - Files.SetWriteable (file); + Files.SetWriteable (TaskEnvironment.Fallback.GetAbsolutePath (file)); bool success = AndroidResource.UpdateXmlResource (resdir, file, resourcedirectories, (level, message) => { switch (level) { @@ -123,7 +123,7 @@ void FixupResources (ITaskItem item) // doesn't support those type of BOM (it really wants the document to start // with " (); foreach (var entry in zip.Entries) { @@ -86,13 +86,13 @@ void ExtractLibraries (string []? libraries, string outputJarsDirectory, string DeleteUnknownFiles (outputAnnotationsDirectory, annotations); } - static void Extract (ZipArchiveEntry entry, MemoryStream stream, string destination) + static void Extract (ZipArchiveEntry entry, MemoryStream stream, AbsolutePath destination) { stream.SetLength (0); //Reuse the stream using (var source = entry.Open ()) source.CopyTo (stream); stream.Position = 0; - Files.CopyIfStreamChanged (stream, destination); + Files.CopyIfStreamChanged (stream, destination, TaskEnvironment.Fallback); } void DeleteUnknownFiles (string directory, HashSet knownFiles) @@ -104,7 +104,7 @@ void DeleteUnknownFiles (string directory, HashSet knownFiles) prefix += Path.DirectorySeparatorChar; foreach (var file in Directory.GetFiles (directory, "*", SearchOption.AllDirectories)) { var fullPath = Path.GetFullPath (file); - var path = Files.GetArchiveExtractionPath (directory, fullPath.Substring (prefix.Length)); + var path = Files.GetArchiveExtractionPath (TaskEnvironment.Fallback.GetAbsolutePath (directory), fullPath.Substring (prefix.Length)); if (!knownFiles.Contains (path)) { Log.LogDebugMessage ($"Deleting unknown file: {path}"); File.Delete (path); diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/GenerateLayoutBindings.cs b/src/Xamarin.Android.Build.Tasks/Tasks/GenerateLayoutBindings.cs index c61156f2a6e..67dc808c3fd 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/GenerateLayoutBindings.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/GenerateLayoutBindings.cs @@ -271,7 +271,7 @@ bool GenerateSource (BindingGenerator generator, string outputFilePath, ICollect } } if (result) - Files.CopyIfChanged (tempFile, outputFilePath); + Files.CopyIfChanged (TaskEnvironment.Fallback.GetAbsolutePath (tempFile), TaskEnvironment.Fallback.GetAbsolutePath (outputFilePath), TaskEnvironment.Fallback); } finally { if (File.Exists (tempFile)) File.Delete (tempFile); diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/GenerateProguardConfiguration.cs b/src/Xamarin.Android.Build.Tasks/Tasks/GenerateProguardConfiguration.cs index 51b28d738e2..704a04b7dc1 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/GenerateProguardConfiguration.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/GenerateProguardConfiguration.cs @@ -33,7 +33,7 @@ public override bool RunTask () ProcessAssembly (assembly.ItemSpec, writer); } - Files.CopyIfStringChanged (writer.ToString (), OutputFile); + Files.CopyIfStringChanged (writer.ToString (), TaskEnvironment.Fallback.GetAbsolutePath (OutputFile)); return !Log.HasLoggedErrors; } diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/GenerateResourceDesigner.cs b/src/Xamarin.Android.Build.Tasks/Tasks/GenerateResourceDesigner.cs index 7e7a04dba68..f214a222cf6 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/GenerateResourceDesigner.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/GenerateResourceDesigner.cs @@ -216,7 +216,7 @@ private void WriteFile (string file, CodeTypeDeclaration resources, string langu provider.GenerateCodeFromCompileUnit(new CodeSnippetCompileUnit("#pragma warning restore 1591"), o, options); o.Flush (); - if (Files.CopyIfStreamChanged (o.BaseStream, file)) { + if (Files.CopyIfStreamChanged (o.BaseStream, TaskEnvironment.Fallback.GetAbsolutePath (file), TaskEnvironment.Fallback)) { Log.LogDebugMessage ($"Writing to: {file}"); } else { Log.LogDebugMessage ($"Up to date: {file}"); diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/GenerateResourceDesignerIntermediateClass.cs b/src/Xamarin.Android.Build.Tasks/Tasks/GenerateResourceDesignerIntermediateClass.cs index ed73e8dc3a9..5e929c45a09 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/GenerateResourceDesignerIntermediateClass.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/GenerateResourceDesignerIntermediateClass.cs @@ -71,7 +71,7 @@ public override bool RunTask () .Replace ("%MODIFIER%", Modifier.ToLower ()); } - Files.CopyIfStringChanged (template, OutputFile.ItemSpec); + Files.CopyIfStringChanged (template, TaskEnvironment.Fallback.GetAbsolutePath (OutputFile.ItemSpec)); return !Log.HasLoggedErrors; } } diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/ManifestMerger.cs b/src/Xamarin.Android.Build.Tasks/Tasks/ManifestMerger.cs index 9e8e6ac81ce..022eaf0a49d 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/ManifestMerger.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/ManifestMerger.cs @@ -82,7 +82,7 @@ public override bool Execute () var ms = MemoryStreamPool.Shared.Rent (); try { m.Save (Log, ms, removeNodes: true); - if (!Files.CopyIfStreamChanged (ms, OutputManifestFile)) { + if (!Files.CopyIfStreamChanged (ms, TaskEnvironment.Fallback.GetAbsolutePath (OutputManifestFile), TaskEnvironment.Fallback)) { // NOTE: We still need to update the timestamp on this file, or the target would run again File.SetLastWriteTimeUtc (OutputManifestFile, DateTime.UtcNow); } diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/PreTrimmingFixLegacyBindings.cs b/src/Xamarin.Android.Build.Tasks/Tasks/PreTrimmingFixLegacyBindings.cs index 4afdcd20f24..3f0a39cb1ea 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/PreTrimmingFixLegacyBindings.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/PreTrimmingFixLegacyBindings.cs @@ -85,9 +85,9 @@ public override bool RunTask () WriteSymbols = assembly.MainModule.HasSymbols, DeterministicMvid = Deterministic, }); - Files.CopyIfChanged (temporaryPath, outputPath); + Files.CopyIfChanged (TaskEnvironment.Fallback.GetAbsolutePath (temporaryPath), TaskEnvironment.Fallback.GetAbsolutePath (outputPath), TaskEnvironment.Fallback); if (File.Exists (temporarySymbols)) { - Files.CopyIfChanged (temporarySymbols, outputSymbols); + Files.CopyIfChanged (TaskEnvironment.Fallback.GetAbsolutePath (temporarySymbols), TaskEnvironment.Fallback.GetAbsolutePath (outputSymbols), TaskEnvironment.Fallback); } else if (File.Exists (outputSymbols)) { File.Delete (outputSymbols); } diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/RemoveDirFixed.cs b/src/Xamarin.Android.Build.Tasks/Tasks/RemoveDirFixed.cs index 5d44fbfea4e..e13360e65bf 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/RemoveDirFixed.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/RemoveDirFixed.cs @@ -63,15 +63,15 @@ public override bool RunTask () continue; } int retryCount = 0; - int attempts = RetryAttempts >= 0 ? RetryAttempts : Files.GetFileWriteRetryAttempts (); - int delay = RetryDelayMs >= 0 ? RetryDelayMs : Files.GetFileWriteRetryDelay (); + int attempts = RetryAttempts >= 0 ? RetryAttempts : Files.GetFileWriteRetryAttempts (TaskEnvironment.Fallback); + int delay = RetryDelayMs >= 0 ? RetryDelayMs : Files.GetFileWriteRetryDelay (TaskEnvironment.Fallback); try { while (retryCount <= attempts) { try { // try to do a normal "fast" delete of the directory. // only do the set writable on the second attempt if (retryCount == 1) - Files.SetDirectoryWriteable (fullPath); + Files.SetDirectoryWriteable (TaskEnvironment.Fallback.GetAbsolutePath (fullPath)); DeleteDirectory (fullPath, true); temporaryRemovedDirectories.Add (directory); break; @@ -117,13 +117,13 @@ public override bool RunTask () /// /// Number of retry attempts when directory deletion fails. - /// Defaults to Files.GetFileWriteRetryAttempts() if not specified. + /// Defaults to Files.GetFileWriteRetryAttempts (TaskEnvironment) if not specified. /// public int RetryAttempts { get; set; } = -1; /// /// Delay in milliseconds between retry attempts. - /// Defaults to Files.GetFileWriteRetryDelay() if not specified. + /// Defaults to Files.GetFileWriteRetryDelay (TaskEnvironment) if not specified. /// public int RetryDelayMs { get; set; } = -1; diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/RemoveUnknownFiles.cs b/src/Xamarin.Android.Build.Tasks/Tasks/RemoveUnknownFiles.cs index 77eb30a79f4..7cec4279314 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/RemoveUnknownFiles.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/RemoveUnknownFiles.cs @@ -60,7 +60,7 @@ public override bool RunTask () Log.LogDebugMessage ("Deleting File {0}", f); var item = new TaskItem (f.Replace (absDir, root + Path.DirectorySeparatorChar)); removedFiles.Add (item); - Microsoft.Android.Build.Tasks.Files.SetWriteable (f); + Microsoft.Android.Build.Tasks.Files.SetWriteable (TaskEnvironment.Fallback.GetAbsolutePath (f)); File.Delete (f); } } @@ -73,7 +73,7 @@ public override bool RunTask () if (!knownDirs.Contains (d) && IsDirectoryEmpty (d)) { Log.LogDebugMessage ("Deleting Directory {0}", d); removedDirectories.Add (new TaskItem(d)); - Microsoft.Android.Build.Tasks.Files.SetDirectoryWriteable (d); + Microsoft.Android.Build.Tasks.Files.SetDirectoryWriteable (TaskEnvironment.Fallback.GetAbsolutePath (d)); System.IO.Directory.Delete (d); } } diff --git a/src/Xamarin.Android.Build.Tasks/Tasks/ResolveLibraryProjectImports.cs b/src/Xamarin.Android.Build.Tasks/Tasks/ResolveLibraryProjectImports.cs index f48475f908d..75d18148c56 100644 --- a/src/Xamarin.Android.Build.Tasks/Tasks/ResolveLibraryProjectImports.cs +++ b/src/Xamarin.Android.Build.Tasks/Tasks/ResolveLibraryProjectImports.cs @@ -120,11 +120,11 @@ public override bool RunTask () if (OS.IsWindows) { foreach (var directory in ResolvedResourceDirectories) { - Files.SetDirectoryWriteable (directory.ItemSpec); + Files.SetDirectoryWriteable (TaskEnvironment.Fallback.GetAbsolutePath (directory.ItemSpec)); } foreach (var directory in ResolvedAssetDirectories) { - Files.SetDirectoryWriteable (directory.ItemSpec); + Files.SetDirectoryWriteable (TaskEnvironment.Fallback.GetAbsolutePath (directory.ItemSpec)); } } @@ -168,7 +168,7 @@ void Extract ( // lets "upgrade" the old directory. string oldPath = Path.GetFullPath (Path.Combine (OutputImportDirectory, "..", "__library_projects__")); if (!OutputImportDirectory.Contains ("__library_projects__") && Directory.Exists (oldPath)) { - Files.SetDirectoryWriteable (Path.Combine (oldPath, "..")); + Files.SetDirectoryWriteable (TaskEnvironment.Fallback.GetAbsolutePath (Path.Combine (oldPath, ".."))); Directory.Delete (oldPath, recursive: true); } var outdir = Path.GetFullPath (OutputImportDirectory); @@ -206,7 +206,7 @@ void Extract ( // Skip already-extracted resources. bool updated = false; - string assemblyHash = Files.HashFile (assemblyPath); + string assemblyHash = Files.HashFile (TaskEnvironment.Fallback.GetAbsolutePath (assemblyPath)); string stamp = Path.Combine (outdir, assemblyIdentName + ".stamp"); string? stampHash = File.Exists (stamp) ? File.ReadAllText (stamp) : null; if (assemblyHash == stampHash) { @@ -261,7 +261,7 @@ void Extract ( // stream disposal finish before pe's enclosing using exits, also on failure. using (var stream = unsafe (pe.GetEmbeddedResourceStream (resource))) { AddJar (jars, importsDir, name, assemblyPath, nuGetPackageId: nuGetPackageId, nuGetPackageVersion: nuGetPackageVersion); - updated |= Files.CopyIfStreamChanged (stream, Files.GetArchiveExtractionPath (importsDir, name)); + updated |= Files.CopyIfStreamChanged (stream, Files.GetArchiveExtractionPath (TaskEnvironment.Fallback.GetAbsolutePath (importsDir), name), TaskEnvironment.Fallback); } } // embedded native libraries @@ -272,7 +272,7 @@ void Extract ( using (var stream = unsafe (pe.GetEmbeddedResourceStream (resource))) using (var zip = new ZipArchive (stream, ZipArchiveMode.Read)) { try { - updated |= Files.ExtractAll (zip, nativeimportsDir, modifyCallback: (entryFullName) => { + updated |= Files.ExtractAll (zip, TaskEnvironment.Fallback.GetAbsolutePath (nativeimportsDir), TaskEnvironment.Fallback, modifyCallback: (entryFullName) => { files.Add (Path.GetFullPath (Path.Combine (nativeimportsDir, entryFullName))); return entryFullName .Replace ("native_library_imports\\", "") @@ -298,7 +298,7 @@ void Extract ( using (var stream = unsafe (pe.GetEmbeddedResourceStream (resource))) using (var zip = new ZipArchive (stream, ZipArchiveMode.Read)) { try { - updated |= Files.ExtractAll (zip, importsDir, modifyCallback: (entryFullName) => { + updated |= Files.ExtractAll (zip, TaskEnvironment.Fallback.GetAbsolutePath (importsDir), TaskEnvironment.Fallback, modifyCallback: (entryFullName) => { var path = entryFullName .Replace ("library_project_imports\\", "") .Replace ("library_project_imports/", ""); @@ -383,7 +383,7 @@ void Extract ( })); bool updated = false; - string aarHash = Files.HashFile (aarFile.ItemSpec); + string aarHash = Files.HashFile (TaskEnvironment.Fallback.GetAbsolutePath (aarFile.ItemSpec)); string stamp = Path.Combine (outdir, aarIdentityName + ".stamp"); string? stampHash = File.Exists (stamp) ? File.ReadAllText (stamp) : null; var aarFullPath = Path.GetFullPath (aarFile.ItemSpec); @@ -429,7 +429,7 @@ void Extract ( using (var zip = MonoAndroidHelper.ReadZipFile (aarFile.ItemSpec)) { try { - updated |= Files.ExtractAll (zip, importsDir, modifyCallback: (entryFullName) => { + updated |= Files.ExtractAll (zip, TaskEnvironment.Fallback.GetAbsolutePath (importsDir), TaskEnvironment.Fallback, modifyCallback: (entryFullName) => { var entryFileName = Path.GetFileName (entryFullName); var entryPath = Path.GetDirectoryName (entryFullName); if (entryFileName.StartsWith ("internal_impl", StringComparison.InvariantCulture)) { @@ -442,7 +442,7 @@ void Extract ( AddJar (jars, importsDir, entryFullName, aarFullPath, nuGetPackageId: nuGetPackageId, nuGetPackageVersion: nuGetPackageVersion); } else if (entryFullName.StartsWith (".net/env/", StringComparison.OrdinalIgnoreCase) || entryFullName.StartsWith (".net\\env\\", StringComparison.OrdinalIgnoreCase)) { - var fullPath = Files.GetArchiveExtractionPath (importsDir, entryFullName); + var fullPath = Files.GetArchiveExtractionPath (TaskEnvironment.Fallback.GetAbsolutePath (importsDir), entryFullName); resolvedEnvironments.Add (new TaskItem (fullPath, new Dictionary { [OriginalFile] = aarFile.ItemSpec, [NuGetPackageId] = nuGetPackageId, @@ -493,7 +493,7 @@ void Extract ( static void AddJar (IDictionary jars, string destination, string path, string? originalFile = null, string? nuGetPackageId = null, string? nuGetPackageVersion = null) { - var fullPath = Files.GetArchiveExtractionPath (destination, path); + var fullPath = Files.GetArchiveExtractionPath (TaskEnvironment.Fallback.GetAbsolutePath (destination), path); AddJar (jars, fullPath, originalFile: originalFile, nuGetPackageId: nuGetPackageId, nuGetPackageVersion: nuGetPackageVersion); } diff --git a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/IncrementalBuildTest.cs b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/IncrementalBuildTest.cs index 64a50a1fd1a..c4d472048a3 100644 --- a/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/IncrementalBuildTest.cs +++ b/src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/IncrementalBuildTest.cs @@ -18,6 +18,8 @@ namespace Xamarin.Android.Build.Tests [TestClass] public class IncrementalBuildTest : BaseTest { + static string HashFile (string path) => Files.HashFile (TaskEnvironment.Fallback.GetAbsolutePath (path)); + [TestMethod] public void AaptRulesRemainInR8ConfigurationAfterIncrementalBuild () { @@ -340,14 +342,14 @@ public void BasicApplicationRepetitiveReleaseBuild ([CombinatorialValues (Androi Path.Combine (outputDirectory, $"{proj.PackageName}-Signed.aab"), Path.Combine (outputDirectory, $"{proj.PackageName}-Signed.apk"), ]; - var packageHashes = packages.Select (Files.HashFile).ToArray (); + var packageHashes = packages.Select (HashFile).ToArray (); var packageWriteTimes = packages.Select (File.GetLastWriteTimeUtc).ToArray (); Assert.IsTrue (b.Build (proj, doNotCleanupOnUpdate: true, saveProject: false), "second build failed"); b.Output.AssertTargetIsSkipped ("CoreCompile"); b.Output.AssertTargetIsSkipped ("_Sign"); b.Output.AssertTargetIsSkipped (compilationTarget); - CollectionAssert.AreEqual (packageHashes, packages.Select (Files.HashFile).ToArray (), "An unchanged build should preserve package contents."); + CollectionAssert.AreEqual (packageHashes, packages.Select (HashFile).ToArray (), "An unchanged build should preserve package contents."); CollectionAssert.AreEqual (packageWriteTimes, packages.Select (File.GetLastWriteTimeUtc).ToArray (), "An unchanged build should not rewrite packages."); // A timestamp-only touch can produce identical binaries and legitimately skip signing. @@ -361,16 +363,16 @@ public void BasicApplicationRepetitiveReleaseBuild ([CombinatorialValues (Androi b.Output.AssertTargetIsPartiallyBuilt ("_CompressAssemblies"); } for (int i = 0; i < packages.Length; i++) { - Assert.AreNotEqual (packageHashes [i], Files.HashFile (packages [i]), $"Changing reachable code should update {packages [i]}."); + Assert.AreNotEqual (packageHashes [i], HashFile (packages [i]), $"Changing reachable code should update {packages [i]}."); } - packageHashes = packages.Select (Files.HashFile).ToArray (); + packageHashes = packages.Select (HashFile).ToArray (); packageWriteTimes = packages.Select (File.GetLastWriteTimeUtc).ToArray (); Assert.IsTrue (b.Build (proj, doNotCleanupOnUpdate: true, saveProject: false), "fourth build failed"); b.Output.AssertTargetIsSkipped ("CoreCompile"); b.Output.AssertTargetIsSkipped (compilationTarget); b.Output.AssertTargetIsSkipped ("_Sign"); - CollectionAssert.AreEqual (packageHashes, packages.Select (Files.HashFile).ToArray (), "An unchanged build after a code change should preserve package contents."); + CollectionAssert.AreEqual (packageHashes, packages.Select (HashFile).ToArray (), "An unchanged build after a code change should preserve package contents."); CollectionAssert.AreEqual (packageWriteTimes, packages.Select (File.GetLastWriteTimeUtc).ToArray (), "An unchanged build after a code change should not rewrite packages."); } } @@ -1909,7 +1911,7 @@ public void GenerateJavaStubsAndAssembly ([ValidRuntimeConfigurations] (bool isR Assert.IsTrue (File.Exists (typemap), "The managed application type map should be generated."); string apk = Directory.GetFiles (Path.Combine (projectDirectory, proj.OutputPath), "*-Signed.apk", SearchOption.AllDirectories).Single (); DateTime apkWriteTime = File.GetLastWriteTimeUtc (apk); - string apkHash = Files.HashFile (apk); + string apkHash = HashFile (apk); // Change managed code without changing any Java type mappings. proj.MainActivity = proj.MainActivity.Replace ("clicks", "CLICKS"); @@ -1920,7 +1922,7 @@ public void GenerateJavaStubsAndAssembly ([ValidRuntimeConfigurations] (bool isR b.Output.AssertTargetIsSkipped ("_BuildApkFastDev"); b.Output.AssertTargetIsSkipped ("_Sign"); Assert.AreEqual (apkWriteTime, File.GetLastWriteTimeUtc (apk), $"{apk} should not be rewritten for an incremental C# change."); - Assert.AreEqual (apkHash, Files.HashFile (apk), $"{apk} contents should not change."); + Assert.AreEqual (apkHash, HashFile (apk), $"{apk} contents should not change."); } } } @@ -1958,7 +1960,7 @@ public void DeterministicBuilds (bool deterministic, [CombinatorialValues (false Assert.IsTrue (b.Build (proj), "first build should have succeeded."); var output = Path.Combine (Root, b.ProjectDirectory, proj.OutputPath, $"{proj.ProjectName}.dll"); Assert.IsTrue (File.Exists (output)); - string expectedHash = Files.HashFile (output); + string expectedHash = HashFile (output); Guid expectedMvid; using (var assembly = AssemblyDefinition.ReadAssembly (output)) { expectedMvid = assembly.MainModule.Mvid; @@ -1970,10 +1972,10 @@ public void DeterministicBuilds (bool deterministic, [CombinatorialValues (false using (var assembly = AssemblyDefinition.ReadAssembly (output)) { if (deterministic) { Assert.AreEqual (expectedMvid, assembly.MainModule.Mvid, "Mvid should match"); - Assert.AreEqual (expectedHash, Files.HashFile (output), "hash should match"); + Assert.AreEqual (expectedHash, HashFile (output), "hash should match"); } else { Assert.AreNotEqual (expectedMvid, assembly.MainModule.Mvid, "Mvid should *not* match"); - Assert.AreNotEqual (expectedHash, Files.HashFile (output), "hash should *not* match"); + Assert.AreNotEqual (expectedHash, HashFile (output), "hash should *not* match"); } } } @@ -2443,12 +2445,12 @@ public void PostTrimmingPipelineIsSkippedOnSecondBuild ([CombinatorialValues ("a b.Output.AssertTargetIsNotSkipped ("_PostTrimmingPipeline"); var linkedAssembly = Path.Combine (Root, b.ProjectDirectory, proj.IntermediateOutputPath, MonoAndroidHelper.AbiToRid (abi), "linked", $"{proj.ProjectName}.dll"); Assert.IsTrue (File.Exists (linkedAssembly), "The post-trimming pipeline should operate on the linked application assembly."); - var assemblyHash = Files.HashFile (linkedAssembly); + var assemblyHash = HashFile (linkedAssembly); var assemblyWriteTime = File.GetLastWriteTimeUtc (linkedAssembly); Assert.IsTrue (b.Build (proj, doNotCleanupOnUpdate: true, saveProject: false), "second build should succeed"); b.Output.AssertTargetIsSkipped ("_PostTrimmingPipeline"); - Assert.AreEqual (assemblyHash, Files.HashFile (linkedAssembly), "A no-change build should preserve the linked assembly."); + Assert.AreEqual (assemblyHash, HashFile (linkedAssembly), "A no-change build should preserve the linked assembly."); Assert.AreEqual (assemblyWriteTime, File.GetLastWriteTimeUtc (linkedAssembly), "A no-change build should not rewrite the linked assembly."); foreach (string keepAlives in new [] { "false", "true" }) { diff --git a/src/Xamarin.Android.Build.Tasks/Utilities/AndroidResource.cs b/src/Xamarin.Android.Build.Tasks/Utilities/AndroidResource.cs index 6332827acca..a4d3fd9580f 100644 --- a/src/Xamarin.Android.Build.Tasks/Utilities/AndroidResource.cs +++ b/src/Xamarin.Android.Build.Tasks/Utilities/AndroidResource.cs @@ -11,6 +11,7 @@ using System.Xml.XPath; using Xamarin.Android.Tasks; using Microsoft.Android.Build.Tasks; +using Microsoft.Build.Framework; namespace Monodroid { static class AndroidResource { @@ -28,7 +29,7 @@ public static bool UpdateXmlResource (string res, string filename, IEnumerable LoadMapFile (IBuildEngine4 engine, string mapFile, StringComparer comparer) @@ -326,7 +326,7 @@ public static bool SaveCustomViewMapFile (IBuildEngine4 engine, string mapFile, writer.WriteLine ($"{i.Key};{v}"); } writer.Flush (); - return Files.CopyIfStreamChanged (writer.BaseStream, mapFile); + return Files.CopyIfStreamChanged (writer.BaseStream, TaskEnvironment.Fallback.GetAbsolutePath (mapFile), TaskEnvironment.Fallback); } } diff --git a/src/Xamarin.Android.Build.Tasks/Utilities/RtxtWriter.cs b/src/Xamarin.Android.Build.Tasks/Utilities/RtxtWriter.cs index 0a166b1e4d7..a4595eacf6d 100644 --- a/src/Xamarin.Android.Build.Tasks/Utilities/RtxtWriter.cs +++ b/src/Xamarin.Android.Build.Tasks/Utilities/RtxtWriter.cs @@ -5,6 +5,7 @@ using System.Text; using System.Linq; using Microsoft.Android.Build.Tasks; +using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Xamarin.Android.Tasks @@ -24,7 +25,7 @@ public void Write (string file, IList items) sw.WriteLine (item.ToString ()); } sw.Flush (); - Files.CopyIfStreamChanged (sw.BaseStream, file); + Files.CopyIfStreamChanged (sw.BaseStream, TaskEnvironment.Fallback.GetAbsolutePath (file), TaskEnvironment.Fallback); } } } diff --git a/tests/Microsoft.Android.Build.BaseTasks-Tests/FilesTests.cs b/tests/Microsoft.Android.Build.BaseTasks-Tests/FilesTests.cs index ba51edd75da..a3506b0ab5d 100644 --- a/tests/Microsoft.Android.Build.BaseTasks-Tests/FilesTests.cs +++ b/tests/Microsoft.Android.Build.BaseTasks-Tests/FilesTests.cs @@ -90,11 +90,11 @@ public void CopyIfStringChanged () var tempFile = Path.Combine (tempDir, "foo.txt"); var foo = "bar"; - Assert.IsTrue (Files.CopyIfStringChanged (foo, tempFile), "Should write on new file."); + Assert.IsTrue (Files.CopyIfStringChanged (foo, new AbsolutePath (tempFile)), "Should write on new file."); Assert.IsTrue (File.Exists (tempFile)); - Assert.IsFalse (Files.CopyIfStringChanged (foo, tempFile), "Should *not* write unless changed."); + Assert.IsFalse (Files.CopyIfStringChanged (foo, new AbsolutePath (tempFile)), "Should *not* write unless changed."); foo += "\n"; - Assert.IsTrue (Files.CopyIfStringChanged (foo, tempFile), "Should write when changed."); + Assert.IsTrue (Files.CopyIfStringChanged (foo, new AbsolutePath (tempFile)), "Should write when changed."); } [TestMethod] @@ -104,11 +104,11 @@ public void CopyIfBytesChanged () var tempFile = Path.Combine (tempDir, "foo.bin"); var foo = new byte [32]; - Assert.IsTrue (Files.CopyIfBytesChanged (foo, tempFile), "Should write on new file."); + Assert.IsTrue (Files.CopyIfBytesChanged (foo, new AbsolutePath (tempFile)), "Should write on new file."); Assert.IsTrue (File.Exists (tempFile)); - Assert.IsFalse (Files.CopyIfBytesChanged (foo, tempFile), "Should *not* write unless changed."); + Assert.IsFalse (Files.CopyIfBytesChanged (foo, new AbsolutePath (tempFile)), "Should *not* write unless changed."); foo [0] = 0xFF; - Assert.IsTrue (Files.CopyIfBytesChanged (foo, tempFile), "Should write when changed."); + Assert.IsTrue (Files.CopyIfBytesChanged (foo, new AbsolutePath (tempFile)), "Should write when changed."); } [TestMethod] @@ -122,12 +122,12 @@ public void CopyIfStreamChanged () writer.WriteLine ("bar"); writer.Flush (); - Assert.IsTrue (Files.CopyIfStreamChanged (foo, tempFile), "Should write on new file."); + Assert.IsTrue (Files.CopyIfStreamChanged (foo, new AbsolutePath (tempFile), TaskEnvironment.Fallback), "Should write on new file."); Assert.IsTrue (File.Exists (tempFile)); - Assert.IsFalse (Files.CopyIfStreamChanged (foo, tempFile), "Should *not* write unless changed."); + Assert.IsFalse (Files.CopyIfStreamChanged (foo, new AbsolutePath (tempFile), TaskEnvironment.Fallback), "Should *not* write unless changed."); writer.WriteLine (); writer.Flush (); - Assert.IsTrue (Files.CopyIfStreamChanged (foo, tempFile), "Should write when changed."); + Assert.IsTrue (Files.CopyIfStreamChanged (foo, new AbsolutePath (tempFile), TaskEnvironment.Fallback), "Should write when changed."); } } @@ -179,7 +179,7 @@ public void CopyIfStringChanged_NewDirectory () var tempFile = Path.Combine (tempDir, "foo.txt"); var foo = "bar"; - Assert.IsTrue (Files.CopyIfStringChanged (foo, tempFile), "Should write on new file."); + Assert.IsTrue (Files.CopyIfStringChanged (foo, new AbsolutePath (tempFile)), "Should write on new file."); Assert.IsTrue (File.Exists (tempFile)); } @@ -190,7 +190,7 @@ public void CopyIfBytesChanged_NewDirectory () var tempFile = Path.Combine (tempDir, "foo.bin"); var foo = new byte [32]; - Assert.IsTrue (Files.CopyIfBytesChanged (foo, tempFile), "Should write on new file."); + Assert.IsTrue (Files.CopyIfBytesChanged (foo, new AbsolutePath (tempFile)), "Should write on new file."); Assert.IsTrue (File.Exists (tempFile)); } @@ -205,7 +205,7 @@ public void CopyIfStreamChanged_NewDirectory () writer.WriteLine ("bar"); writer.Flush (); - Assert.IsTrue (Files.CopyIfStreamChanged (foo, tempFile), "Should write on new file."); + Assert.IsTrue (Files.CopyIfStreamChanged (foo, new AbsolutePath (tempFile), TaskEnvironment.Fallback), "Should write on new file."); Assert.IsTrue (File.Exists (tempFile)); } } @@ -223,7 +223,7 @@ public void CopyIfBytesChanged_Readonly () File.SetAttributes (tempFile, FileAttributes.ReadOnly); var foo = new byte [32]; - Assert.IsTrue (Files.CopyIfBytesChanged (foo, tempFile), "Should write on new file."); + Assert.IsTrue (Files.CopyIfBytesChanged (foo, new AbsolutePath (tempFile)), "Should write on new file."); Assert.IsTrue (File.Exists (tempFile)); } @@ -242,7 +242,7 @@ public void CleanBOM_Readonly () } File.SetAttributes (tempFile, FileAttributes.ReadOnly); var before = File.ReadAllBytes (tempFile); - Files.CleanBOM (tempFile); + Files.CleanBOM (new AbsolutePath (tempFile)); var after = File.ReadAllBytes (tempFile); var preamble = encoding.GetPreamble (); Assert.AreEqual (before.Length, after.Length + preamble.Length, "BOM should be removed!"); @@ -262,7 +262,7 @@ public void CopyIfStreamChanged_MemoryStreamPool_StreamWriter () writer.WriteLine ("bar"); writer.Flush (); - Assert.IsTrue (Files.CopyIfStreamChanged (writer.BaseStream, tempFile), "Should write on new file."); + Assert.IsTrue (Files.CopyIfStreamChanged (writer.BaseStream, new AbsolutePath (tempFile), TaskEnvironment.Fallback), "Should write on new file."); Assert.IsTrue (File.Exists (tempFile)); } @@ -285,7 +285,7 @@ public void CopyIfStreamChanged_MemoryStreamPool_BinaryWriter () writer.Write (42); writer.Flush (); - Assert.IsTrue (Files.CopyIfStreamChanged (writer.BaseStream, tempFile), "Should write on new file."); + Assert.IsTrue (Files.CopyIfStreamChanged (writer.BaseStream, new AbsolutePath (tempFile), TaskEnvironment.Fallback), "Should write on new file."); Assert.IsTrue (File.Exists (tempFile)); } @@ -303,7 +303,7 @@ public void SetWriteable () File.WriteAllText (tempFile, contents: "foo"); File.SetAttributes (tempFile, FileAttributes.ReadOnly); - Files.SetWriteable (tempFile); + Files.SetWriteable (new AbsolutePath (tempFile)); var attributes = File.GetAttributes (tempFile); Assert.AreEqual (FileAttributes.Normal, attributes); @@ -317,7 +317,7 @@ public void SetDirectoryWriteable () try { var directoryInfo = new DirectoryInfo (tempDir); directoryInfo.Attributes |= FileAttributes.ReadOnly; - Files.SetDirectoryWriteable (tempDir); + Files.SetDirectoryWriteable (new AbsolutePath (tempDir)); directoryInfo = new DirectoryInfo (tempDir); Assert.AreEqual (FileAttributes.Directory, directoryInfo.Attributes); @@ -342,7 +342,7 @@ bool ExtractAll (MemoryStream stream) { stream.Position = 0; using (var zip = new ZipArchive (stream, ZipArchiveMode.Read, leaveOpen: true)) { - return Files.ExtractAll (zip, tempDir); + return Files.ExtractAll (zip, new AbsolutePath (tempDir), TaskEnvironment.Fallback); } } @@ -377,7 +377,7 @@ public void CopyIfChanged_NoChanges () { var src = NewFile ("foo"); var dest = NewFile ("foo"); - Assert.IsFalse (Files.CopyIfChanged (src, dest), "No change should have occurred"); + Assert.IsFalse (Files.CopyIfChanged (new AbsolutePath (src), new AbsolutePath (dest), TaskEnvironment.Fallback), "No change should have occurred"); CollectionAssert.AreEqual (File.ReadAllBytes (src), File.ReadAllBytes (dest)); } @@ -386,7 +386,7 @@ public void CopyIfChanged_NoExist () { var src = NewFile ("foo"); var dest = NewFile (); - Assert.IsTrue (Files.CopyIfChanged (src, dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfChanged (new AbsolutePath (src), new AbsolutePath (dest), TaskEnvironment.Fallback), "Changes should have occurred"); CollectionAssert.AreEqual (File.ReadAllBytes (src), File.ReadAllBytes (dest)); } @@ -396,7 +396,7 @@ public void CopyIfChanged_LongPath () var src = NewFile (contents: "foo"); var dest = NewFile (contents: "bar", fileName: "bar".PadRight (MaxFileName, 'N')); dest = Files.ToLongPath (dest); - Assert.IsTrue (Files.CopyIfChanged (src, dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfChanged (new AbsolutePath (src), new AbsolutePath (dest), TaskEnvironment.Fallback), "Changes should have occurred"); CollectionAssert.AreEqual (File.ReadAllBytes (src), File.ReadAllBytes (dest)); } @@ -405,7 +405,7 @@ public void CopyIfChanged_Changes () { var src = NewFile ("foo"); var dest = NewFile ("bar"); - Assert.IsTrue (Files.CopyIfChanged (src, dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfChanged (new AbsolutePath (src), new AbsolutePath (dest), TaskEnvironment.Fallback), "Changes should have occurred"); CollectionAssert.AreEqual (File.ReadAllBytes (src), File.ReadAllBytes (dest)); } @@ -415,7 +415,7 @@ public void CopyIfChanged_Readonly () var src = NewFile ("foo"); var dest = NewFile ("bar"); File.SetAttributes (dest, FileAttributes.ReadOnly); - Assert.IsTrue (Files.CopyIfChanged (src, dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfChanged (new AbsolutePath (src), new AbsolutePath (dest), TaskEnvironment.Fallback), "Changes should have occurred"); CollectionAssert.AreEqual (File.ReadAllBytes (src), File.ReadAllBytes (dest)); } @@ -425,7 +425,7 @@ public void CopyIfChanged_CasingChange () var src = NewFile (contents: "foo"); var dest = NewFile (contents: "Foo", fileName: "foo"); dest = dest.Replace ("foo", "Foo"); - Assert.IsTrue (Files.CopyIfChanged (src, dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfChanged (new AbsolutePath (src), new AbsolutePath (dest), TaskEnvironment.Fallback), "Changes should have occurred"); CollectionAssert.AreEqual (File.ReadAllBytes (src), File.ReadAllBytes (dest)); var files = Directory.GetFiles (Path.GetDirectoryName (dest), "Foo"); @@ -436,7 +436,7 @@ public void CopyIfChanged_CasingChange () public void CopyIfStringChanged_NoChanges () { var dest = NewFile ("foo"); - Assert.IsFalse (Files.CopyIfStringChanged ("foo", dest), "No change should have occurred"); + Assert.IsFalse (Files.CopyIfStringChanged ("foo", new AbsolutePath (dest)), "No change should have occurred"); Assert.IsTrue (File.Exists (dest)); } @@ -444,7 +444,7 @@ public void CopyIfStringChanged_NoChanges () public void CopyIfStringChanged_NoExist () { var dest = NewFile (); - Assert.IsTrue (Files.CopyIfStringChanged ("foo", dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfStringChanged ("foo", new AbsolutePath (dest)), "Changes should have occurred"); Assert.IsTrue (File.Exists (dest)); } @@ -453,7 +453,7 @@ public void CopyIfStringChanged_LongPath () { var dest = NewFile (fileName: "bar".PadRight (MaxFileName, 'N')); dest = Files.ToLongPath (dest); - Assert.IsTrue (Files.CopyIfStringChanged ("foo", dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfStringChanged ("foo", new AbsolutePath (dest)), "Changes should have occurred"); Assert.IsTrue (File.Exists (dest)); } @@ -461,7 +461,7 @@ public void CopyIfStringChanged_LongPath () public void CopyIfStringChanged_Changes () { var dest = NewFile ("bar"); - Assert.IsTrue (Files.CopyIfStringChanged ("foo", dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfStringChanged ("foo", new AbsolutePath (dest)), "Changes should have occurred"); Assert.IsTrue (File.Exists (dest)); } @@ -470,7 +470,7 @@ public void CopyIfStringChanged_Readonly () { var dest = NewFile ("bar"); File.SetAttributes (dest, FileAttributes.ReadOnly); - Assert.IsTrue (Files.CopyIfStringChanged ("foo", dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfStringChanged ("foo", new AbsolutePath (dest)), "Changes should have occurred"); Assert.IsTrue (File.Exists (dest)); } @@ -479,7 +479,7 @@ public void CopyIfStringChanged_CasingChange () { var dest = NewFile (contents: "foo", fileName: "foo"); dest = dest.Replace ("foo", "Foo"); - Assert.IsTrue (Files.CopyIfStringChanged ("Foo", dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfStringChanged ("Foo", new AbsolutePath (dest)), "Changes should have occurred"); Assert.IsTrue (File.Exists (dest)); Assert.AreEqual ("Foo", File.ReadAllText (dest), "File contents should match"); @@ -492,7 +492,7 @@ public void CopyIfStreamChanged_NoChanges () { using (var src = NewStream ("foo")) { var dest = NewFile ("foo"); - Assert.IsFalse (Files.CopyIfStreamChanged (src, dest), "No change should have occurred"); + Assert.IsFalse (Files.CopyIfStreamChanged (src, new AbsolutePath (dest), TaskEnvironment.Fallback), "No change should have occurred"); Assert.IsTrue (File.Exists (dest)); } } @@ -503,7 +503,7 @@ public void CopyIfStreamChanged_LongPath () using (var src = NewStream ("foo")) { var dest = NewFile (fileName: "bar".PadRight (MaxFileName, 'N')); dest = Files.ToLongPath (dest); - Assert.IsTrue (Files.CopyIfStreamChanged (src, dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfStreamChanged (src, new AbsolutePath (dest), TaskEnvironment.Fallback), "Changes should have occurred"); Assert.IsTrue (File.Exists (dest)); } } @@ -513,7 +513,7 @@ public void CopyIfStreamChanged_NoExist () { using (var src = NewStream ("foo")) { var dest = NewFile (); - Assert.IsTrue (Files.CopyIfStreamChanged (src, dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfStreamChanged (src, new AbsolutePath (dest), TaskEnvironment.Fallback), "Changes should have occurred"); Assert.IsTrue (File.Exists (dest)); } } @@ -523,7 +523,7 @@ public void CopyIfStreamChanged_Changes () { using (var src = NewStream ("foo")) { var dest = NewFile ("bar"); - Assert.IsTrue (Files.CopyIfStreamChanged (src, dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfStreamChanged (src, new AbsolutePath (dest), TaskEnvironment.Fallback), "Changes should have occurred"); Assert.IsTrue (File.Exists (dest)); } } @@ -534,7 +534,7 @@ public void CopyIfStreamChanged_Readonly () using (var src = NewStream ("foo")) { var dest = NewFile ("bar"); File.SetAttributes (dest, FileAttributes.ReadOnly); - Assert.IsTrue (Files.CopyIfStreamChanged (src, dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfStreamChanged (src, new AbsolutePath (dest), TaskEnvironment.Fallback), "Changes should have occurred"); Assert.IsTrue (File.Exists (dest)); } } @@ -545,7 +545,7 @@ public void CopyIfStreamChanged_CasingChange () using (var src = NewStream ("Foo")) { var dest = NewFile (contents: "foo", fileName: "foo"); dest = dest.Replace ("foo", "Foo"); - Assert.IsTrue (Files.CopyIfStreamChanged (src, dest), "Changes should have occurred"); + Assert.IsTrue (Files.CopyIfStreamChanged (src, new AbsolutePath (dest), TaskEnvironment.Fallback), "Changes should have occurred"); Assert.IsTrue (File.Exists (dest)); Assert.AreEqual ("Foo", File.ReadAllText (dest), "File contents should match"); @@ -560,10 +560,10 @@ public async Task CopyIfChanged_LockedFile () var dest = NewFile (contents: "foo", fileName: "foo_locked"); var src = NewFile (contents: "foo0", fileName: "foo"); using (var file = File.OpenWrite (dest)) { - Assert.ThrowsExactly (() => Files.CopyIfChanged (src, dest)); + Assert.ThrowsExactly (() => Files.CopyIfChanged (new AbsolutePath (src), new AbsolutePath (dest), TaskEnvironment.Fallback)); } src = NewFile (contents: "foo1", fileName: "foo"); - Assert.IsTrue (Files.CopyIfChanged (src, dest)); + Assert.IsTrue (Files.CopyIfChanged (new AbsolutePath (src), new AbsolutePath (dest), TaskEnvironment.Fallback)); src = NewFile (contents: "foo2", fileName: "foo"); dest = NewFile (contents: "foo", fileName: "foo_locked2"); var ev = new ManualResetEvent (false); @@ -578,7 +578,7 @@ public async Task CopyIfChanged_LockedFile () } }); ev.WaitOne (); - Assert.IsTrue (Files.CopyIfChanged (src, dest)); + Assert.IsTrue (Files.CopyIfChanged (new AbsolutePath (src), new AbsolutePath (dest), TaskEnvironment.Fallback)); await task; } @@ -593,7 +593,7 @@ public void CopyIfChanged_ProjectScopedRetries () var src = NewFile (contents: "foo0", fileName: "foo"); using var locked = new FileStream (dest, FileMode.Open, FileAccess.ReadWrite, FileShare.None); var stopwatch = Stopwatch.StartNew (); - Assert.ThrowsExactly (() => Files.CopyIfChanged (src, dest, environment)); + Assert.ThrowsExactly (() => Files.CopyIfChanged (environment.GetAbsolutePath (src), environment.GetAbsolutePath (dest), environment)); Assert.IsLessThan (TimeSpan.FromSeconds (2), stopwatch.Elapsed, "The project's retry limit must be used."); } @@ -720,7 +720,7 @@ public void ExtractAll_ModifyCallback () stream.Position = 0; using (var zip = new ZipArchive (stream, ZipArchiveMode.Read, leaveOpen: true)) { - bool changes = Files.ExtractAll (zip, tempDir, modifyCallback: e => e.Replace ("foo/", "")); + bool changes = Files.ExtractAll (zip, new AbsolutePath (tempDir), TaskEnvironment.Fallback, modifyCallback: e => e.Replace ("foo/", "")); Assert.IsTrue (changes, "ExtractAll should report changes."); } @@ -738,7 +738,7 @@ public void ExtractAll_SkipCallback () stream.Position = 0; using (var zip = new ZipArchive (stream, ZipArchiveMode.Read, leaveOpen: true)) { - bool changes = Files.ExtractAll (zip, tempDir, skipCallback: e => e == "a.txt"); + bool changes = Files.ExtractAll (zip, new AbsolutePath (tempDir), TaskEnvironment.Fallback, skipCallback: e => e == "a.txt"); Assert.IsTrue (changes, "ExtractAll should report changes."); } @@ -771,7 +771,7 @@ public void ExtractAll_RejectsPathTraversal () stream.Position = 0; using (var zip = new ZipArchive (stream, ZipArchiveMode.Read, leaveOpen: true)) { // modifyCallback introduces a path traversal - Assert.ThrowsExactly (() => Files.ExtractAll (zip, destinationDir, modifyCallback: e => "../" + e)); + Assert.ThrowsExactly (() => Files.ExtractAll (zip, new AbsolutePath (destinationDir), TaskEnvironment.Fallback, modifyCallback: e => "../" + e)); } Assert.IsFalse (File.Exists (Path.Combine (tempDir, "a.txt"))); } @@ -788,7 +788,7 @@ public void ExtractAll_RejectsTraversalBeforeWritingValidEntries () stream.Position = 0; using (var zip = new ZipArchive (stream, ZipArchiveMode.Read, leaveOpen: true)) { // Only relative.txt gets a traversal prefix - Assert.ThrowsExactly (() => Files.ExtractAll (zip, destinationDir, modifyCallback: e => + Assert.ThrowsExactly (() => Files.ExtractAll (zip, new AbsolutePath (destinationDir), TaskEnvironment.Fallback, modifyCallback: e => e == "relative.txt" ? "../" + e : e)); } Assert.IsFalse (File.Exists (Path.Combine (destinationDir, "good.txt"))); @@ -807,7 +807,7 @@ public void ExtractAll_RejectsPathTraversal_ForwardSlash (string prefix) var destinationDir = Path.Combine (tempDir, "dest"); stream.Position = 0; using (var zip = new ZipArchive (stream, ZipArchiveMode.Read, leaveOpen: true)) { - Assert.ThrowsExactly (() => Files.ExtractAll (zip, destinationDir, modifyCallback: e => prefix + e)); + Assert.ThrowsExactly (() => Files.ExtractAll (zip, new AbsolutePath (destinationDir), TaskEnvironment.Fallback, modifyCallback: e => prefix + e)); } } @@ -823,7 +823,7 @@ public void ExtractAll_RejectsPathTraversal_BackSlash (string prefix) var destinationDir = Path.Combine (tempDir, "dest"); stream.Position = 0; using (var zip = new ZipArchive (stream, ZipArchiveMode.Read, leaveOpen: true)) { - Assert.ThrowsExactly (() => Files.ExtractAll (zip, destinationDir, modifyCallback: e => prefix + e)); + Assert.ThrowsExactly (() => Files.ExtractAll (zip, new AbsolutePath (destinationDir), TaskEnvironment.Fallback, modifyCallback: e => prefix + e)); } } @@ -846,10 +846,10 @@ public void CopyIfZipChanged_Stream () } stream.Position = 0; - Assert.IsTrue (Files.CopyIfZipChanged (stream, destination), "Should copy on new file."); + Assert.IsTrue (Files.CopyIfZipChanged (stream, new AbsolutePath (destination)), "Should copy on new file."); Assert.IsTrue (File.Exists (destination)); stream.Position = 0; - Assert.IsFalse (Files.CopyIfZipChanged (stream, destination), "Should *not* copy when unchanged."); + Assert.IsFalse (Files.CopyIfZipChanged (stream, new AbsolutePath (destination)), "Should *not* copy when unchanged."); } [TestMethod] @@ -867,31 +867,9 @@ public void CopyIfZipChanged_String () stream.CopyTo (f); } - Assert.IsTrue (Files.CopyIfZipChanged (source, destination), "Should copy on new file."); + Assert.IsTrue (Files.CopyIfZipChanged (new AbsolutePath (source), new AbsolutePath (destination)), "Should copy on new file."); Assert.IsTrue (File.Exists (destination)); - Assert.IsFalse (Files.CopyIfZipChanged (source, destination), "Should *not* copy when unchanged."); - } - - [TestMethod] - public void CopyIfZipChanged_BareFileName () - { - // Regression test: Path.GetDirectoryName("file.zip") returns "", - // which previously caused Directory.CreateDirectory("") to throw. - var cwd = Directory.GetCurrentDirectory (); - try { - Directory.CreateDirectory (tempDir); - Directory.SetCurrentDirectory (tempDir); - - using (var zip = new ZipArchive (stream, ZipArchiveMode.Create, leaveOpen: true)) { - WriteEntry (zip, "a.txt", "a"); - } - stream.Position = 0; - - Assert.IsTrue (Files.CopyIfZipChanged (stream, "bare.zip"), "Should copy bare filename."); - Assert.IsTrue (File.Exists (Path.Combine (tempDir, "bare.zip"))); - } finally { - Directory.SetCurrentDirectory (cwd); - } + Assert.IsFalse (Files.CopyIfZipChanged (new AbsolutePath (source), new AbsolutePath (destination)), "Should *not* copy when unchanged."); } [TestMethod] @@ -899,7 +877,7 @@ public void DeleteFile_NullLog_DoesNotThrow () { var path = Path.Combine (tempDir, "directory-instead-of-file"); Directory.CreateDirectory (path); - Files.DeleteFile (path, null); + Files.DeleteFile (new AbsolutePath (path), null); } [TestMethod] @@ -907,7 +885,7 @@ public void DeleteFile_NonTaskLoggingHelperLog_DoesNotThrow () { var path = Path.Combine (tempDir, "directory-instead-of-file-nontasklog"); Directory.CreateDirectory (path); - Files.DeleteFile (path, "not a TaskLoggingHelper"); + Files.DeleteFile (new AbsolutePath (path), "not a TaskLoggingHelper"); } [TestMethod] @@ -917,7 +895,7 @@ public void TryDeleteFile_LogsFailure () Directory.CreateDirectory (path); string message = ""; - Files.TryDeleteFile (path, value => message = value); + Files.TryDeleteFile (new AbsolutePath (path), value => message = value); Assert.Contains (path, message); } diff --git a/tests/Xamarin.Android.Tools.Benchmarks/FilesHashBenchmarks.cs b/tests/Xamarin.Android.Tools.Benchmarks/FilesHashBenchmarks.cs index 5c119144ca4..8c41a2a9cb2 100644 --- a/tests/Xamarin.Android.Tools.Benchmarks/FilesHashBenchmarks.cs +++ b/tests/Xamarin.Android.Tools.Benchmarks/FilesHashBenchmarks.cs @@ -2,6 +2,7 @@ using System.IO; using BenchmarkDotNet.Attributes; using Microsoft.Android.Build.Tasks; +using Microsoft.Build.Framework; namespace Xamarin.Android.Tools.Benchmarks; @@ -48,8 +49,8 @@ public void Cleanup () public string HashStream () => Files.HashStream (_stream); [Benchmark] - public string HashFile () => Files.HashFile (_tempFile1); + public string HashFile () => Files.HashFile (new AbsolutePath (_tempFile1)); [Benchmark] - public bool HasFileChanged () => Files.HasFileChanged (_tempFile1, _tempFile2); + public bool HasFileChanged () => Files.HasFileChanged (new AbsolutePath (_tempFile1), new AbsolutePath (_tempFile2)); }