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

@@ -203,6 +203,8 @@ public sealed class ReorganizeTests(TestContext context)
Assert.Equal("fileTemplate", new RenameTemplates(File: "{nope}").Problem());
Assert.Equal("fileTemplate", new RenameTemplates(File: "{date:%}").Problem());
Assert.Equal("titleTemplate", new RenameTemplates(Title: "{title").Problem());
// Not valid, blank or written with an unusable format: no rule to name.
Assert.Equal(new TemplateProblem("fileTemplate", null), new RenameTemplates(File: "{date:%}").Check());
Assert.True(new RenameTemplates().IsEmpty);
}
@@ -221,6 +223,7 @@ public sealed class ReorganizeTests(TestContext context)
var folder = field == "folderTemplate";
var templates = folder ? new RenameTemplates(Folder: template) : new RenameTemplates(File: template);
Assert.Equal(field, templates.Problem());
Assert.Equal(new TemplateProblem(field, rule), templates.Check());
Assert.Equal(rule, folder ? TemplateRules.FolderRule(PathTemplate.Parse(template)) : TemplateRules.FileRule(PathTemplate.Parse(template)));
}
@@ -362,6 +365,59 @@ public sealed class ReorganizeTests(TestContext context)
}
}
[Test]
public void AChangeOfCaseIsNeverPlannedOntoAnotherFolderOfThatExactName()
{
// A case-sensitive server: "Trip (2)" is a folder of its own beside the sequence at "trip (2)", and no sequence's.
var subject = new RenameSubject(Guid.NewGuid(), "trip (2)", "Trip", Start, null, null, null);
var onDisk = new HashSet<string>(["trip (2)", "Trip (2)"], StringComparer.Ordinal);
var plan = RenamePlanner.Plan(Guid.NewGuid(), [subject], "{title}", null, ["trip (2)"], onDisk.Contains, existsExactly: onDisk.Contains);
Assert.Equal("Trip", plan.Steps.Single().ToFolder);
// Case-insensitive, the only folder of that name is its own: it keeps its number, in the template's case.
var own = RenamePlanner.Plan(Guid.NewGuid(), [subject], "{title}", null, ["trip (2)"], f => f.Equals("trip (2)", StringComparison.OrdinalIgnoreCase),
existsExactly: f => f == "trip (2)");
Assert.Equal("Trip (2)", own.Steps.Single().ToFolder);
}
[Test]
public void AFolderExistsExactlyOnlyInTheCaseOfEveryLevel()
{
var archive = new ArchivePaths(context.CreateTempDirectory("archive"));
Directory.CreateDirectory(archive.FromRelative("trip/day"));
File.WriteAllText(Path.Combine(archive.FromRelative("trip/day"), "a.txt"), "a");
Assert.True(RenamePlanner.ExistsExactly(archive, "trip/day"));
Assert.False(RenamePlanner.ExistsExactly(archive, "Trip/day"));
Assert.False(RenamePlanner.ExistsExactly(archive, "trip/Day"));
Assert.False(RenamePlanner.ExistsExactly(archive, "trip/night"));
// An outer level's case alone: the folder moves on any file system (a case-insensitive one keeps the outer name as it was).
var step = new RenameStep(Guid.NewGuid(), "trip/day", "Trip/day", "T", "T");
RenamePlanner.MoveFolder(archive, step);
RenamePlanner.MoveFolder(archive, step);
Assert.Equal("a", File.ReadAllText(Path.Combine(archive.FromRelative("Trip/day"), "a.txt")));
}
[Test]
public void PhotosOfALongTitleKeepTheirExtension()
{
// As long as a title goes, less the room the number and the extension take: the name gives way before ".{ext}".
var manifest = Sequence("originals/a.JPG", "originals/b.JPG", "originals/c.JPG");
var title = new string('t', 186) + " harbour";
const string Template = "{title}_{n:0000}.{ext}";
var plan = Plan(manifest, Template, title);
Assert.Equal(3, plan.Frames);
foreach (var move in plan.Moves)
{
Assert.True(move.To.EndsWith(".JPG", StringComparison.Ordinal), move.To);
Assert.True(Path.GetFileName(move.To).Length <= PathTemplate.MaxSegmentLength + 2, move.To);
}
Assert.Equal(3, plan.Moves.Select(m => m.To).Distinct(StringComparer.OrdinalIgnoreCase).Count());
// Renamed so, the template names them again as they are.
var renamed = FileRenameJournal.Applied(manifest, FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t"))!;
Assert.Empty(Plan(renamed, Template, title).Moves);
}
[Test]
public void ExtensionsAPhotoLostComeBackFromItsName()
{
@@ -384,7 +440,8 @@ public sealed class ReorganizeTests(TestContext context)
{
// Every third photo has an XMP companion: "x_4" is free for the others, not for it.
Func<string, bool> companion = i % 3 == 1 ? c => !reference.Contains(Path.ChangeExtension(c, ".xmp")) : _ => true;
var expected = FrameNaming.Unique("a/x.JPG", c => !reference.Contains(c) && companion(c));
var expected = "a/x.JPG";
for (var n = 2; reference.Contains(expected) || !companion(expected); n++) expected = FrameNaming.Numbered("a/x.JPG", n);
reference.Add(expected);
Assert.Equal(expected, names.Claim("a/x.JPG", companion), $"photo {i}");
}
@@ -68,6 +68,15 @@ public sealed class FrameNamingTests(TestContext context)
Assert.Equal("DSC_0001", context.OriginalName);
Assert.Equal("jpg", context.Extension);
Assert.Equal(1, context.Number);
// After a first photo that has one, that photo's time.
var first = new DateTime(2026, 9, 28, 18, 0, 0);
var timed = manifest with
{
Frames = [manifest.Frames[0] with { CapturedAt = first }, new SidecarFrame { Id = Guid.NewGuid(), I = 1, File = "originals/b.jpg", Original = "DSC_0002.JPG" }],
};
var second = FrameNaming.Context(timed.Frames[1], timed, null);
Assert.Equal((first, first, 2), (second.CapturedAt, second.SessionStart, second.Number));
}
[Test]
@@ -77,10 +86,11 @@ public sealed class FrameNamingTests(TestContext context)
var context = FrameNaming.Context(Metadata(new DateTime(2026, 9, 28, 18, 0, 0)), "IMG_1.JPG", new DateTime(2026, 9, 28, 18, 0, 0),
new DateTime(2026, 9, 28, 18, 0, 0), 1, null);
var taken = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "originals/2026-09-28.jpg" };
Assert.Equal("originals/2026-09-28_2.JPG", FrameNaming.FileName(template, context, taken, "originals/"));
Assert.Equal("originals/2026-09-28_3.JPG", FrameNaming.FileName(template, context, taken, "originals/"));
var names = new UniqueNames(taken);
Assert.Equal("originals/2026-09-28_2.JPG", FrameNaming.FileName(template, context, names, "originals/"));
Assert.Equal("originals/2026-09-28_3.JPG", FrameNaming.FileName(template, context, names, "originals/"));
Assert.Contains("originals/2026-09-28_3.JPG", taken);
Assert.Equal("a/IMG_5_2.CR2", FrameNaming.Unique("a/IMG_5.CR2", f => f != "a/IMG_5.CR2"));
Assert.Equal("a/IMG_5_2.CR2", new UniqueNames(new HashSet<string>(["a/IMG_5.CR2"])).Claim("a/IMG_5.CR2"));
}
[Test]
@@ -92,21 +102,7 @@ public sealed class FrameNamingTests(TestContext context)
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = fileTemplate });
var session = plan.Sessions.Single();
// The sequence the import files: the plan's names, each frame from its photo's metadata, the camera of the first.
var frames = session.Items.Select(item =>
{
var metadata = MetadataReader.Read(Path.Combine(card, item.SourcePath));
return SequenceFrames.FromMetadata(Guid.NewGuid(), "originals/" + item.FileName, Path.GetFileName(item.SourcePath), item.Size, new string('b', 64),
metadata, item.CapturedAt);
}).ToList();
var first = MetadataReader.Read(Path.Combine(card, session.Items[0].SourcePath));
var manifest = SequenceFrames.Insert(new SequenceManifest
{
Id = Guid.NewGuid(),
Camera = new SidecarCamera { Make = first.Make, Model = first.Model },
Lens = first.LensModel,
}, frames);
var manifest = Filed(card, session);
var reorganized = FileRenames.Plan(manifest, session.Title, PathTemplate.Parse(fileTemplate), [.. manifest.Frames.Select(f => f.File)]);
Assert.Empty(reorganized.Moves);
Assert.Equal(0, reorganized.Frames);
@@ -114,6 +110,62 @@ public sealed class FrameNamingTests(TestContext context)
manifest.Frames.Select(f => PathTemplate.Parse(fileTemplate).ExpandFile(FrameNaming.Context(f, manifest, session.Title))));
}
/// <summary>
/// The sequence an import files <paramref name="session"/> of <paramref name="source"/> into: the plan's names, each
/// frame from its photo's metadata, the camera and lens of the first.
/// </summary>
private static SequenceManifest Filed(string source, PlannedSession session)
{
var frames = session.Items.Select(item => SequenceFrames.FromMetadata(Guid.NewGuid(), "originals/" + item.FileName, Path.GetFileName(item.SourcePath),
item.Size, new string('b', 64), MetadataReader.Read(Path.Combine(source, item.SourcePath)), item.CapturedAt)).ToList();
var first = MetadataReader.Read(Path.Combine(source, session.Items[0].SourcePath));
return SequenceFrames.Insert(new SequenceManifest
{
Id = Guid.NewGuid(),
Camera = new SidecarCamera { Make = first.Make, Model = first.Model },
Lens = first.LensModel,
}, frames);
}
private static List<string> Renames(SequenceManifest manifest, string? title, string template) =>
[.. FileRenames.Plan(manifest, title, PathTemplate.Parse(template), [.. manifest.Frames.Select(f => f.File)]).Moves.Select(m => $"{m.From}>{m.To}")];
[Test]
public async Task ASecondSessionOfACardIsNumberedByTheImportAndRenamedByReorganize()
{
// Two sessions of one card two hours apart: the import numbers them, while each sequence is one session of its own.
var card = context.CreateTempDirectory("card");
var folder = Path.Combine(card, "DCIM", "100CANON");
TestPhotos.WriteSeries(folder, Start, 2, TimeSpan.FromSeconds(10));
TestPhotos.WriteSeries(folder, Start.AddHours(2), 2, TimeSpan.FromSeconds(10), firstSeed: 10, firstNumber: 3);
const string fileTemplate = "{session}_{n:0000}";
var plan = await PlanAsync(card, context.CreateTempDirectory("archive"), new ImportOptions { FileTemplate = fileTemplate, MinimumSessionFrames = 1 });
Assert.SequenceEqual(["1_0001.JPG 1_0002.JPG", "2_0001.JPG 2_0002.JPG"], plan.Sessions.Select(s => string.Join(' ', s.Items.Select(i => i.FileName))));
// A divergence FrameNaming names: Reorganize calls the second sequence's session 1, and its dry run lists the renames.
Assert.Empty(Renames(Filed(card, plan.Sessions[0]), plan.Sessions[0].Title, fileTemplate));
Assert.SequenceEqual(["originals/2_0001.JPG>originals/1_0001.JPG", "originals/2_0002.JPG>originals/1_0002.JPG"],
Renames(Filed(card, plan.Sessions[1]), plan.Sessions[1].Title, fileTemplate));
}
[Test]
public async Task AWholeFolderOfTwoCamerasNamesEveryPhotoWithTheFirstOnesCamera()
{
var folder = Path.Combine(context.CreateTempDirectory("source"), "Etna");
TestPhotos.WriteSeries(folder, Start, 2, TimeSpan.FromSeconds(10), prefix: "CAN_");
TestPhotos.WriteSeries(folder, Start.AddSeconds(5), 2, TimeSpan.FromSeconds(10), firstSeed: 40, prefix: "NIK_", make: "NIKON CORPORATION", model: "NIKON Z 8");
const string fileTemplate = "{camera}_{n:0000}";
var plan = await PlanAsync(folder, context.CreateTempDirectory("archive"), new ImportOptions { Grouping = ImportGrouping.WholeFolder, FileTemplate = fileTemplate });
var session = plan.Sessions.Single();
Assert.Equal(2, session.Cameras);
Assert.SequenceEqual(["CAN_0001.JPG", "NIK_0001.JPG", "CAN_0002.JPG", "NIK_0002.JPG"], session.Items.Select(i => Path.GetFileName(i.SourcePath)));
// The sequence carries the first photo's camera, which names every photo of it, the second body's too: Reorganize agrees.
Assert.SequenceEqual(["Canon EOS R5_0001.JPG", "Canon EOS R5_0002.JPG", "Canon EOS R5_0003.JPG", "Canon EOS R5_0004.JPG"],
session.Items.Select(i => i.FileName));
Assert.Empty(Renames(Filed(folder, session), session.Title, fileTemplate));
}
[Test]
public async Task ALensChangedDuringASessionNamesItsPhotosAsTheirSequenceDoes()
{
@@ -89,6 +89,20 @@ public sealed class PathTemplateTests
Assert.Equal(keeps, parsed.ExpandFile(Frame).EndsWith(".CR2", StringComparison.Ordinal), parsed.ExpandFile(Frame));
}
[Test]
public void ALongNameIsShortenedBeforeItsExtension()
{
// A title as long as titles go: the number gives way, the extension never does.
var title = new string('a', 195);
var name = PathTemplate.Parse("{title}_{n:0000}.{ext}").ExpandFile(Frame with { Title = title });
Assert.Equal(title + "_.CR2", name);
Assert.Equal(PathTemplate.MaxSegmentLength, name.Length);
// Appended, the extension comes after the longest name.
Assert.Equal(title + "_0001.CR2", PathTemplate.Parse("{title}_{n:0000}").ExpandFile(Frame with { Title = title }));
// Short names are as they were.
Assert.Equal("Harbour sunset_0001.CR2", PathTemplate.Parse("{title}_{n:0000}.{ext}").ExpandFile(Frame));
}
[Theory]
[Case("{title} 2026", "Paris: night", "Paris: night 2026")]
[Case("{title} 2026", "24/7 roof", "24/7 roof 2026")]