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
4 changes: 4 additions & 0 deletions src/Files.App/Data/Items/ListedItem.FileTags.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ public void SetLoadedFileTags(string[] tags, long? expectedRevision = null)
#if WINDOWS
FileTags = tags;
#else
// A deferred snapshot may predate an edit made through another item for this path.
if (FileTagsHelper.TryReadDatabaseFallback(this.GetRequiredPath(), out var fallbackTags))
tags = fallbackTags;

if (fileTags is not null && fileTags.SequenceEqual(tags, StringComparer.Ordinal))
return;

Expand Down
37 changes: 26 additions & 11 deletions src/Files.App/Utils/FileTags/FileTagsDatabase.Linux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,23 +30,38 @@ public FileTagsDatabase() { }
private string DatabasePath
=> _databasePath ?? Path.Combine(Ioc.Default.GetRequiredService<Files.Platform.Abstractions.IAppDataPaths>().DataDirectory, "filetags.json");

public void SetTags(string filePath, ulong? frn, string[] tags)
public void SetTags(string filePath, ulong? frn, string[] tags) => SetTags(filePath, frn, tags, xattrStale: false);

/// <summary>
/// Stores the tags of a file. <paramref name="xattrStale"/> persists that the file's extended attribute could not be updated,
/// so the entry (even an empty one) stays authoritative over the attribute after a restart.
/// </summary>
public void SetTags(string filePath, ulong? frn, string[] tags, bool xattrStale)
{
lock (_gate)
{
var entries = Load();
var changed = tags.Length == 0
var keep = tags.Length > 0 || xattrStale;
var changed = !keep
? entries.Remove(filePath)
: !entries.TryGetValue(filePath, out var current) || !current.Tags.SequenceEqual(tags, StringComparer.Ordinal);
: !entries.TryGetValue(filePath, out var current)
|| current.XattrStale != xattrStale
|| !current.Tags.SequenceEqual(tags, StringComparer.Ordinal);
if (!changed && !_dirty)
return;
if (tags.Length > 0 && changed)
entries[filePath] = new TaggedFile { FilePath = filePath, Tags = (string[])tags.Clone() };
if (keep && changed)
entries[filePath] = new TaggedFile { FilePath = filePath, Tags = (string[])tags.Clone(), XattrStale = xattrStale };

Save(entries);
}
}

public bool IsXattrStale(string filePath)
{
lock (_gate)
return Load().TryGetValue(filePath, out var tagged) && tagged.XattrStale;
}

public void UpdateTag(string oldFilePath, ulong? frn, string? newFilePath)
{
if (newFilePath is null || string.Equals(oldFilePath, newFilePath, StringComparison.Ordinal))
Expand Down Expand Up @@ -81,14 +96,14 @@ public string[] GetTags(string? filePath, ulong? frn)
public IEnumerable<TaggedFile> GetAll()
{
lock (_gate)
return Load().Values.ToList();
return Load().Values.Where(x => x.Tags.Length > 0).ToList();
}

public IEnumerable<TaggedFile> GetAllUnderPath(string folderPath)
{
var prefix = folderPath.TrimEnd('/') + "/";
lock (_gate)
return Load().Values.Where(x => x.FilePath.StartsWith(prefix, StringComparison.Ordinal)).ToList();
return Load().Values.Where(x => x.Tags.Length > 0 && x.FilePath.StartsWith(prefix, StringComparison.Ordinal)).ToList();
}

public void Import(string json)
Expand All @@ -100,14 +115,14 @@ public void Import(string json)
var entries = new Dictionary<string, TaggedFile>(StringComparer.Ordinal);
foreach (var tag in tags ?? [])
{
if (!string.IsNullOrEmpty(tag.FilePath) && tag.Tags.Length > 0)
if (!string.IsNullOrEmpty(tag.FilePath) && (tag.Tags.Length > 0 || tag.XattrStale))
entries[tag.FilePath] = tag;
}

var current = Load();
if (!_dirty && current.Count == entries.Count && entries.All(pair =>
current.TryGetValue(pair.Key, out var existing) && existing.Frn == pair.Value.Frn &&
existing.Tags.SequenceEqual(pair.Value.Tags, StringComparer.Ordinal)))
existing.XattrStale == pair.Value.XattrStale && existing.Tags.SequenceEqual(pair.Value.Tags, StringComparer.Ordinal)))
return;

Save(entries);
Expand All @@ -117,7 +132,7 @@ public void Import(string json)
public string Export()
{
lock (_gate)
return JsonSerializer.Serialize(Load().Values.ToList(), AppJsonSerializerContext.Default.ListTaggedFile);
return JsonSerializer.Serialize(Load().Values.Where(x => x.Tags.Length > 0 || x.XattrStale).ToList(), AppJsonSerializerContext.Default.ListTaggedFile);
}

private Dictionary<string, TaggedFile> Load()
Expand All @@ -134,7 +149,7 @@ private Dictionary<string, TaggedFile> Load()
var list = JsonSerializer.Deserialize(File.ReadAllText(path), AppJsonSerializerContext.Default.TaggedFileArray);
foreach (var tag in list ?? [])
{
if (!string.IsNullOrEmpty(tag.FilePath) && tag.Tags.Length > 0)
if (!string.IsNullOrEmpty(tag.FilePath) && (tag.Tags.Length > 0 || tag.XattrStale))
entries[tag.FilePath] = tag;
}
}
Expand Down
37 changes: 34 additions & 3 deletions src/Files.App/Utils/FileTags/FileTagsHelper.Linux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,30 @@ namespace Files.App.Utils.FileTags
// Files stores tag UIDs internally, so names are translated through the tag list; xattr tags with an unknown name are ignored.
public static partial class FileTagsHelper
{
internal static bool TryReadDatabaseFallback(string filePath, out string[] tags)
{
// Persisted marker: survives restarts, so a stale readable attribute never overwrites newer database tags.
if (GetDbInstance().IsXattrStale(filePath))
{
tags = GetDbInstance().GetTags(filePath, null);
return true;
}
tags = [];
return false;
}

public static string[] ReadFileTag(string filePath)
{
if (TryReadDatabaseFallback(filePath, out var tags))
return tags;

var store = Ioc.Default.GetService<IFileTagsStore>();
var names = store?.ReadTags(filePath);

// A write may have failed while the attribute was being read.
if (TryReadDatabaseFallback(filePath, out tags))
return tags;

if (names is { Count: > 0 })
{
var settings = Ioc.Default.GetRequiredService<IFileTagsSettingsService>();
Expand All @@ -43,7 +62,8 @@ public static Task<string[]> ReadAndUpdateFileTagsAsync(string filePath)
return EnqueueWrite(() =>
{
var tags = ReadFileTag(filePath);
GetDbInstance().SetTags(filePath, null, tags);
if (!GetDbInstance().IsXattrStale(filePath))
GetDbInstance().SetTags(filePath, null, tags);
return tags;
}, Array.Empty<string>());
}
Expand Down Expand Up @@ -108,8 +128,19 @@ private static bool WriteTags(string filePath, string[] tags, string[] names, IF
{
try
{
GetDbInstance().SetTags(filePath, null, tags);
if (store is not null && !store.WriteTags(filePath, names))
var written = false;
try
{
written = store is not null && store.WriteTags(filePath, names);
}
catch (Exception ex) when (ex is not (OutOfMemoryException or StackOverflowException or AccessViolationException))
{
App.Logger?.LogDebug(ex, "Could not write extended attributes.");
}

// Keep the DB authoritative (persistently) when a readable attribute could not be updated or removed.
GetDbInstance().SetTags(filePath, null, tags, xattrStale: !written);
if (!written)
App.Logger?.LogDebug("Extended attributes are not available for '{FilePath}'; tags are kept in the database only.", LogPathHelper.RedactPath(filePath));
return true;
}
Expand Down
2 changes: 2 additions & 0 deletions src/Files.App/Utils/FileTags/TaggedFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@ public sealed class TaggedFile
public ulong? Frn { get; set; }
public string FilePath { get; set; } = string.Empty;
public string[] Tags { get; set; } = [];
/// <summary>Linux: the database is newer than the file's extended attribute, which could not be updated.</summary>
public bool XattrStale { get; set; }
}
}
51 changes: 51 additions & 0 deletions tests/Files.Platform.Tests/Tags/FileTagsDatabaseTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,57 @@ public void Save_SkipsEmptyAndEqualTagsAndKeepsInputAndOutputIsolated()
finally { Directory.Delete(root, true); }
}

[TestMethod]
public void ExportImport_EmptyStaleEntry_RemainsAuthoritativeAndHidden()
{
var root = Path.Combine(Path.GetTempPath(), "files-tags-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
try
{
var source = new FileTagsDatabase(Path.Combine(root, "source.json"));
source.SetTags("/folder/file", null, ["a"]);
source.SetTags("/folder/file", null, [], xattrStale: true);
Assert.AreEqual(0, source.GetAll().Count());

var path = Path.Combine(root, "imported.json");
var imported = new FileTagsDatabase(path);
imported.Import(source.Export());
foreach (var db in new[] { imported, new FileTagsDatabase(path) })
{
Assert.IsTrue(db.IsXattrStale("/folder/file"));
Assert.AreEqual(0, db.GetTags("/folder/file", null).Length);
Assert.AreEqual(0, db.GetAll().Count());
Assert.AreEqual(0, db.GetAllUnderPath("/folder").Count());
}
}
finally { Directory.Delete(root, true); }
}

[TestMethod]
[DataRow(true)]
[DataRow(false)]
public void Import_IdenticalTagsWithDifferentXattrStale_PersistsFlag(bool xattrStale)
{
var root = Path.Combine(Path.GetTempPath(), "files-tags-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(root);
try
{
var source = new FileTagsDatabase(Path.Combine(root, "source.json"));
source.SetTags("/file", null, ["a"], xattrStale);
var path = Path.Combine(root, "imported.json");
var imported = new FileTagsDatabase(path);
imported.SetTags("/file", null, ["a"], !xattrStale);

imported.Import(source.Export());
foreach (var db in new[] { imported, new FileTagsDatabase(path) })
{
Assert.AreEqual(xattrStale, db.IsXattrStale("/file"));
CollectionAssert.AreEqual(new[] { "a" }, db.GetTags("/file", null));
}
}
finally { Directory.Delete(root, true); }
}

[TestMethod]
public void Save_RetriesFailedPersistenceEvenWhenTagsAreEqual()
{
Expand Down
Loading
Loading