diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx
index 79ccbb34..5c11be26 100644
--- a/i18n/en/Archive.resx
+++ b/i18n/en/Archive.resx
@@ -81,6 +81,7 @@
The copy of {0} does not match the original.long: error sentence
{0} could not be added to the sequence.long: error sentence
{0} is already in the library.long: error sentence
+ {0} would be inside the sequence folder {1}.long: error sentence
{0} was written by a newer Titano (format {1}).long: error sentence
The archive {0} is offline.long: error sentence
The archive {0} is read-only.long: error sentence
diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx
index 889e7ad4..06606110 100644
--- a/i18n/it/Archive.it.resx
+++ b/i18n/it/Archive.it.resx
@@ -76,6 +76,7 @@
La copia di {0} non corrisponde all'originale.
Impossibile aggiungere {0} alla sequenza.
{0} è già nella libreria.
+ {0} finirebbe dentro la cartella della sequenza {1}.
{0} è stato scritto da un Titano più recente (formato {1}).
L'archivio {0} non è raggiungibile.
L'archivio {0} è di sola lettura.
diff --git a/src/Titano.App/Archive/ArchiveFailures.cs b/src/Titano.App/Archive/ArchiveFailures.cs
index b7013175..94565389 100644
--- a/src/Titano.App/Archive/ArchiveFailures.cs
+++ b/src/Titano.App/Archive/ArchiveFailures.cs
@@ -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"),
diff --git a/src/Titano.App/Archive/MassOperations.cs b/src/Titano.App/Archive/MassOperations.cs
index 4bcb2d3b..7be16553 100644
--- a/src/Titano.App/Archive/MassOperations.cs
+++ b/src/Titano.App/Archive/MassOperations.cs
@@ -41,8 +41,8 @@ public static class MassRename
: new RenameRow(s.SequenceId, s.FromTitle ?? string.Empty, s.ToTitle ?? string.Empty)),
];
- /// "12 of 36 sequences change".
- public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count, setSize);
+ /// "12 of 36 sequences change"; sequences that only move with a folder they are in are listed, not counted.
+ public static string Summary(RenamePlan plan, int setSize) => Loc.Plural("Archive.Rename.Summary", plan.Steps.Count(s => !s.Carried), setSize);
}
/// Adding and removing tags on a set of sequences (BRIEF §12.5 Retag).
diff --git a/src/Titano.Core/Archiving/MassRename.cs b/src/Titano.Core/Archiving/MassRename.cs
index caf423c9..c653b694 100644
--- a/src/Titano.Core/Archiving/MassRename.cs
+++ b/src/Titano.Core/Archiving/MassRename.cs
@@ -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);
/// One sequence's change: its folder, its title, or both.
-public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle)
+/// The folder moves only because a folder it is inside moves (a sequence nested in another).
+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);
}
+/// A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned.
+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;
+}
+
/// The exact changes a mass rename will make (its dry run); applying it makes exactly these.
public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList Steps);
@@ -50,16 +60,21 @@ public static class RenamePlanner
/// Expands (where {title} is the current title) and then
/// (where {title} 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 step after every move, so the index
+ /// follows its files; a selected sequence inside a moving folder that moves elsewhere leaves first.
///
/// Every sequence folder of the archive (renamed or not).
+ /// The archive's other sequences inside a subject's folder, with their titles.
+ /// A target lies inside a sequence's folder, or inside another target.
public static RenamePlan Plan(Guid archiveId, IReadOnlyList subjects, string? folderTemplate, string? titleTemplate,
- IEnumerable occupied, Func existsOnDisk)
+ IEnumerable occupied, Func existsOnDisk, IReadOnlyList? nested = null)
{
var folder = folderTemplate is null ? null : PathTemplate.Parse(folderTemplate);
var title = titleTemplate is null ? null : PathTemplate.Parse(titleTemplate);
- var claimed = new HashSet(occupied, StringComparer.OrdinalIgnoreCase);
- var steps = new List();
+ var taken = occupied.ToList();
+ var claimed = new HashSet(taken, StringComparer.OrdinalIgnoreCase);
+ var own = new List(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)]);
}
+ ///
+ /// Whether lies inside (archive-relative, forward slashes); the
+ /// archive root, a sequence only when a folder was adopted in place, counts as containing nothing.
+ ///
+ public static bool IsInside(string folder, string path) =>
+ folder.Length > 0 && path.Length > folder.Length + 1 && path[folder.Length] == '/' && path.StartsWith(folder, StringComparison.OrdinalIgnoreCase);
+
///
/// 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).
diff --git a/src/Titano.Data/Archiving/MassRenamer.cs b/src/Titano.Data/Archiving/MassRenamer.cs
index 9cc0af2e..ad46a81b 100644
--- a/src/Titano.Data/Archiving/MassRenamer.cs
+++ b/src/Titano.Data/Archiving/MassRenamer.cs
@@ -32,6 +32,8 @@ public sealed class MassRenamer
/// New folder template ({title} = the new title), or null to keep folders.
/// New title template ({title} = the current title), or null to keep titles.
+ /// Sequences nested in a folder that moves are part of the plan (they move with it); see .
+ /// A new folder would lie inside a sequence's folder.
public async Task PlanAsync(Archive archive, IReadOnlyList 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();
+ 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);
+
/// Applies a plan; each completed step is journaled before the next starts.
/// A sequence is no longer where the plan expects it; nothing of that step was changed.
public Task ApplyAsync(Archive archive, RenamePlan plan, IProgress? progress = null, CancellationToken cancellationToken = default) =>
diff --git a/tests/Titano.Data.Tests/Archiving/MassRenameTests.cs b/tests/Titano.Data.Tests/Archiving/MassRenameTests.cs
index 5cf3130a..c54ca153 100644
--- a/tests/Titano.Data.Tests/Archiving/MassRenameTests.cs
+++ b/tests/Titano.Data.Tests/Archiving/MassRenameTests.cs
@@ -105,6 +105,69 @@ public sealed class MassRenameTests(TestContext context)
Assert.True(Directory.Exists(fx.Paths.FromRelative(other.Steps[0].ToFolder)));
}
+ /// "trips" with photos of its own, "trips/day2" inside it and "trips/day2/dawn" inside that: three nested sequences.
+ private static async Task> 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(() => 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(() => 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));
+ }
+
/// Reports synchronously (Progress<T> would post to the thread pool).
private sealed class SyncProgress(Action report) : IProgress
{