Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/// <summary>Re-keys or removes completed operations, including hidden stale entries.</summary>
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);
}
}

Expand Down
7 changes: 7 additions & 0 deletions src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,13 @@ private static Task<T> EnqueueWrite<T>(Func<T> 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -306,7 +307,7 @@ public async Task<IStorageHistory> CreateShortcutItemsAsync(IList<IStorageItemWi
if (batch == renamed)
{
// LINUX-TODO(fileops): a pre-existing item with the source name in the destination can clash with this staging step
var rename = await _fileOperations.RenameAsync(resultPath, Path.GetFileName(entry.Dest.TrimEnd('/')), cancellationToken: cancellationToken);
var rename = await _fileOperations.RenameAsync(resultPath, Path.GetFileName(entry.Dest.TrimEnd('/')), options: OptionsFor(FileNameConflictResolveOptionType.None, null), cancellationToken: cancellationToken);
if (rename.Succeeded && rename.ResultPath is not null)
resultPath = rename.ResultPath;
else
Expand Down Expand Up @@ -372,7 +373,9 @@ public async Task<IStorageHistory> CreateShortcutItemsAsync(IList<IStorageItemWi
if (result.Succeeded)
{
var src = distinct.First(s => 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, result.XattrStale);
succeeded.Add((src, trashedPath));
}
else
{
Expand All @@ -389,15 +392,18 @@ public async Task<IStorageHistory> CreateShortcutItemsAsync(IList<IStorageItemWi
{
var src = distinct.FirstOrDefault(s => 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;
}
}
else
{
var adapter = new ProgressAdapter(fsProgress, 0, 0);
var results = await _fileOperations.DeleteAsync(paths, new FileOperationOptions { Progress = adapter }, cancellationToken);
var results = await _fileOperations.DeleteAsync(paths, new FileOperationOptions { Progress = adapter, PathChanged = FileTagsHelper.UpdatePath }, cancellationToken);
foreach (var result in results)
{
if (result.Succeeded)
Expand Down Expand Up @@ -449,7 +455,7 @@ public async Task<IStorageHistory> CreateShortcutItemsAsync(IList<IStorageItemWi
{
NameCollisionOption.ReplaceExisting => 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);
Expand Down Expand Up @@ -494,6 +500,7 @@ public async Task<IStorageHistory> CreateShortcutItemsAsync(IList<IStorageItemWi
if (src is null)
continue;

FileTagsHelper.UpdatePath(src.Path, result.ResultPath ?? result.Item?.OriginalPath, true, result.XattrStale);
movedSources.Add(src);
movedDestinations.Add(FromResult(result.ResultPath ?? result.Item?.OriginalPath ?? string.Empty, src.ItemType));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ public sealed record FileOperationOptions
/// </summary>
public Func<FileConflict, ValueTask<ConflictResolution>>? ConflictResolver { get; init; }

/// <summary>Called after each completed move or deletion (null destination). Recursive denotes an entire renamed/deleted tree; xattrStale denotes a copy-based move.</summary>
public Action<string, string?, bool, bool>? PathChanged { get; init; }

/// <summary>Copies the content of symbolic links instead of recreating the links. Defaults to <see langword="false"/>.</summary>
public bool FollowSymlinks { get; init; }
}
Expand Down
3 changes: 3 additions & 0 deletions src/Files.Platform.Abstractions/Trash/TrashOperationResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ public sealed record TrashOperationResult(
string? ResultPath = null,
TrashItem? Item = null)
{
/// <summary>Whether copying the item lost its extended attributes.</summary>
public bool XattrStale { get; init; }

/// <summary>
/// Creates a successful result.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ public FileOperationContext(FileOperationOptions? options, CancellationToken can
/// <summary>Canonical paths of folders currently being walked through symbolic links, to detect cycles.</summary>
public HashSet<string> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ private async Task<Outcome> 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);
Expand All @@ -78,6 +79,7 @@ private async Task<Outcome> 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;
}
Expand Down Expand Up @@ -126,6 +128,7 @@ private async Task<Outcome> MoveDirectoryContentsAsync(string source, string des
try
{
PosixNative.UnlinkAt(sourceParent.Descriptor, Path.GetFileName(source), PosixNative.AtRemoveDir, source);
context.PathChanged(source, created ? destination : null, xattrStale: created);
}
catch (IOException ex) when (ex.HResult == 39 && sourceDirectory.ListNames().Count > 0)
{
Expand Down Expand Up @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -221,7 +228,9 @@ private async Task<Outcome> 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);
}

Expand All @@ -234,6 +243,7 @@ private async Task<Outcome> 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);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Files.Platform.Linux/Trash/LinuxTrashService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ private async Task<TrashOperationResult> 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)
Expand Down
146 changes: 146 additions & 0 deletions tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,152 @@ 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]
[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()
{
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()
{
Expand Down
Loading
Loading