From 2f0dff0ddfc37afc62e6a9e9b209d7d014fd26b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Mon, 12 Oct 2026 15:44:02 +0300 Subject: [PATCH 1/2] Keep tags attached to files on rename and move Co-Authored-By: Codex Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_016FAtbHHLQSiJiYcw2vnKiq --- .../Utils/FileTags/FileTagsDatabase.Linux.cs | 30 ++++-- .../Utils/FileTags/FileTagsHelper.Linux.cs | 7 ++ .../Operations/LinuxFilesystemOperations.cs | 17 ++- .../FileOperations/FileOperationOptions.cs | 3 + .../FileOperations/FileOperationContext.cs | 3 + .../LinuxFileOperationsService.Move.cs | 10 ++ .../Tags/FileTagsDatabaseTests.cs | 101 ++++++++++++++++++ 7 files changed, 159 insertions(+), 12 deletions(-) diff --git a/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs b/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs index 38d7d38a07af..2d9c881ffcc1 100644 --- a/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs +++ b/src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs @@ -63,18 +63,34 @@ public bool IsXattrStale(string filePath) public void UpdateTag(string oldFilePath, ulong? frn, string? newFilePath) { - if (newFilePath is null || string.Equals(oldFilePath, newFilePath, StringComparison.Ordinal)) + UpdatePath(oldFilePath, newFilePath, recursive: false); + } + + /// Re-keys or removes completed operations, including hidden stale entries. + public void UpdatePath(string oldFilePath, string? newFilePath, bool recursive, bool xattrStale = false) + { + oldFilePath = Path.TrimEndingDirectorySeparator(Path.GetFullPath(oldFilePath)); + newFilePath = newFilePath is null ? null : Path.TrimEndingDirectorySeparator(Path.GetFullPath(newFilePath)); + if (string.Equals(oldFilePath, newFilePath, StringComparison.Ordinal)) return; lock (_gate) { var entries = Load(); - if (!entries.Remove(oldFilePath, out var existing)) - return; - - existing.FilePath = newFilePath; - entries[newFilePath] = existing; - Save(entries); + bool Matches(string path, string root) => path == root || (recursive && path.StartsWith(root + "/", StringComparison.Ordinal)); + var moved = entries.Values.Where(entry => Matches(entry.FilePath, oldFilePath)).ToList(); + var removed = entries.Keys.Where(path => Matches(path, oldFilePath) || (newFilePath is not null && Matches(path, newFilePath))).ToList(); + foreach (var path in removed) + entries.Remove(path); + if (newFilePath is not null) + foreach (var entry in moved) + { + entry.FilePath = newFilePath + entry.FilePath[oldFilePath.Length..]; + entry.XattrStale |= xattrStale; + entries[entry.FilePath] = entry; + } + if (removed.Count > 0 || _dirty) + Save(entries); } } diff --git a/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs b/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs index b25f6caf6056..0ddc5ccb5e95 100644 --- a/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs +++ b/src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs @@ -173,6 +173,13 @@ private static Task EnqueueWrite(Func action, T failureResult) } } + public static void UpdatePath(string source, string? destination, bool recursive, bool xattrStale) + => EnqueueWrite(() => + { + GetDbInstance().UpdatePath(source, destination, recursive, xattrStale); + return true; + }, false).GetAwaiter().GetResult(); + public static void UpdateTagsDb() { // Windows re-resolves moved files through their file reference numbers; Linux has none. diff --git a/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs b/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs index 4a6b531396df..258037db8469 100644 --- a/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs +++ b/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using Files.Platform.Abstractions.FileOperations; +using Files.App.Utils.FileTags; using Files.Platform.Abstractions.Trash; using Microsoft.Extensions.Logging; using System.IO; @@ -110,7 +111,7 @@ private static FileOperationOptions OptionsFor(FileNameConflictResolveOptionType resolver = _ => ValueTask.FromResult(new ConflictResolution(action, true)); } - return new FileOperationOptions { Progress = progress, ConflictResolver = resolver }; + return new FileOperationOptions { Progress = progress, ConflictResolver = resolver, PathChanged = FileTagsHelper.UpdatePath }; } private static IStorageItemWithPath FromResult(string path, FilesystemItemType type) @@ -306,7 +307,7 @@ public async Task CreateShortcutItemsAsync(IList CreateShortcutItemsAsync(IList s.Path == result.Source); - succeeded.Add((src, result.Item?.TrashedPath ?? result.ResultPath)); + var trashedPath = result.Item?.TrashedPath ?? result.ResultPath; + FileTagsHelper.UpdatePath(src.Path, trashedPath, true, true); + succeeded.Add((src, trashedPath)); } else { @@ -389,7 +392,10 @@ public async Task CreateShortcutItemsAsync(IList s.Path == result.Source || s.Path == result.Item?.TrashedPath); if (result.Succeeded && src is not null) + { + FileTagsHelper.UpdatePath(src.Path, null, true, false); succeeded.Add((src, null)); + } else if (!result.Succeeded) failed = true; } @@ -397,7 +403,7 @@ public async Task CreateShortcutItemsAsync(IList CreateShortcutItemsAsync(IList OptionsFor(FileNameConflictResolveOptionType.ReplaceExisting, null), NameCollisionOption.GenerateUniqueName => OptionsFor(FileNameConflictResolveOptionType.GenerateNewName, null), - _ => null, + _ => OptionsFor(FileNameConflictResolveOptionType.None, null), }; var result = await _fileOperations.RenameAsync(source.Path, newName, options, cancellationToken); @@ -494,6 +500,7 @@ public async Task CreateShortcutItemsAsync(IList public Func>? ConflictResolver { get; init; } + /// Called after each completed move or deletion (null destination). Recursive denotes an entire renamed/deleted tree; xattrStale denotes a copy-based move. + public Action? PathChanged { get; init; } + /// Copies the content of symbolic links instead of recreating the links. Defaults to . public bool FollowSymlinks { get; init; } } diff --git a/src/Files.Platform.Linux/FileOperations/FileOperationContext.cs b/src/Files.Platform.Linux/FileOperations/FileOperationContext.cs index 6cd65934b55a..24f48adfb8b0 100644 --- a/src/Files.Platform.Linux/FileOperations/FileOperationContext.cs +++ b/src/Files.Platform.Linux/FileOperations/FileOperationContext.cs @@ -43,6 +43,9 @@ public FileOperationContext(FileOperationOptions? options, CancellationToken can /// Canonical paths of folders currently being walked through symbolic links, to detect cycles. public HashSet ActiveDirectories { get; } = new(StringComparer.Ordinal); + public void PathChanged(string source, string? destination, bool recursive = false, bool xattrStale = false) + => _options.PathChanged?.Invoke(source, destination, recursive, xattrStale); + public void AddTotals(long items, long bytes) { _itemsTotal += items; diff --git a/src/Files.Platform.Linux/FileOperations/LinuxFileOperationsService.Move.cs b/src/Files.Platform.Linux/FileOperations/LinuxFileOperationsService.Move.cs index 074334c27867..2b6879ea0e8b 100644 --- a/src/Files.Platform.Linux/FileOperations/LinuxFileOperationsService.Move.cs +++ b/src/Files.Platform.Linux/FileOperations/LinuxFileOperationsService.Move.cs @@ -54,6 +54,7 @@ private async Task MoveEntryAsync(string source, string destination, Di { if (PosixNative.TryRenameAt(sourceParent.Descriptor, name, destinationParent.Descriptor, destinationName, resolved.Replace, out var errno, context.Hooks)) { + context.PathChanged(source, destination, stat.IsDirectory); context.AddBytes(stat.IsRegularFile ? (long)stat.Size : 0, source); context.ItemDone(source); return Outcome.Success(destination); @@ -78,6 +79,7 @@ private async Task MoveEntryAsync(string source, string destination, Di context.CancellationToken.ThrowIfCancellationRequested(); VerifyMoveSource(sourceParent, name, stat, source); PosixNative.UnlinkAt(sourceParent.Descriptor, name, 0, source); + context.PathChanged(source, destination, xattrStale: true); } return copy; } @@ -126,6 +128,7 @@ private async Task MoveDirectoryContentsAsync(string source, string des try { PosixNative.UnlinkAt(sourceParent.Descriptor, Path.GetFileName(source), PosixNative.AtRemoveDir, source); + context.PathChanged(source, destination, xattrStale: true); } catch (IOException ex) when (ex.HResult == 39 && sourceDirectory.ListNames().Count > 0) { @@ -170,7 +173,10 @@ private static Outcome DeleteChild(DirectoryHandle parent, string name, string f result = result.Combine(DeleteChild(directory, childName, Path.Combine(fullPath, childName), context), null); if (result.Status == FileOperationStatus.Succeeded) + { PosixNative.UnlinkAt(parent.Descriptor, name, PosixNative.AtRemoveDir, fullPath); + context.PathChanged(fullPath, null, recursive: true); + } context.ItemDone(fullPath); return result; @@ -183,6 +189,7 @@ private static Outcome DeleteChild(DirectoryHandle parent, string name, string f } PosixNative.UnlinkAt(parent.Descriptor, name, 0, fullPath); + context.PathChanged(fullPath, null); context.AddBytes(stat.IsRegularFile ? (long)stat.Size : 0, fullPath); context.ItemDone(fullPath); return Outcome.Success(null); @@ -221,7 +228,9 @@ private async Task RenameCoreAsync(string path, string newName, FileOpe { var temporary = Path.GetFileName(TemporaryPathNextTo(destination)); PosixNative.RenameAt(parent.Descriptor, sourceName, parent.Descriptor, temporary, false, destination, context.Hooks); + context.PathChanged(source, Path.Combine(parentPath, temporary), stat.IsDirectory); PosixNative.RenameAt(parent.Descriptor, temporary, parent.Descriptor, newName, false, destination, context.Hooks); + context.PathChanged(Path.Combine(parentPath, temporary), destination, stat.IsDirectory); return Outcome.Success(destination); } @@ -234,6 +243,7 @@ private async Task RenameCoreAsync(string path, string newName, FileOpe context.Hooks?.BeforeMoveEntry?.Invoke(source, resolved.Destination); context.CancellationToken.ThrowIfCancellationRequested(); PosixNative.RenameAt(parent.Descriptor, sourceName, parent.Descriptor, Path.GetFileName(resolved.Destination), resolved.Replace, resolved.Destination, context.Hooks); + context.PathChanged(source, resolved.Destination, stat.IsDirectory); return Outcome.Success(resolved.Destination); } } diff --git a/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs b/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs index 13b6b2f0cfa5..737485dcf830 100644 --- a/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs +++ b/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs @@ -11,6 +11,107 @@ namespace Files.Platform.Tests.Tags [TestClass] public sealed class FileTagsDatabaseTests { + [TestMethod] + public async System.Threading.Tasks.Task Move_PartialMergeOnlyRekeysCompletedChildren() + { + var root = Path.Combine(Path.GetTempPath(), "files-tags-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var db = new FileTagsDatabase(Path.Combine(root, "tags.json")); + var source = Path.Combine(root, "source", "folder"); + var destination = Path.Combine(root, "destination"); + var target = Path.Combine(destination, "folder"); + Directory.CreateDirectory(source); + Directory.CreateDirectory(target); + foreach (var name in new[] { "move", "skip" }) + { + File.WriteAllText(Path.Combine(source, name), name); + db.SetTags(Path.Combine(source, name), null, [name], true); + } + File.WriteAllText(Path.Combine(target, "skip"), "existing"); + db.SetTags(source, null, ["source-root"]); + db.SetTags(target, null, ["destination-root"]); + var options = new Files.Platform.Abstractions.FileOperations.FileOperationOptions + { + PathChanged = db.UpdatePath, + ConflictResolver = conflict => System.Threading.Tasks.ValueTask.FromResult( + new Files.Platform.Abstractions.FileOperations.ConflictResolution( + Path.GetFileName(conflict.Source) == "skip" + ? Files.Platform.Abstractions.FileOperations.ConflictAction.Skip + : Files.Platform.Abstractions.FileOperations.ConflictAction.Overwrite)) + }; + var service = new Files.Platform.Linux.FileOperations.LinuxFileOperationsService(); + await service.MoveAsync([source], destination, options); + Assert.IsTrue(File.Exists(Path.Combine(source, "skip"))); + Assert.IsFalse(db.IsXattrStale(Path.Combine(source, "move"))); + Assert.IsTrue(db.IsXattrStale(Path.Combine(target, "move"))); + Assert.IsTrue(db.IsXattrStale(Path.Combine(source, "skip"))); + CollectionAssert.AreEqual(new[] { "source-root" }, db.GetTags(source, null)); + CollectionAssert.AreEqual(new[] { "destination-root" }, db.GetTags(target, null)); + } + finally { Directory.Delete(root, true); } + } + + [TestMethod] + public async System.Threading.Tasks.Task Operations_RekeyTreesAndRemoveDeletedTags() + { + var root = Path.Combine(Path.GetTempPath(), "files-tags-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var databasePath = Path.Combine(root, "tags.json"); + var db = new FileTagsDatabase(databasePath); + var folder = Path.Combine(root, "folder"); + Directory.CreateDirectory(folder); + File.WriteAllText(Path.Combine(folder, "file"), "content"); + db.SetTags(folder, null, ["folder-tag"]); + db.SetTags(Path.Combine(folder, "file"), null, [], true); + db.SetTags(folder + "-neighbor", null, ["neighbor"]); + var options = new Files.Platform.Abstractions.FileOperations.FileOperationOptions { PathChanged = db.UpdatePath }; + var service = new Files.Platform.Linux.FileOperations.LinuxFileOperationsService((_, _) => false); + var rename = await service.RenameAsync(folder, "renamed", options); + Assert.IsTrue(rename.Succeeded); + var renamed = Path.Combine(root, "renamed"); + Assert.IsFalse(db.IsXattrStale(Path.Combine(folder, "file"))); + Assert.IsTrue(new FileTagsDatabase(databasePath).IsXattrStale(Path.Combine(renamed, "file"))); + var destination = Path.Combine(root, "destination"); + Directory.CreateDirectory(destination); + var moved = await service.MoveAsync([renamed], destination, options); + Assert.IsTrue(moved[0].Succeeded); + var target = Path.Combine(destination, "renamed"); + CollectionAssert.AreEqual(new[] { "folder-tag" }, db.GetTags(target, null)); + Assert.IsTrue(db.IsXattrStale(target)); + Assert.IsTrue(db.IsXattrStale(Path.Combine(target, "file"))); + var deleted = await service.DeleteAsync([target], options); + Assert.IsTrue(deleted[0].Succeeded); + var reloaded = new FileTagsDatabase(databasePath); + Assert.IsFalse(reloaded.IsXattrStale(Path.Combine(target, "file"))); + Assert.AreEqual(0, reloaded.GetTags(target, null).Length); + CollectionAssert.AreEqual(new[] { "neighbor" }, reloaded.GetTags(folder + "-neighbor", null)); + } + finally { Directory.Delete(root, true); } + } + + [TestMethod] + public void UpdatePath_UntaggedReplacementClearsDestinationAndDeletionClearsStaleEntries() + { + var root = Path.Combine(Path.GetTempPath(), "files-tags-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var path = Path.Combine(root, "tags.json"); + var db = new FileTagsDatabase(path); + db.SetTags("/destination", null, ["old"], true); + db.UpdatePath("/source", "/destination", false); + Assert.IsFalse(new FileTagsDatabase(path).IsXattrStale("/destination")); + db.SetTags("/folder/empty", null, [], true); + db.UpdatePath("/folder", null, true); + Assert.IsFalse(new FileTagsDatabase(path).IsXattrStale("/folder/empty")); + } + finally { Directory.Delete(root, true); } + } + [TestMethod] public void Save_SkipsEmptyAndEqualTagsAndKeepsInputAndOutputIsolated() { From 71881e14e42d9c515f48c84b992884646d1441e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Mon, 12 Oct 2026 18:27:51 +0300 Subject: [PATCH 2/2] Address review findings Co-Authored-By: Codex Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_016FAtbHHLQSiJiYcw2vnKiq --- .../Operations/LinuxFilesystemOperations.cs | 4 +- .../Trash/TrashOperationResult.cs | 3 ++ .../LinuxFileOperationsService.Move.cs | 2 +- .../Trash/LinuxTrashService.cs | 2 +- .../Tags/FileTagsDatabaseTests.cs | 45 ++++++++++++++++++ .../Tags/FileTagsHelperTests.cs | 46 +++++++++++++++++++ .../Trash/FdRestoreCompatibilityTests.cs | 2 + 7 files changed, 100 insertions(+), 4 deletions(-) diff --git a/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs b/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs index 258037db8469..d2992437e4f6 100644 --- a/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs +++ b/src/Files.App/Utils/Storage/Operations/LinuxFilesystemOperations.cs @@ -374,7 +374,7 @@ public async Task CreateShortcutItemsAsync(IList s.Path == result.Source); var trashedPath = result.Item?.TrashedPath ?? result.ResultPath; - FileTagsHelper.UpdatePath(src.Path, trashedPath, true, true); + FileTagsHelper.UpdatePath(src.Path, trashedPath, true, result.XattrStale); succeeded.Add((src, trashedPath)); } else @@ -500,7 +500,7 @@ public async Task CreateShortcutItemsAsync(IListWhether copying the item lost its extended attributes. + public bool XattrStale { get; init; } + /// /// Creates a successful result. /// diff --git a/src/Files.Platform.Linux/FileOperations/LinuxFileOperationsService.Move.cs b/src/Files.Platform.Linux/FileOperations/LinuxFileOperationsService.Move.cs index 2b6879ea0e8b..7300d7f10237 100644 --- a/src/Files.Platform.Linux/FileOperations/LinuxFileOperationsService.Move.cs +++ b/src/Files.Platform.Linux/FileOperations/LinuxFileOperationsService.Move.cs @@ -128,7 +128,7 @@ private async Task MoveDirectoryContentsAsync(string source, string des try { PosixNative.UnlinkAt(sourceParent.Descriptor, Path.GetFileName(source), PosixNative.AtRemoveDir, source); - context.PathChanged(source, destination, xattrStale: true); + context.PathChanged(source, created ? destination : null, xattrStale: created); } catch (IOException ex) when (ex.HResult == 39 && sourceDirectory.ListNames().Count > 0) { diff --git a/src/Files.Platform.Linux/Trash/LinuxTrashService.cs b/src/Files.Platform.Linux/Trash/LinuxTrashService.cs index 2e6b5e3eee13..25d3308d1cd8 100644 --- a/src/Files.Platform.Linux/Trash/LinuxTrashService.cs +++ b/src/Files.Platform.Linux/Trash/LinuxTrashService.cs @@ -536,7 +536,7 @@ private async Task RestoreOneAsync(TrashItem item, TrashRe new DirectorySizesCache(location.Root, trashRoot).Remove([name]); // Successful restores may carry a cleanup warning in ErrorMessage; ResultPath remains usable. - return new TrashOperationResult(item.TrashedPath, true, warning, destination); + return new TrashOperationResult(item.TrashedPath, true, warning, destination) { XattrStale = copiedSource is not null }; } private TrashOperationResult DeleteOne(TrashItem item) diff --git a/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs b/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs index 737485dcf830..7f819a8870e7 100644 --- a/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs +++ b/tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs @@ -53,6 +53,51 @@ public async System.Threading.Tasks.Task Move_PartialMergeOnlyRekeysCompletedChi finally { Directory.Delete(root, true); } } + [TestMethod] + [DataRow(false, false)] + [DataRow(false, true)] + [DataRow(true, false)] + [DataRow(true, true)] + public async System.Threading.Tasks.Task Move_CompleteMergePreservesDestinationRootTags(bool crossDevice, bool taggedSource) + { + var root = Path.Combine(Path.GetTempPath(), "files-tags-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var databasePath = Path.Combine(root, "tags.json"); + var db = new FileTagsDatabase(databasePath); + var source = Path.Combine(root, "source", "folder"); + var destination = Path.Combine(root, "destination"); + var target = Path.Combine(destination, "folder"); + Directory.CreateDirectory(source); + Directory.CreateDirectory(target); + File.WriteAllText(Path.Combine(source, "child"), "data"); + db.SetTags(Path.Combine(source, "child"), null, ["child"]); + if (taggedSource) + db.SetTags(source, null, ["source-root"], true); + db.SetTags(target, null, ["destination-root"], true); + var options = new Files.Platform.Abstractions.FileOperations.FileOperationOptions + { + PathChanged = db.UpdatePath, + ConflictResolver = _ => System.Threading.Tasks.ValueTask.FromResult( + new Files.Platform.Abstractions.FileOperations.ConflictResolution( + Files.Platform.Abstractions.FileOperations.ConflictAction.Overwrite)) + }; + var service = new Files.Platform.Linux.FileOperations.LinuxFileOperationsService((_, _) => !crossDevice); + var results = await service.MoveAsync([source], destination, options); + Assert.IsTrue(results[0].Succeeded); + Assert.IsFalse(Directory.Exists(source)); + var reloaded = new FileTagsDatabase(databasePath); + CollectionAssert.AreEqual(new[] { "destination-root" }, reloaded.GetTags(target, null)); + Assert.IsTrue(reloaded.IsXattrStale(target)); + Assert.AreEqual(0, reloaded.GetTags(source, null).Length); + Assert.IsFalse(reloaded.IsXattrStale(source)); + CollectionAssert.AreEqual(new[] { "child" }, reloaded.GetTags(Path.Combine(target, "child"), null)); + Assert.AreEqual(crossDevice, reloaded.IsXattrStale(Path.Combine(target, "child"))); + } + finally { Directory.Delete(root, true); } + } + [TestMethod] public async System.Threading.Tasks.Task Operations_RekeyTreesAndRemoveDeletedTags() { diff --git a/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs b/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs index 4767a7eaad7a..eafcf7a7dbb8 100644 --- a/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs +++ b/tests/Files.Platform.Tests/Tags/FileTagsHelperTests.cs @@ -381,6 +381,52 @@ public async Task ReadOnlyFile_StaleXattrDoesNotOverwriteDatabaseAfterRestart() } } + [TestMethod] + [DataRow(false, false)] + [DataRow(false, true)] + [DataRow(true, false)] + [DataRow(true, true)] + public async Task TrashAndRestore_PreserveRenameAuthorityAndMarkCopies(bool copyRestore, bool alreadyStale) + { + var store = new XattrFileTagsStore(); + using var fixture = new TagFixture(store); + var root = Path.GetDirectoryName(fixture.DatabasePath)!; + var folder = Path.Combine(root, "folder"); + Directory.CreateDirectory(folder); + var path = Path.Combine(folder, "child"); + File.WriteAllText(path, "data"); + if (!store.WriteTags(path, ["B"])) + Assert.Inconclusive("The test file system has no user xattr support."); + FileTagsHelper.GetDbInstance().SetTags(path, null, ["a"], alreadyStale); + var service = new Files.Platform.Linux.Trash.LinuxTrashService(new() + { + DataHome = Path.Combine(root, "data"), + FileOperationsHooks = new Files.Platform.Linux.FileOperations.LinuxFileOperationsHooks + { + RenameError = (source, _, _) => copyRestore && source == "folder" ? 18 : null + } + }); + try + { + var trashed = (await service.TrashAsync([folder]))[0]; + Assert.IsTrue(trashed.Succeeded, trashed.ErrorMessage); + Assert.IsFalse(trashed.XattrStale); + FileTagsHelper.UpdatePath(folder, trashed.ResultPath, true, trashed.XattrStale); + FileTagsHelper.Database = new FileTagsDatabase(fixture.DatabasePath); + var trashChild = Path.Combine(trashed.ResultPath!, "child"); + Assert.AreEqual(alreadyStale, FileTagsHelper.GetDbInstance().IsXattrStale(trashChild)); + CollectionAssert.AreEqual(new[] { alreadyStale ? "a" : "b" }, FileTagsHelper.ReadFileTag(trashChild)); + var restored = (await service.RestoreAsync([trashed.Item!]))[0]; + Assert.IsTrue(restored.Succeeded, restored.ErrorMessage); + Assert.AreEqual(copyRestore, restored.XattrStale); + FileTagsHelper.UpdatePath(trashed.ResultPath!, restored.ResultPath, true, restored.XattrStale); + FileTagsHelper.Database = new FileTagsDatabase(fixture.DatabasePath); + Assert.AreEqual(copyRestore || alreadyStale, FileTagsHelper.GetDbInstance().IsXattrStale(path)); + CollectionAssert.AreEqual(new[] { copyRestore || alreadyStale ? "a" : "b" }, FileTagsHelper.ReadFileTag(path)); + } + finally { service.Watcher.Dispose(); } + } + private sealed class TagFixture : IDisposable { private readonly string root = Path.Combine(Path.GetTempPath(), "files-tags-queue-" + Guid.NewGuid().ToString("N")); diff --git a/tests/Files.Platform.Tests/Trash/FdRestoreCompatibilityTests.cs b/tests/Files.Platform.Tests/Trash/FdRestoreCompatibilityTests.cs index a7cf2cd0487f..1aa3f44cdbd1 100644 --- a/tests/Files.Platform.Tests/Trash/FdRestoreCompatibilityTests.cs +++ b/tests/Files.Platform.Tests/Trash/FdRestoreCompatibilityTests.cs @@ -38,6 +38,7 @@ public async Task Restore_Rename2Unavailable(int errno, string kind) var result = Single(await _service.RestoreAsync([item])); Assert.IsTrue(result.Succeeded, result.ErrorMessage); + Assert.IsFalse(result.XattrStale); if (kind == "directory") Assert.AreEqual("data", File.ReadAllText(Path.Combine(original, "child"))); else if (kind == "link") @@ -87,6 +88,7 @@ public async Task Restore_CrossDevice_UsesPinnedParentsAndCleansTrash(string kin var result = Single(await _service.RestoreAsync([item])); Assert.IsTrue(result.Succeeded, result.ErrorMessage); + Assert.IsTrue(result.XattrStale); var restored = Path.Combine(parent + ".saved", "entry"); if (kind == "directory") {