fix(archive): move sequences nested in a renamed folder with it

A mass rename or move of a sequence whose folder holds other sequences moved
their files without updating their index rows, and a target inside another
sequence's folder could nest one sequence in another. The plan now carries the
nested sequences (listed in the dry run, moved with the folder that holds them,
inner folders leaving first) and refuses a target inside a sequence folder with
a localized NestedRenameException (CD-4). The Archive screen counts only the
selected sequences in its summary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 09:56:54 +00:00
1 parent b0e3baa47c
commit 5d01d6ab34
7 files changed
+134 -12

No files matched your search

+1
View File
@@ -81,6 +81,7 @@
<data name="Archive.Error.CopyMismatch" xml:space="preserve"><value>The copy of {0} does not match the original.</value><comment>long: error sentence</comment></data>
<data name="Archive.Error.DuplicateLost" xml:space="preserve"><value>{0} could not be added to the sequence.</value><comment>long: error sentence</comment></data>
<data name="Archive.Error.InLibrary" xml:space="preserve"><value>{0} is already in the library.</value><comment>long: error sentence</comment></data>
<data name="Archive.Error.NestedTarget" xml:space="preserve"><value>{0} would be inside the sequence folder {1}.</value><comment>long: error sentence</comment></data>
<data name="Archive.Error.NewerFormat" xml:space="preserve"><value>{0} was written by a newer Titano (format {1}).</value><comment>long: error sentence</comment></data>
<data name="Archive.Error.Offline" xml:space="preserve"><value>The archive {0} is offline.</value><comment>long: error sentence</comment></data>
<data name="Archive.Error.ReadOnly" xml:space="preserve"><value>The archive {0} is read-only.</value><comment>long: error sentence</comment></data>
+1
View File
@@ -76,6 +76,7 @@
<data name="Archive.Error.CopyMismatch" xml:space="preserve"><value>La copia di {0} non corrisponde all'originale.</value></data>
<data name="Archive.Error.DuplicateLost" xml:space="preserve"><value>Impossibile aggiungere {0} alla sequenza.</value></data>
<data name="Archive.Error.InLibrary" xml:space="preserve"><value>{0} è già nella libreria.</value></data>
<data name="Archive.Error.NestedTarget" xml:space="preserve"><value>{0} finirebbe dentro la cartella della sequenza {1}.</value></data>
<data name="Archive.Error.NewerFormat" xml:space="preserve"><value>{0} è stato scritto da un Titano più recente (formato {1}).</value></data>
<data name="Archive.Error.Offline" xml:space="preserve"><value>L'archivio {0} non è raggiungibile.</value></data>
<data name="Archive.Error.ReadOnly" xml:space="preserve"><value>L'archivio {0} è di sola lettura.</value></data>
+2 -1
View File
@@ -17,7 +17,8 @@ public static class ArchiveFailures
ArchiveOfflineException offline => Loc.L(offline.Availability == ArchiveAvailability.ReadOnly ? "Archive.Error.ReadOnly" : "Archive.Error.Offline",
Formatting.LeftToRight(offline.Root)),
// Already one localized sentence each.
LeaseUnavailableException or NewerFormatException or StaleRenamePlanException or StaleDeletePlanException or SequenceInLibraryException => ex.Message,
LeaseUnavailableException or NewerFormatException or StaleRenamePlanException or NestedRenameException or StaleDeletePlanException
or SequenceInLibraryException => ex.Message,
UnauthorizedAccessException => Loc.L("Archive.Failed.Access"),
DatabaseException => Loc.L("Archive.Failed.Index"),
ArgumentException => Loc.L("Archive.Failed.Gone"),
+2 -2
View File
@@ -41,8 +41,8 @@ public static class MassRename
: new RenameRow(s.SequenceId, s.FromTitle ?? string.Empty, s.ToTitle ?? string.Empty)),
];
/// <summary>"12 of 36 sequences change".</summary>
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count, setSize);
/// <summary>"12 of 36 sequences change"; sequences that only move with a folder they are in are listed, not counted.</summary>
public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => !s.Carried), setSize);
}
/// <summary>Adding and removing tags on a set of sequences (BRIEF §12.5 Retag).</summary>
+50 -7
View File
@@ -1,6 +1,7 @@
using System.Globalization;
using System.Text.Json;
using Titano.Core.IO;
using Titano.Core.Localization;
using Titano.Core.Naming;
namespace Titano.Core.Archiving;
@@ -9,11 +10,20 @@ namespace Titano.Core.Archiving;
public sealed record RenameSubject(Guid SequenceId, string Folder, string? Title, DateTime? FirstCapture, string? CameraMake, string? CameraModel, string? Lens);
/// <summary>One sequence's change: its folder, its title, or both.</summary>
public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle)
/// <param name="Carried">The folder moves only because a folder it is inside moves (a sequence nested in another).</param>
public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried = false)
{
public bool MovesFolder => !string.Equals(FromFolder, ToFolder, StringComparison.Ordinal);
}
/// <summary>A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned.</summary>
public sealed class NestedRenameException(string target, string folder)
: ArgumentException(Loc.L("Archive.Error.NestedTarget", target, folder))
{
public string Target { get; } = target;
public string Folder { get; } = folder;
}
/// <summary>The exact changes a mass rename will make (its dry run); applying it makes exactly these.</summary>
public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList<RenameStep> Steps);
@@ -50,16 +60,21 @@ public static class RenamePlanner
/// Expands <paramref name="titleTemplate"/> (where <c>{title}</c> is the current title) and then
/// <paramref name="folderTemplate"/> (where <c>{title}</c> is the new title) for every subject. A target folder
/// that is any current sequence folder, exists on disk or was given to an earlier subject gets " (2)", " (3)"….
/// Null templates leave that part unchanged; subjects without a change produce no step.
/// Null templates leave that part unchanged; subjects without a change produce no step. A folder that moves takes
/// the sequences inside it along: each gets a <see cref="RenameStep.Carried"/> step after every move, so the index
/// follows its files; a selected sequence inside a moving folder that moves elsewhere leaves first.
/// </summary>
/// <param name="occupied">Every sequence folder of the archive (renamed or not).</param>
/// <param name="nested">The archive's other sequences inside a subject's folder, with their titles.</param>
/// <exception cref="NestedRenameException">A target lies inside a sequence's folder, or inside another target.</exception>
public static RenamePlan Plan(Guid archiveId, IReadOnlyList<RenameSubject> subjects, string? folderTemplate, string? titleTemplate,
IEnumerable<string> occupied, Func<string, bool> existsOnDisk)
IEnumerable<string> occupied, Func<string, bool> existsOnDisk, IReadOnlyList<RenameSubject>? nested = null)
{
var folder = folderTemplate is null ? null : PathTemplate.Parse(folderTemplate);
var title = titleTemplate is null ? null : PathTemplate.Parse(titleTemplate);
var claimed = new HashSet<string>(occupied, StringComparer.OrdinalIgnoreCase);
var steps = new List<RenameStep>();
var taken = occupied.ToList();
var claimed = new HashSet<string>(taken, StringComparer.OrdinalIgnoreCase);
var own = new List<RenameStep>(subjects.Count);
foreach (var s in subjects)
{
var context = new NamingContext
@@ -80,11 +95,39 @@ public static class RenamePlanner
newFolder = expanded.Equals(s.Folder, StringComparison.OrdinalIgnoreCase) ? expanded : Unique(expanded, claimed, existsOnDisk);
claimed.Add(newFolder);
}
if (newFolder != s.Folder || newTitle != s.Title) steps.Add(new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle));
own.Add(new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle));
}
return new RenamePlan(Guid.CreateVersion7(), archiveId, steps);
var moving = own.Where(s => s.MovesFolder).ToList();
foreach (var step in moving)
{
// Into a sequence's folder (its own included) or another target: one sequence would end up inside another.
var host = taken.Concat(moving.Where(m => m != step).Select(m => m.ToFolder)).FirstOrDefault(f => IsInside(f, step.ToFolder));
if (host is not null) throw new NestedRenameException(step.ToFolder, host);
}
var steps = new List<(RenameStep Step, int Order)>();
foreach (var step in own.Concat((nested ?? []).Select(n => new RenameStep(n.SequenceId, n.Folder, n.Folder, n.Title, n.Title))))
{
// The nearest folder around it that moves carries it; a sequence that moves elsewhere leaves before its folder does.
var carrier = step.MovesFolder ? null : moving.Where(m => IsInside(m.FromFolder, step.FromFolder)).MaxBy(m => m.FromFolder.Length);
if (carrier is not null)
steps.Add((step with { ToFolder = carrier.ToFolder + step.FromFolder[carrier.FromFolder.Length..], Carried = true }, 1));
else if (step.MovesFolder)
steps.Add((step, -moving.Count(m => m != step && IsInside(m.FromFolder, step.FromFolder))));
else if (step.FromTitle != step.ToTitle)
steps.Add((step, 0));
}
// Stable: subjects keep their order, sequences inside moving folders move out first, carried ones come last.
return new RenamePlan(Guid.CreateVersion7(), archiveId, [.. steps.OrderBy(s => s.Order).Select(s => s.Step)]);
}
/// <summary>
/// Whether <paramref name="path"/> lies inside <paramref name="folder"/> (archive-relative, forward slashes); the
/// archive root, a sequence only when a folder was adopted in place, counts as containing nothing.
/// </summary>
public static bool IsInside(string folder, string path) =>
folder.Length > 0 && path.Length > folder.Length + 1 && path[folder.Length] == '/' && path.StartsWith(folder, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Moves the folder of a step; idempotent so a resumed plan can repeat it: an already moved folder is accepted,
/// a case-only change goes through a temporary name (case-insensitive file systems).
+15 -2
View File
@@ -32,6 +32,8 @@ public sealed class MassRenamer
/// <param name="folderTemplate">New folder template (<c>{title}</c> = the new title), or null to keep folders.</param>
/// <param name="titleTemplate">New title template (<c>{title}</c> = the current title), or null to keep titles.</param>
/// <remarks>Sequences nested in a folder that moves are part of the plan (they move with it); see <see cref="RenamePlanner.Plan"/>.</remarks>
/// <exception cref="NestedRenameException">A new folder would lie inside a sequence's folder.</exception>
public async Task<RenamePlan> PlanAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, string? folderTemplate, string? titleTemplate,
CancellationToken cancellationToken = default)
{
@@ -42,12 +44,23 @@ public sealed class MassRenamer
{
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } s || s.ArchiveId != archive.Id)
throw new ArgumentException($"Sequence {id} is not in archive {archive.Id}.", nameof(sequenceIds));
subjects.Add(new RenameSubject(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens));
subjects.Add(Subject(s));
}
var nested = new List<RenameSubject>();
if (folderTemplate is not null)
{
var selected = sequenceIds.ToHashSet();
foreach (var location in locations.Where(l => !selected.Contains(l.Id) && subjects.Any(s => RenamePlanner.IsInside(s.Folder, l.Folder))))
{
if (await _db.Sequences.GetAsync(location.Id, cancellationToken).ConfigureAwait(false) is { } inner) nested.Add(Subject(inner));
}
}
return RenamePlanner.Plan(archive.Id, subjects, folderTemplate, titleTemplate, locations.Select(l => l.Folder),
folder => Directory.Exists(paths.Sequence(folder).Folder));
folder => Directory.Exists(paths.Sequence(folder).Folder), nested);
}
private static RenameSubject Subject(Sequence s) => new(s.Id, s.Folder, s.Title, s.FirstCapture, s.CameraMake, s.CameraModel, s.Lens);
/// <summary>Applies a plan; each completed step is journaled before the next starts.</summary>
/// <exception cref="StaleRenamePlanException">A sequence is no longer where the plan expects it; nothing of that step was changed.</exception>
public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress<int>? progress = null, CancellationToken cancellationToken = default) =>
@@ -105,6 +105,69 @@ public sealed class MassRenameTests(TestContext context)
Assert.True(Directory.Exists(fx.Paths.FromRelative(other.Steps[0].ToFolder)));
}
/// <summary>"trips" with photos of its own, "trips/day2" inside it and "trips/day2/dawn" inside that: three nested sequences.</summary>
private static async Task<List<Guid>> NestedAsync(ArchiveFixture fx)
{
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips"), Start, 2);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips", "day2"), Start.AddDays(1), 2, firstSeed: 10);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "trips", "day2", "dawn"), Start.AddDays(2), 2, firstSeed: 20);
await fx.ScanAsync();
var locations = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).OrderBy(l => l.Folder, StringComparer.Ordinal).ToList();
Assert.SequenceEqual(["trips", "trips/day2", "trips/day2/dawn"], locations.Select(l => l.Folder));
return [.. locations.Select(l => l.Id)];
}
[Test]
public async Task SequencesInsideAMovedFolderAreInTheDryRunAndMoveWithIt()
{
await using var fx = await CreateAsync(context);
var ids = await NestedAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "moved/{date}", null, fx.Ct);
Assert.SequenceEqual(["moved/2026-09-28", "moved/2026-09-28/day2", "moved/2026-09-28/day2/dawn"], plan.Steps.Select(s => s.ToFolder));
Assert.SequenceEqual([false, true, true], plan.Steps.Select(s => s.Carried));
Assert.SequenceEqual(before, await StateAsync(fx, ids));
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
Assert.Empty((await fx.Service.FindOrphansAsync(fx.Archive.Id, fx.Ct)).MissingSequences);
}
[Test]
public async Task NestedSequencesMovedTogetherLeaveTheirFolderFirst()
{
await using var fx = await CreateAsync(context);
var ids = await NestedAsync(fx);
var before = await StateAsync(fx, ids);
var plan = await fx.Service.PlanRenameAsync(fx.Archive.Id, ids, "moved/{date}", null, fx.Ct);
Assert.SequenceEqual([ids[2], ids[1], ids[0]], plan.Steps.Select(s => s.SequenceId));
Assert.True(plan.Steps.All(s => !s.Carried));
await fx.Service.ApplyRenameAsync(plan, null, fx.Ct);
Assert.SequenceEqual(["moved/2026-09-28", "moved/2026-09-29", "moved/2026-09-30"], (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id))
.Select(l => l.Folder).Order(StringComparer.Ordinal));
Assert.SequenceEqual(Expected(plan, before), await StateAsync(fx, ids));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
}
[Test]
public async Task AFolderInsideASequenceFolderIsRefused()
{
await using var fx = await CreateAsync(context);
var ids = await PopulateAsync(fx);
var before = await StateAsync(fx, ids);
var into = await Assert.ThrowsAsync<NestedRenameException>(() => fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[1]], "inbox/a/{date}", null, fx.Ct));
Assert.Equal("inbox/a", into.Folder);
var itself = await Assert.ThrowsAsync<NestedRenameException>(() => fx.Service.PlanRenameAsync(fx.Archive.Id, [ids[0]], "inbox/a/{date}", null, fx.Ct));
Assert.Equal("inbox/a/2026-09-28", itself.Target);
Assert.SequenceEqual(before, await StateAsync(fx, ids));
}
/// <summary>Reports synchronously (Progress&lt;T&gt; would post to the thread pool).</summary>
private sealed class SyncProgress(Action<int> report) : IProgress<int>
{