Files
Chronos/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs
T
Alby96 eb2395d9b0 feat(archive): reorganize existing sequences with folder, file and title templates
Owner review 2, R7 asks for renaming and moving after import, on the web panel and the
desktop. This is the engine and the server API both UIs build on.

- FrameNaming (Core/Naming) is the one naming context and unique-name rule of a frame:
  imports, uploads and Reorganize now produce identical names (behaviour of the ingest and
  the import planner unchanged).
- RenamePlanner takes a file template: each step counts its renamed frames, shows the first
  three and the frames version they were planned at, and lists what keeps its name (photos
  in place outside originals/, never hashed, missing, unreadable sidecar). Names are given
  in index order with _2, _3 as filing does; XMP companions follow their photo.
- MassRenamer renames a step's files under the same leases after its folder moved, checks
  the frames version, journals .chronos/rename-files.json and moves files in two phases
  through temporary names so chains and swaps never meet; then sidecar, index
  (FrameRepository.RenameFilesAsync, both dialects) and journal. A failure puts every file
  back; a crash is completed by the next writer or the plan's resume, the index following.
  Plans a paused or cancelled job holds are left to that job.
- JobKind.Move gets MoveJobHandler: it plans again and applies only the confirmed plan
  (fingerprint and frames versions), with progress and checkpoints per sequence.
- POST /api/v1/archive/reorganize: dry run with the plan and its fingerprint, otherwise a
  202 move job; validated templates, audited, sequenceChanged reorganized events.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit aae1c3eb18ea932b4a6251c5e2a282b9295a5785)
2026-10-27 14:03:36 +01:00

227 lines
13 KiB
C#

using System.Text;
using Chronos.Core.Archiving;
using Chronos.Core.Naming;
using Chronos.Testing;
namespace Chronos.Core.Tests.Archiving;
/// <summary>Reorganize (owner review 2, R7): file names planned from a template, and the two-phase renames of a sequence's files.</summary>
[Category("archive")]
public sealed class ReorganizeTests(TestContext context)
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
/// <summary>Frames in index order, every one hashed, ten seconds apart.</summary>
private static SequenceManifest Sequence(params string[] files) => new()
{
Id = Guid.NewGuid(),
Camera = new SidecarCamera { Make = "Canon", Model = "Canon EOS R5" },
Versions = new ManifestVersions { Frames = 4 },
Frames = [.. files.Select((f, i) => new SidecarFrame
{
Id = Guid.NewGuid(),
I = i,
File = f,
Original = $"IMG_{i + 1:0000}{Path.GetExtension(f)}",
Sha256 = new string((char)('a' + i % 6), 64),
CapturedAt = Start.AddSeconds(10 * i),
})],
};
private static FileRenamePlan Plan(SequenceManifest manifest, string template, string? title = null, IEnumerable<string>? extra = null) =>
FileRenames.Plan(manifest, title, PathTemplate.Parse(template), [.. manifest.Frames.Select(f => f.File), .. extra ?? []]);
[Test]
public void FramesAreNamedInIndexOrderAndNamesTakenGetNumbersAsFilingDoes()
{
var manifest = Sequence("originals/c.JPG", "originals/a.JPG", "originals/b.JPG", "originals/d.JPG");
var plan = Plan(manifest, "{date}");
Assert.SequenceEqual(["originals/2026-09-28.JPG", "originals/2026-09-28_2.JPG", "originals/2026-09-28_3.JPG", "originals/2026-09-28_4.JPG"],
plan.Moves.Select(m => m.To));
Assert.SequenceEqual(manifest.Frames.Select(f => f.Id), plan.Moves.Select(m => m.FrameId));
Assert.Equal(4, plan.Frames);
Assert.SequenceEqual(plan.Moves.Take(FileRenames.SampleCount), plan.Samples);
Assert.Empty(plan.Blocked);
}
[Test]
public void AChainOfNamesIsPlannedAndAFileNoFrameListsKeepsItsName()
{
// Frame 1 now holds the name frame 0 gets, frame 2 the one frame 1 gets: 2→1, 3→2, 4→3. A file no frame lists holds "4".
var manifest = Sequence("originals/2.JPG", "originals/3.JPG", "originals/4.JPG");
var plan = Plan(manifest, "{n:0}");
Assert.SequenceEqual(["originals/2.JPG>originals/1.JPG", "originals/3.JPG>originals/2.JPG", "originals/4.JPG>originals/3.JPG"],
plan.Moves.Select(m => $"{m.From}>{m.To}"));
var stray = Plan(manifest, "{n:0}", extra: ["originals/1.jpg", "originals/notes.txt"]);
Assert.Equal("originals/1_2.JPG", stray.Moves[0].To);
}
[Test]
public void PhotosInPlaceUnhashedOrMissingKeepTheirNamesAndHoldThem()
{
var manifest = Sequence("IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0003.JPG", "originals/IMG_0004.JPG");
manifest = manifest with { Frames = [manifest.Frames[0], manifest.Frames[1] with { Sha256 = null }, manifest.Frames[2], manifest.Frames[3]] };
// The third photo is not on disk; the fourth would take its name.
var plan = FileRenames.Plan(manifest, "IMG_0003", PathTemplate.Parse("{title}"), ["IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0004.JPG"]);
Assert.SequenceEqual([(RenameBlock.InPlace, 1), (RenameBlock.Unhashed, 1), (RenameBlock.Missing, 1)], plan.Blocked.Select(b => (b.Reason, b.Frames)));
Assert.Equal("originals/IMG_0004.JPG>originals/IMG_0003_2.JPG", plan.Moves.Select(m => $"{m.From}>{m.To}").Single());
Assert.Equal(1, plan.Frames);
}
[Test]
public void CompanionsFollowTheirPhotoAndTheirNamesAreKeptFree()
{
var manifest = Sequence("originals/A.CR2", "originals/B.CR2");
var plan = Plan(manifest, "{n:0000}", extra: ["originals/A.xmp", "originals/B.CR2.xmp", "originals/0001.xmp"]);
// "0001.xmp" belongs to no frame: the first photo, whose companion would take it, gets the next free name.
Assert.SequenceEqual(["originals/A.CR2>originals/0001_2.CR2", "originals/A.xmp>originals/0001_2.xmp",
"originals/B.CR2>originals/0002.CR2", "originals/B.CR2.xmp>originals/0002.CR2.xmp"], plan.Moves.Select(m => $"{m.From}>{m.To}"));
Assert.SequenceEqual([false, true, false, true], plan.Moves.Select(m => m.Companion));
Assert.Equal(2, plan.Frames);
Assert.Count(2, plan.Samples);
}
[Test]
public void NamesGivenOnceStayAsTheyAre()
{
var manifest = Sequence("originals/x.JPG", "originals/y.JPG");
var plan = Plan(manifest, "{date}_{n:000}");
var renamed = FileRenameJournal.Applied(manifest, FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t"))!;
Assert.Equal(manifest.Versions.Frames + 1, renamed.Versions.Frames);
Assert.SequenceEqual(manifest.Frames.Select(f => f.Id), renamed.Frames.Select(f => f.Id));
Assert.Empty(Plan(renamed, "{date}_{n:000}").Moves);
Assert.Null(FileRenameJournal.Applied(renamed, FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t")));
}
[Test]
public void APlanWithAFileTemplateCountsSamplesAndListsWhatKeepsItsName()
{
var renamed = Sequence("originals/a.JPG", "originals/b.JPG");
var adopted = Sequence("a.JPG");
var subjects = new[]
{
new RenameSubject(renamed.Id, "s/one", "Trip", Start, "Canon", "Canon EOS R5", null) { Files = new SequenceFiles(renamed, [.. renamed.Frames.Select(f => f.File)]) },
new RenameSubject(adopted.Id, "s/two", "Adopted", Start, "Canon", "Canon EOS R5", null) { Files = new SequenceFiles(adopted, ["a.JPG"]) },
new RenameSubject(Guid.NewGuid(), "s/three", null, Start, "Canon", "Canon EOS R5", null),
};
var plan = RenamePlanner.Plan(Guid.NewGuid(), subjects, null, "{title} 2026", ["s/one", "s/two", "s/three"], _ => false, fileTemplate: "{title}_{n:00}");
Assert.Equal("{title}_{n:00}", plan.FileTemplate);
Assert.SequenceEqual(subjects.Select(s => s.SequenceId), plan.Subjects);
var one = plan.Steps.Single(s => s.SequenceId == renamed.Id);
Assert.Equal((2, 4), (one.FileChanges, one.FramesVersion));
// The new title names the files.
Assert.SequenceEqual(["originals/Trip 2026_01.JPG", "originals/Trip 2026_02.JPG"], one.FileSamples.Select(f => f.To));
var two = plan.Steps.Single(s => s.SequenceId == adopted.Id);
Assert.Equal((0, 0), (two.FileChanges, two.FramesVersion));
Assert.Equal((RenameBlock.InPlace, 1), (two.Blocked.Single().Reason, two.Blocked.Single().Frames));
Assert.True(two.Changes, "its title changes");
var three = plan.Steps.Single(s => s.SequenceId == subjects[2].SequenceId);
Assert.Equal(RenameBlock.Unreadable, three.Blocked.Single().Reason);
// Nothing but kept names: listed, changes nothing.
var keptOnly = RenamePlanner.Plan(Guid.NewGuid(), [subjects[1]], null, null, ["s/two"], _ => false, fileTemplate: "{n}");
Assert.False(keptOnly.Steps.Single().Changes);
}
[Test]
public void TheFingerprintFollowsWhatThePlanChanges()
{
var manifest = Sequence("originals/a.JPG");
RenamePlan Make(SequenceManifest m) => RenamePlanner.Plan(Guid.NewGuid(), [new RenameSubject(m.Id, "s", "T", Start, null, null, null)
{ Files = new SequenceFiles(m, [.. m.Frames.Select(f => f.File)]) }], null, null, ["s"], _ => false, fileTemplate: "{n:000}");
var plan = Make(manifest);
Assert.Equal(64, plan.Fingerprint().Length);
Assert.Equal(plan.Fingerprint(), Make(manifest).Fingerprint());
Assert.NotEqual(plan.Fingerprint(), Make(manifest with { Versions = new ManifestVersions { Frames = 5 } }).Fingerprint());
}
[Test]
public void TemplatesAreCheckedAsTheArchiveSettingsAre()
{
Assert.Null(new RenameTemplates("{year}/{title}", "{date}_{n}", "{title} 2026").Problem());
Assert.Equal("folderTemplate", new RenameTemplates(Folder: " ").Problem());
Assert.Equal("fileTemplate", new RenameTemplates(File: "{nope}").Problem());
Assert.Equal("fileTemplate", new RenameTemplates(File: "{date:%}").Problem());
Assert.Equal("titleTemplate", new RenameTemplates(Title: "{title").Problem());
Assert.True(new RenameTemplates().IsEmpty);
}
private SequencePaths Folder(out ArchivePaths archive)
{
archive = new ArchivePaths(context.CreateTempDirectory("archive"));
var sequence = archive.Sequence("s");
Directory.CreateDirectory(sequence.Originals);
Directory.CreateDirectory(sequence.MetaDirectory);
return sequence;
}
private static void Write(SequencePaths sequence, string file, string text) => File.WriteAllText(sequence.File(file), text, Encoding.UTF8);
private static string Read(SequencePaths sequence, string file) => File.ReadAllText(sequence.File(file), Encoding.UTF8);
[Test]
public void FilesMoveInTwoPhasesSoChainsAndSwapsNeverMeet()
{
var sequence = Folder(out _);
Write(sequence, "originals/a.jpg", "A");
Write(sequence, "originals/b.jpg", "B");
Write(sequence, "originals/c.jpg", "C");
Guid x = Guid.NewGuid(), y = Guid.NewGuid(), z = Guid.NewGuid();
// A swap (a↔b) and a chain into a name that frees up (c→a's place is taken by b, so c→d).
var journal = FileRenameJournal.Create(7, [new FileRename(x, "originals/a.jpg", "originals/b.jpg"), new FileRename(y, "originals/b.jpg", "originals/a.jpg"),
new FileRename(z, "originals/c.jpg", "originals/d.jpg")], "t1");
FileRenameJournal.Write(sequence, journal);
var done = FileRenameJournal.Run(sequence, journal);
Assert.Equal(2, done.Phase);
Assert.Equal(("A", "B", "C"), (Read(sequence, "originals/b.jpg"), Read(sequence, "originals/a.jpg"), Read(sequence, "originals/d.jpg")));
Assert.FileMissing(sequence.File("originals/c.jpg"));
Assert.True(journal.Files.All(f => !File.Exists(sequence.File(f.Temp))));
Assert.True(journal.Files.All(f => Path.GetFileName(f.Temp).StartsWith(".chronos-rename-t1-", StringComparison.Ordinal)), "hidden, never a photo");
}
[Test]
public void AFailedMovePutsEveryFileBackAndChangesNothing()
{
var sequence = Folder(out _);
Write(sequence, "originals/a.jpg", "A");
Write(sequence, "originals/b.jpg", "B");
var journal = FileRenameJournal.Create(1, [new FileRename(Guid.NewGuid(), "originals/a.jpg", "originals/x.jpg"),
new FileRename(Guid.NewGuid(), "originals/b.jpg", "originals/y.jpg")], "t2");
FileRenameJournal.Write(sequence, journal);
// Another file took the second name after the plan: nothing is written over it, and the first file goes back.
Write(sequence, "originals/y.jpg", "other");
Assert.Throws<IOException>(() => FileRenameJournal.Run(sequence, journal));
Assert.Equal(("A", "B", "other"), (Read(sequence, "originals/a.jpg"), Read(sequence, "originals/b.jpg"), Read(sequence, "originals/y.jpg")));
Assert.FileMissing(sequence.File("originals/x.jpg"));
Assert.Null(FileRenameJournal.Read(sequence));
}
[Theory]
[Case(1)]
[Case(2)]
public void ARenameACrashInterruptedIsCompleted(int phase)
{
var sequence = Folder(out _);
var manifest = Sequence("originals/2.jpg", "originals/3.jpg", "originals/4.jpg");
foreach (var f in manifest.Frames) Write(sequence, f.File, f.Id.ToString());
var plan = Plan(manifest, "{n:0}");
var journal = FileRenameJournal.Create(manifest.Versions.Frames, plan.Moves, "t3") with { Phase = phase };
FileRenameJournal.Write(sequence, journal);
// Phase 1: the first file reached its temporary name. Phase 2: every file did, and the first its new name.
File.Move(sequence.File(journal.Files[0].From), sequence.File(journal.Files[0].Temp));
if (phase == 2)
{
foreach (var f in journal.Files.Skip(1)) File.Move(sequence.File(f.From), sequence.File(f.Temp));
File.Move(sequence.File(journal.Files[0].Temp), sequence.File(journal.Files[0].To));
}
var recovered = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
Assert.SequenceEqual(["originals/1.jpg", "originals/2.jpg", "originals/3.jpg"], recovered.Frames.Select(f => f.File));
Assert.Equal(manifest.Versions.Frames + 1, recovered.Versions.Frames);
foreach (var f in recovered.Frames) Assert.Equal(f.Id.ToString(), Read(sequence, f.File));
Assert.FileMissing(sequence.File("originals/4.jpg"));
Assert.True(journal.Files.All(f => !File.Exists(sequence.File(f.Temp))));
}
}