fix(archive): Reorganize never plans a move onto a folder of the exact name, keeps long names' extensions, says why a template is refused

Second fix round of owner review 2, phase 4a (planner findings).

- A sequence keeps a folder that differs from its own in case only while no
  other folder holds that exact name (RenamePlanner.ExistsExactly, every level
  compared exactly). On a case-sensitive file system a stray "Trip (2)" beside
  the sequence at "trip (2)" no longer gives a case-only step that MoveFolder
  refuses at every archive open: the plan gives "Trip", and a plan whose
  target appeared since is refused under the step's leases before anything
  moves (or dropped when it resumes). A change of case in an outer level no
  longer looks like two folders on Windows.
- A file name longer than 200 characters is shortened before the ".{ext}" the
  template ends with, never through it, so a long title never strips the
  photo's extension.
- The archive engine's own settings check applies the template rules the
  server and the desktop apply (a folder scans skip, a lost extension, names
  that repeat), so archive.json can no longer take such a template.
- The server's invalid_template answer names the rule after the field
  ("fileTemplate:extension") with the desktop's sentence as its message; both
  admin panels show it on the field.
- FrameNaming keeps only the naming overloads production uses.
- Comments about Unreadable say the whole sequence stays as it is.
- Tests pin filing against Reorganize: an upload without a capture time, a
  card's second session with {session}, a duplicate skipped mid-session, and a
  whole folder of two cameras named with the first one's camera.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 50fe59aec1e180daa1733bcb951892a79dceba6c)
This commit is contained in:
Alby96 committed 2026-10-27 18:08:08 +01:00
1 parent 9e1f109b58
commit 765f0ad36b
20 files changed
+446 -141

No files matched your search

@@ -112,8 +112,8 @@ internal sealed class ArchiveFixture : IAsyncDisposable
return job;
}
/// <summary>Stages a verified upload-like file for ingest: returns its path, size and SHA-256.</summary>
public (string Path, long Size, string Sha256) Stage(DateTime captured, int seed, string? make = "Canon", string? model = "Canon EOS R5", string? lens = null)
/// <summary>Stages a verified upload-like file for ingest (<paramref name="captured"/> null: a photo that records no time): returns its path, size and SHA-256.</summary>
public (string Path, long Size, string Sha256) Stage(DateTime? captured, int seed, string? make = "Canon", string? model = "Canon EOS R5", string? lens = null)
{
var staging = Path.Combine(Paths.StagingDirectory, "uploads");
Directory.CreateDirectory(staging);
@@ -132,7 +132,7 @@ internal sealed class ArchiveFixture : IAsyncDisposable
/// <summary>Small real JPEGs with Exif made by the in-house encoder; each seed gives distinct bytes.</summary>
internal static class Photos
{
public static byte[] Jpeg(DateTime captured, int seed, string? make = "Canon", string? model = "Canon EOS R5", string? lens = null)
public static byte[] Jpeg(DateTime? captured, int seed, string? make = "Canon", string? model = "Canon EOS R5", string? lens = null)
{
using var image = new ImageBuffer(48, 32);
var random = new Random(seed);
@@ -90,6 +90,19 @@ public sealed class ArchiveSettingsTests(TestContext context)
var template = await Assert.ThrowsAsync<ArgumentException>(() =>
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = "{year/{date" } }, fx.Ct));
Assert.Equal("folderTemplate", template.ParamName);
// The rules every template is held to wherever it is typed: a folder scans never enter, a lost extension, names that repeat.
foreach (var (folder, file, field) in new[]
{
("exports/{date}", "{n}", "folderTemplate"), ("{date}", "{n}{ext}", "fileTemplate"), ("{date}", "{title}", "fileTemplate"),
})
{
var rule = await Assert.ThrowsAsync<ArgumentException>(() =>
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = folder, File = file } }, fx.Ct));
Assert.Equal(field, rule.ParamName, $"{folder} · {file}");
}
var created = await Assert.ThrowsAsync<ArgumentException>(() =>
fx.Service.CreateAsync(context.CreateTempDirectory("other"), "Other", new LayoutTemplates { Folder = "{date}", File = "{n}{ext}" }, null, fx.Ct));
Assert.Equal("fileTemplate", created.ParamName);
var proxies = await Assert.ThrowsAsync<ArgumentException>(() =>
fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 100 } }, fx.Ct));
Assert.Equal("proxyLongEdge", proxies.ParamName);
@@ -177,6 +177,50 @@ public sealed class ReorganizeTests(TestContext context)
Assert.Empty(plan.Steps);
}
[Test]
public async Task AnUploadWithoutACaptureTimeIsFiledAsReorganizeNamesIt()
{
await using var fx = await CreateAsync(context);
const string FolderTemplate = "{year}/{date} {hm}", FileTemplate = "{date}_{time}_{n:0000}";
await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = FolderTemplate, File = FileTemplate } }, fx.Ct);
// Photos that record no time: the first takes its file's, the second the one its client sent; never the time they are filed.
var noon = new DateTime(2026, 9, 28, 12, 0, 0);
var first = fx.Stage(null, 60);
File.SetLastWriteTime(first.Path, noon);
var id = (await fx.Service.Ingest.CommitAsync(Upload(fx, first, "IMG_0001.JPG", "upload-1"), fx.Ct)).SequenceId;
var second = fx.Stage(null, 61);
await fx.Service.Ingest.CommitAsync(Upload(fx, second, "IMG_0002.JPG", "upload-1") with { ClientCapturedAt = noon.AddSeconds(10) }, fx.Ct);
Assert.Equal("2026/2026-09-28 12-00", (await fx.Db.Sequences.GetAsync(id))!.Folder);
Assert.SequenceEqual(["originals/2026-09-28_12-00-00_0001.JPG", "originals/2026-09-28_12-00-10_0002.JPG"], await FilesAsync(fx, id));
Assert.Empty((await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(FolderTemplate, FileTemplate), fx.Ct)).Steps);
}
[Test]
public async Task APhotoSkippedMidSessionLeavesNumbersThatReorganizeCloses()
{
await using var fx = await CreateAsync(context);
// The card's second photo is in the archive already (uploaded before): the import skips it.
var day = Start.AddDays(1);
await fx.Service.Ingest.CommitAsync(Upload(fx, fx.Stage(day.AddSeconds(10), 31), "IMG_0002.JPG", "upload-1"), fx.Ct);
var card = context.CreateTempDirectory("card");
Photos.WriteSeries(Path.Combine(card, "DCIM", "100CANON"), day, 4, firstSeed: 30);
const string FileTemplate = "{date}_{n:0000}";
var import = await fx.Service.PlanImportAsync(fx.Archive.Id, card, new ImportOptions { FolderTemplate = "{year}/{date} card", FileTemplate = FileTemplate },
null, null, fx.Ct);
Assert.SequenceEqual([ImportAction.Copy, ImportAction.SkipInArchive, ImportAction.Copy, ImportAction.Copy], import.Sessions.Single().Items.Select(i => i.Action));
var engine = await fx.StartEngineAsync();
await fx.WaitForAsync((await engine.EnqueueAsync(ArchiveJobs.Import(fx.Archive, import, null), cancellationToken: fx.Ct)).Id, JobState.Done);
// Filed with the numbers the import showed, the skipped photo's left out; Reorganize numbers the sequence as it is
// now, which its dry run lists (a divergence FrameNaming names).
var imported = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "2026/2026-09-29 card").Id;
Assert.SequenceEqual(["originals/2026-09-29_0001.JPG", "originals/2026-09-29_0003.JPG", "originals/2026-09-29_0004.JPG"], await FilesAsync(fx, imported));
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [imported], new RenameTemplates(File: FileTemplate), fx.Ct);
Assert.SequenceEqual(["originals/2026-09-29_0003.JPG>originals/2026-09-29_0002.JPG", "originals/2026-09-29_0004.JPG>originals/2026-09-29_0003.JPG"],
plan.Steps.Single().FileSamples.Select(s => $"{s.From}>{s.To}"));
}
[Test]
public async Task ASequenceWhoseSidecarCannotBeReadStaysAsItIsAndTheOthersMove()
{
@@ -730,6 +774,42 @@ public sealed class ReorganizeTests(TestContext context)
Assert.Empty(RenameJournal.ListPending(fx.Paths));
}
[Test]
public async Task AChangeOfCaseOntoAnotherFolderOfThatExactNameIsRefusedBeforeItMoves()
{
await using var fx = await CreateAsync(context);
Directory.CreateDirectory(fx.Paths.FromRelative("probe"));
var caseSensitive = !Directory.Exists(fx.Paths.FromRelative("PROBE"));
Directory.Delete(fx.Paths.FromRelative("probe"));
if (!caseSensitive) TestContext.Skip("needs a case-sensitive file system, where two folders differ only in case");
var id = await UploadAsync(fx, 1);
await fx.Service.ApplyRenameAsync(await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], new RenameTemplates(Folder: "trip (2)"), fx.Ct), null, fx.Ct);
var templates = new RenameTemplates(Folder: "Trip");
// Planned while no other folder holds that name: the folder keeps its number, in the template's case.
var plan = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
Assert.Equal("Trip (2)", plan.Steps.Single().ToFolder);
// A folder of exactly that name appears beside it (a copy): refused before anything moves, and dropped when an
// interrupted plan resumes, instead of failing at every archive open.
var stranger = fx.Paths.FromRelative("Trip (2)/note.txt");
Directory.CreateDirectory(Path.GetDirectoryName(stranger)!);
File.WriteAllText(stranger, "kept");
await Assert.ThrowsAsync<StaleRenamePlanException>(() => fx.Service.ApplyRenameAsync(plan, null, fx.Ct));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
RenameJournal.Write(fx.Paths, new RenameJournal(plan, []));
Assert.Equal(1, await fx.Service.Renamer.ResumePendingAsync(fx.Archive, fx.Ct));
Assert.Empty(RenameJournal.ListPending(fx.Paths));
Assert.Equal("trip (2)", await FolderAsync(fx, id));
// Planned now, the sequence takes a folder of its own, and the other folder stays as it was.
var again = await fx.Service.PlanReorganizeAsync(fx.Archive.Id, [id], templates, fx.Ct);
Assert.Equal("Trip", again.Steps.Single().ToFolder);
await fx.Service.ApplyRenameAsync(again, null, fx.Ct);
Assert.Equal("Trip", await FolderAsync(fx, id));
Assert.Equal("kept", File.ReadAllText(stranger));
Assert.SequenceEqual(["note.txt"], Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(stranger)!).Select(Path.GetFileName));
}
[Test]
public async Task PhotosHashedAfterThePlanKeepTheNamesItShowed()
{