A Reorganize with a file template failed its job at the step of a sequence
a camera was still uploading into, and its retry gave the rest up. Photos
changed since the plan now never refuse a step: that sequence keeps its file
names (FilesKept), its folder and title change as planned, the other steps go
on and the job ends with ReorganizeKept. The fingerprint, the job's
confirmation and the check under the leases pin file renames by their digest
instead of the frames version, so photos filed under the names the plan gives
them no longer make a dry run or a queued job stale.
- A step whose folder or files a template names after {title} checks the
title as a retitle does (RenameStep.NamedByTitle): no name comes from a
title edited since the plan.
- Recovery sends a photo that already took its new name back together with a
companion whose new name was taken, so the two never end up apart.
- ArchiveService.OpenAsync logs a NewerFormatException from resuming a plan
and keeps its journal, so a server still boots.
- Once a step's folder moved, every index row of the step follows it even
when a sidecar cannot be read or written; the step then fails for a retry.
- Job log lines and errors give the real reason for files kept busy (in use
or a new name taken) and for a sidecar of a newer format (new Newer
outcome; strings en and it).
- A plan an archive open completes tells sequenceChanged; the docs that
promised more than that are corrected.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit f8554b8af0828ab9b0ff128e694abacdd53e6fd7)
614 lines
37 KiB
C#
614 lines
37 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 TheTrashAndReorganizeFindTheSameCompanionsWhateverTheirCase()
|
|
{
|
|
var sequence = Folder(out _);
|
|
var manifest = Sequence("originals/A.CR2", "originals/B.CR2");
|
|
foreach (var file in new[] { "originals/A.CR2", "originals/B.CR2", "originals/a.XMP", "originals/b.cr2.Xmp", "originals/c.xmp" }) Write(sequence, file, file);
|
|
var present = FileRenames.ListPresent(sequence, manifest);
|
|
var plan = FileRenames.Plan(manifest, null, PathTemplate.Parse("{n:0000}"), present);
|
|
Assert.SequenceEqual(["originals/A.CR2>originals/0001.CR2", "originals/a.XMP>originals/0001.XMP", "originals/B.CR2>originals/0002.CR2",
|
|
"originals/b.cr2.Xmp>originals/0002.cr2.Xmp"], plan.Moves.Select(m => $"{m.From}>{m.To}"));
|
|
var index = new FrameCompanions.Index(sequence);
|
|
Assert.SequenceEqual(["originals/a.XMP"], index.Of("originals/A.CR2"));
|
|
Assert.SequenceEqual(["originals/b.cr2.Xmp"], index.Of("originals/B.CR2"));
|
|
Assert.SequenceEqual(plan.Moves.Where(m => m.Companion).Select(m => m.From), manifest.Frames.SelectMany(f => FrameCompanions.Of(sequence, f.File)));
|
|
}
|
|
|
|
[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 FoldersTheTemplateGaveAlreadyStayAndASecondRunPlansNothing()
|
|
{
|
|
// Two sequences of one day filed by the template, the second beside the first; a third elsewhere, a fourth whose
|
|
// folder differs only in case, a fifth with a number filing never gives.
|
|
const string Template = "{year}/{date} {title}";
|
|
RenameSubject At(string folder) => new(Guid.NewGuid(), folder, "Sunset", Start, null, null, null);
|
|
RenameSubject[] subjects = [At("2026/2026-09-28 Sunset"), At("2026/2026-09-28 Sunset (2)"), At("inbox/c"), At("2026/2026-09-28 sunset (4)"),
|
|
At("2026/2026-09-28 Sunset (03)")];
|
|
var plan = RenamePlanner.Plan(Guid.NewGuid(), subjects, Template, null, subjects.Select(s => s.Folder), _ => false);
|
|
Assert.SequenceEqual([(subjects[2].SequenceId, "2026/2026-09-28 Sunset (3)"), (subjects[3].SequenceId, "2026/2026-09-28 Sunset (4)"),
|
|
(subjects[4].SequenceId, "2026/2026-09-28 Sunset (5)")], plan.Steps.Select(s => (s.SequenceId, s.ToFolder)));
|
|
|
|
// Where the plan put them, the same template changes nothing.
|
|
var moved = plan.Steps.ToDictionary(s => s.SequenceId, s => s.ToFolder);
|
|
RenameSubject[] after = [.. subjects.Select(s => moved.TryGetValue(s.SequenceId, out var to) ? s with { Folder = to } : s)];
|
|
var onDisk = after.Select(s => s.Folder).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
|
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), after, Template, null, onDisk, onDisk.Contains).Steps);
|
|
// Nor in another order.
|
|
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), [.. after.Reverse()], Template, null, onDisk, onDisk.Contains).Steps);
|
|
}
|
|
|
|
[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());
|
|
// A photo received since under the name the plan gives it raises the frames version only: the plan is the one shown.
|
|
var received = manifest with
|
|
{
|
|
Versions = new ManifestVersions { Frames = 5 },
|
|
Frames = [.. manifest.Frames, manifest.Frames[0] with { Id = Guid.NewGuid(), I = 1, File = "originals/002.JPG", CapturedAt = Start.AddSeconds(10) }],
|
|
};
|
|
Assert.Equal(plan.Fingerprint(), Make(received).Fingerprint());
|
|
// One the plan would rename too, or a file renamed otherwise, is another plan.
|
|
Assert.NotEqual(plan.Fingerprint(), Make(received with { Frames = [.. received.Frames.SkipLast(1), received.Frames[1] with { File = "originals/b.JPG" }] }).Fingerprint());
|
|
Assert.NotEqual(plan.Fingerprint(), Make(manifest with { Frames = [manifest.Frames[0] with { File = "originals/c.JPG" }] }).Fingerprint());
|
|
}
|
|
|
|
[Test]
|
|
public void AStepNamedAfterTheTitleSaysSo()
|
|
{
|
|
var manifest = Sequence("originals/a.JPG");
|
|
RenameStep Step(string? folder, string? file) => RenamePlanner.Plan(Guid.NewGuid(), [new RenameSubject(manifest.Id, "s", "Roof", Start, null, null, null)
|
|
{ Files = new SequenceFiles(manifest, [.. manifest.Frames.Select(f => f.File)]) }], folder, null, ["s"], _ => false, fileTemplate: file).Steps.Single();
|
|
Assert.True(Step("moved/{TITLE}", null) is { MovesFolder: true, NamedByTitle: true, UsesTitle: true, Retitles: false });
|
|
Assert.True(Step(null, "{title}_{n:000}") is { FileChanges: 1, NamedByTitle: true, UsesTitle: true });
|
|
Assert.True(Step("moved/{date}", "{n:000}") is { MovesFolder: true, FileChanges: 1, NamedByTitle: false, UsesTitle: false });
|
|
}
|
|
|
|
[Test]
|
|
public void TemplatesAreCheckedAsTheArchiveSettingsAre()
|
|
{
|
|
Assert.Null(new RenameTemplates("{year}/{title}", "{date}_{n}", "{title} 2026").Problem());
|
|
Assert.Null(new RenameTemplates(File: "{name}.{ext}", Title: "Paris: {title}?").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);
|
|
}
|
|
|
|
[Theory]
|
|
[Case("{n}{ext}", "fileTemplate", "Extension")]
|
|
[Case("{date}_{n}_{ext}", "fileTemplate", "Extension")]
|
|
[Case("{title}", "fileTemplate", "NotUnique")]
|
|
[Case("{date}_{hm}", "fileTemplate", "NotUnique")]
|
|
[Case("{year}/{n}", "fileTemplate", "FileSeparator")]
|
|
[Case("Originals/{date:yyyy}/{title}", "folderTemplate", "ReservedFolder")]
|
|
[Case("{year}/exports", "folderTemplate", "ReservedFolder")]
|
|
[Case(".archive/{date}", "folderTemplate", "ReservedFolder")]
|
|
[Case("{date:.yyyy}", "folderTemplate", "ReservedFolder")]
|
|
public void TemplatesThatWouldLoseOrHidePhotosAreRefused(string template, string field, string rule)
|
|
{
|
|
var folder = field == "folderTemplate";
|
|
var templates = folder ? new RenameTemplates(Folder: template) : new RenameTemplates(File: template);
|
|
Assert.Equal(field, templates.Problem());
|
|
Assert.Equal(rule, folder ? TemplateRules.FolderRule(PathTemplate.Parse(template)) : TemplateRules.FileRule(PathTemplate.Parse(template)));
|
|
}
|
|
|
|
/// <summary>A sidecar of <paramref name="files"/>, each photo's first capture time <paramref name="first"/> (none when null), titled <paramref name="title"/>.</summary>
|
|
private static RenameSubject Filed(string folder, string? title, DateTime? first, params string[] files)
|
|
{
|
|
var manifest = Sequence(files) with { Title = title, Created = new DateTimeOffset(2026, 10, 1, 9, 30, 0, TimeSpan.Zero) };
|
|
manifest = manifest with { Frames = [.. manifest.Frames.Select(f => f with { CapturedAt = first?.AddSeconds(10 * f.I) })] };
|
|
return new RenameSubject(manifest.Id, folder, title, first, "Canon", "Canon EOS R5", null)
|
|
{
|
|
Files = new SequenceFiles(manifest, [.. manifest.Frames.Select(f => f.File)]),
|
|
};
|
|
}
|
|
|
|
[Theory]
|
|
[Case("{year}/{date} {ext}", "2026/2026-09-28 CR2", "2026/2026-09-28 JPG")]
|
|
[Case("{date} {name}", "2026-09-28 IMG_0001", "2026-09-28 IMG_0001 (2)")]
|
|
[Case("{year}/{date} {camera} {iso}", "2026/2026-09-28 Canon EOS R5", "2026/2026-09-28 Canon EOS R5 (2)")]
|
|
public void FoldersFiledFromTheFirstPhotoStayWhereFilingPutThem(string template, string raw, string jpeg)
|
|
{
|
|
// RAW and JPEG of one day, filed by the template from their first photo ({ext}, {name}… are that photo's).
|
|
RenameSubject[] subjects =
|
|
[
|
|
Filed(raw, null, Start, "originals/2026-09-28_0001.CR2", "originals/2026-09-28_0002.CR2"),
|
|
Filed(jpeg, null, Start, "originals/2026-09-28_0001.JPG", "originals/2026-09-28_0002.JPG"),
|
|
];
|
|
var folders = subjects.Select(s => s.Folder).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
|
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), subjects, template, null, folders, folders.Contains).Steps);
|
|
// The context filing saw: the folder each first frame gives.
|
|
var context = FrameNaming.Context(subjects[0].Files!.Manifest.Frames[0], subjects[0].Files!.Manifest, null);
|
|
Assert.Equal(raw.Replace(" (2)", string.Empty, StringComparison.Ordinal), PathTemplate.Parse(template).ExpandFolder(context));
|
|
}
|
|
|
|
[Test]
|
|
public void ASequenceWithoutACaptureTimeNeverTakesTodaysDate()
|
|
{
|
|
// No time in the sidecar: the day the sequence was made, as its files are named; no sidecar and no time: no move.
|
|
var timeless = Filed("inbox/a", null, null, "originals/a.JPG");
|
|
var plan = RenamePlanner.Plan(Guid.NewGuid(), [timeless], "{date}", null, ["inbox/a"], _ => false);
|
|
Assert.Equal("2026-10-01", plan.Steps.Single().ToFolder);
|
|
var row = new RenameSubject(Guid.NewGuid(), "inbox/b", "B", null, null, null, null);
|
|
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), [row], "{date}", "{title} {date}", ["inbox/b"], _ => false).Steps);
|
|
}
|
|
|
|
[Test]
|
|
public void ASequenceWhoseSidecarCannotBeReadStaysAsItIsAndSoDoesTheFolderAroundIt()
|
|
{
|
|
var a = Filed("a", "A", Start, "originals/a.JPG");
|
|
// Unreadable, titled as D: had it been planned, D would get " (2)".
|
|
var unreadable = new RenameSubject(Guid.NewGuid(), "u", "D", Start, null, null, null) { Unreadable = true };
|
|
var carrier = Filed("c", "C", Start, "originals/c.JPG");
|
|
var inner = new RenameSubject(Guid.NewGuid(), "c/n", "N", Start, null, null, null) { Unreadable = true };
|
|
var d = Filed("d", "D", Start, "originals/d.JPG");
|
|
var plan = RenamePlanner.Plan(Guid.NewGuid(), [a, unreadable, carrier, d], "moved/{title}", "{title} 2026", ["a", "u", "c", "c/n", "d"], _ => false,
|
|
[inner]);
|
|
var steps = plan.Steps.ToDictionary(s => s.SequenceId);
|
|
Assert.Equal(("moved/A 2026", "A 2026"), (steps[a.SequenceId].ToFolder, steps[a.SequenceId].ToTitle));
|
|
Assert.Equal(("moved/D 2026", "D 2026"), (steps[d.SequenceId].ToFolder, steps[d.SequenceId].ToTitle));
|
|
foreach (var kept in new[] { unreadable, inner })
|
|
{
|
|
var step = steps[kept.SequenceId];
|
|
Assert.Equal((kept.Folder, kept.Title), (step.ToFolder, step.ToTitle));
|
|
Assert.False(step.Changes);
|
|
Assert.Equal(RenameBlock.Unreadable, step.Blocked.Single().Reason);
|
|
}
|
|
// Its own sidecar reads: the title changes, the folder cannot take the sequence inside along.
|
|
Assert.Equal(("c", "C 2026"), (steps[carrier.SequenceId].ToFolder, steps[carrier.SequenceId].ToTitle));
|
|
Assert.False(steps[inner.SequenceId].Carried);
|
|
|
|
// With a file template, a sequence without its sidecar's files stays too.
|
|
var noFiles = new RenameSubject(Guid.NewGuid(), "x", "X", Start, null, null, null);
|
|
var files = RenamePlanner.Plan(Guid.NewGuid(), [noFiles], "moved/{title}", null, ["x"], _ => false, fileTemplate: "{n}");
|
|
Assert.Equal(("x", false), (files.Steps.Single().ToFolder, files.Steps.Single().Changes));
|
|
}
|
|
|
|
[Test]
|
|
public void AFolderATitleWouldHideFromScansIsEscapedAndFound()
|
|
{
|
|
var archive = new ArchivePaths(context.CreateTempDirectory("archive"));
|
|
var originals = archive.FromRelative("inbox/a/originals");
|
|
Directory.CreateDirectory(originals);
|
|
File.WriteAllBytes(Path.Combine(originals, "IMG_0001.JPG"), TestPhotos.Jpeg(Start, 1));
|
|
var subject = new RenameSubject(Guid.NewGuid(), "inbox/a", "Exports", Start, null, null, null);
|
|
var step = RenamePlanner.Plan(Guid.NewGuid(), [subject], "{year}/{title}", null, ["inbox/a"], _ => false).Steps.Single();
|
|
Assert.Equal("2026/_Exports", step.ToFolder);
|
|
RenamePlanner.MoveFolder(archive, step);
|
|
Assert.SequenceEqual(["2026/_Exports"], ArchiveScanner.FindSequenceFolders(archive).Select(f => f.RelativeFolder));
|
|
}
|
|
|
|
[Test]
|
|
public void TitlesKeepWhatAFileNameCannotHold()
|
|
{
|
|
var paris = new RenameSubject(Guid.NewGuid(), "s/paris", "Paris: night", Start, null, null, null);
|
|
var plan = RenamePlanner.Plan(Guid.NewGuid(), [paris], "{title}", "{title} 2026", ["s/paris"], _ => false);
|
|
// The title is text; the folder it names is a file name.
|
|
Assert.Equal(("Paris: night 2026", "Paris_ night 2026"), (plan.Steps.Single().ToTitle, plan.Steps.Single().ToFolder));
|
|
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), [paris with { Folder = "Paris_ night" }], "{title}", "{title}", ["Paris_ night"], _ => false).Steps);
|
|
}
|
|
|
|
[Test]
|
|
public void TwoFoldersThatDifferOnlyInCaseAreNeverGivenOneFolder()
|
|
{
|
|
// A case-sensitive server: "trip (2)" and "TRIP (2)" are two folders, both of which "Trip (2)" would keep.
|
|
RenameSubject At(string folder) => new(Guid.NewGuid(), folder, "Trip", Start, null, null, null);
|
|
RenameSubject[] subjects = [At("trip (2)"), At("TRIP (2)")];
|
|
var onDisk = new HashSet<string>(["trip (2)", "TRIP (2)"], StringComparer.Ordinal);
|
|
var plan = RenamePlanner.Plan(Guid.NewGuid(), subjects, "{title}", null, onDisk, onDisk.Contains);
|
|
var targets = plan.Steps.Select(s => s.ToFolder).ToList();
|
|
Assert.SequenceEqual(["Trip (2)", "Trip"], targets);
|
|
|
|
// Where they went, the same template changes nothing.
|
|
RenameSubject[] after = [.. subjects.Zip(targets, (s, t) => s with { Folder = t })];
|
|
var moved = new HashSet<string>(targets, StringComparer.Ordinal);
|
|
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), after, "{title}", null, moved, moved.Contains).Steps);
|
|
}
|
|
|
|
[Test]
|
|
public void ACaseOnlyMoveOntoAnotherFolderIsRefused()
|
|
{
|
|
var archive = new ArchivePaths(context.CreateTempDirectory("archive"));
|
|
Directory.CreateDirectory(archive.FromRelative("trip (2)"));
|
|
File.WriteAllText(Path.Combine(archive.FromRelative("trip (2)"), "a.txt"), "a");
|
|
var step = new RenameStep(Guid.NewGuid(), "trip (2)", "Trip (2)", "Trip", "Trip");
|
|
if (Directory.Exists(archive.FromRelative("TRIP (2)")))
|
|
{
|
|
// Case-insensitive: the folder takes the new case, and the step repeated finds it done.
|
|
RenamePlanner.MoveFolder(archive, step);
|
|
RenamePlanner.MoveFolder(archive, step);
|
|
Assert.SequenceEqual(["Trip (2)"], Directory.EnumerateDirectories(archive.Root).Select(Path.GetFileName));
|
|
Assert.Equal("a", File.ReadAllText(Path.Combine(archive.FromRelative("Trip (2)"), "a.txt")));
|
|
}
|
|
else
|
|
{
|
|
// Case-sensitive: another folder holds the new name exactly; neither moves.
|
|
Directory.CreateDirectory(archive.FromRelative("Trip (2)"));
|
|
Assert.Throws<IOException>(() => RenamePlanner.MoveFolder(archive, step));
|
|
Assert.Equal("a", File.ReadAllText(Path.Combine(archive.FromRelative("trip (2)"), "a.txt")));
|
|
Assert.Empty(Directory.EnumerateFileSystemEntries(archive.FromRelative("Trip (2)")));
|
|
}
|
|
}
|
|
|
|
[Test]
|
|
public void ExtensionsAPhotoLostComeBackFromItsName()
|
|
{
|
|
var manifest = Sequence("originals/0001CR3", "originals/0002.CR3");
|
|
manifest = manifest with { Frames = [.. manifest.Frames.Select(f => f with { Original = $"IMG_{f.I + 1:0000}.CR3" })] };
|
|
Assert.Equal("CR3", FrameNaming.Context(manifest.Frames[0], manifest, null).Extension);
|
|
Assert.SequenceEqual(["originals/0001CR3>originals/0001.CR3"], Plan(manifest, "{n:0000}").Moves.Select(m => $"{m.From}>{m.To}"));
|
|
// A file that has an extension of a photo keeps that one, whatever the card's name said.
|
|
Assert.Equal("CR3", FrameNaming.Context(manifest.Frames[1] with { Original = "IMG_0002.JPG" }, manifest, null).Extension);
|
|
}
|
|
|
|
[Test]
|
|
public void ManyPhotosOfOneNameAreNamedInLinearTimeAsTheSearchFromTwoNamesThem()
|
|
{
|
|
// Against the search from _2 it replaces, with names taken by stray files and companions in the way.
|
|
var taken = new HashSet<string>(["a/x.JPG", "a/x_3.JPG", "a/x_4.xmp"], StringComparer.OrdinalIgnoreCase);
|
|
var reference = new HashSet<string>(taken, StringComparer.OrdinalIgnoreCase);
|
|
var names = new UniqueNames(taken);
|
|
for (var i = 0; i < 12; i++)
|
|
{
|
|
// 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));
|
|
reference.Add(expected);
|
|
Assert.Equal(expected, names.Claim("a/x.JPG", companion), $"photo {i}");
|
|
}
|
|
|
|
var frames = Enumerable.Range(0, 20_000).Select(i => $"originals/{i:00000}.JPG").ToArray();
|
|
var manifest = Sequence(frames);
|
|
var clock = System.Diagnostics.Stopwatch.StartNew();
|
|
var plan = Plan(manifest, "{title}", title: "Sunset");
|
|
Assert.True(clock.Elapsed.TotalSeconds < TestTiming.Budget(5), $"{clock.Elapsed.TotalSeconds:0.0} s");
|
|
Assert.SequenceEqual(["originals/Sunset.JPG", "originals/Sunset_2.JPG", "originals/Sunset_3.JPG"], plan.Samples.Select(s => s.To));
|
|
Assert.Equal("originals/Sunset_20000.JPG", plan.Moves[^1].To);
|
|
}
|
|
|
|
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))));
|
|
}
|
|
|
|
/// <summary>
|
|
/// A rename of <paramref name="shape"/> (a chain of names that free up, a swap, a cycle of three) a crash interrupted
|
|
/// in its first phase, once its first file reached its temporary name; each file holds its frame's id.
|
|
/// </summary>
|
|
private static (SequenceManifest Manifest, FileRenameJournal Journal) Interrupted(SequencePaths sequence, string shape)
|
|
{
|
|
string[][] names = shape switch
|
|
{
|
|
"chain" => [["originals/2.jpg", "originals/3.jpg", "originals/4.jpg"], ["originals/1.jpg", "originals/2.jpg", "originals/3.jpg"]],
|
|
"swap" => [["originals/a.jpg", "originals/b.jpg"], ["originals/b.jpg", "originals/a.jpg"]],
|
|
_ => [["originals/a.jpg", "originals/b.jpg", "originals/c.jpg"], ["originals/b.jpg", "originals/c.jpg", "originals/a.jpg"]],
|
|
};
|
|
var (from, to) = (names[0], names[1]);
|
|
var manifest = Sequence(from);
|
|
foreach (var f in manifest.Frames) Write(sequence, f.File, f.Id.ToString());
|
|
var journal = FileRenameJournal.Create(manifest.Versions.Frames, [.. manifest.Frames.Select((f, i) => new FileRename(f.Id, f.File, to[i]))], "t4");
|
|
FileRenameJournal.Write(sequence, journal);
|
|
File.Move(sequence.File(journal.Files[0].From), sequence.File(journal.Files[0].Temp));
|
|
return (manifest, journal);
|
|
}
|
|
|
|
private static void AssertEveryFrameHoldsItsPhoto(SequencePaths sequence, SequenceManifest recovered)
|
|
{
|
|
foreach (var f in recovered.Frames) Assert.Equal(f.Id.ToString(), Read(sequence, f.File));
|
|
Assert.Empty(Directory.EnumerateFiles(sequence.Originals, ".chronos-rename-*"));
|
|
}
|
|
|
|
[Theory]
|
|
[Case("chain")]
|
|
[Case("swap")]
|
|
[Case("cycle")]
|
|
public void ARecoveryRunAgainLeavesEveryFileWithItsFrame(string shape)
|
|
{
|
|
var sequence = Folder(out _);
|
|
var (manifest, _) = Interrupted(sequence, shape);
|
|
// Completed, but the sidecar that follows was never written (a full disk, a crash before it): the journal is found again.
|
|
var first = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
|
|
Assert.Equal(2, Assert.NotNull(FileRenameJournal.Read(sequence)).Phase);
|
|
var again = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
|
|
Assert.SequenceEqual(first.Frames.Select(f => f.File), again.Frames.Select(f => f.File));
|
|
Assert.False(manifest.Frames.Select(f => f.File).SequenceEqual(again.Frames.Select(f => f.File)), "every frame has its new name");
|
|
AssertEveryFrameHoldsItsPhoto(sequence, again);
|
|
}
|
|
|
|
[Test]
|
|
[WindowsOnly]
|
|
public void ARecoveryCutShortWhileFilesTakeTheirNewNamesGoesOnFromThere()
|
|
{
|
|
var sequence = Folder(out _);
|
|
var (manifest, journal) = Interrupted(sequence, "chain");
|
|
// The last file reached its temporary name too, and another program holds it: the recovery stops at it.
|
|
File.Move(sequence.File(journal.Files[2].From), sequence.File(journal.Files[2].Temp));
|
|
using (new FileStream(sequence.File(journal.Files[2].Temp), FileMode.Open, FileAccess.Read, FileShare.None))
|
|
Assert.Throws<IOException>(() => FileRenameJournal.Recover(sequence, manifest));
|
|
Assert.Equal("originals/1.jpg", journal.Files[0].To);
|
|
Assert.Equal(manifest.Frames[0].Id.ToString(), Read(sequence, "originals/1.jpg"));
|
|
|
|
// Run again, it goes on from there: no file that took its new name moves again.
|
|
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));
|
|
AssertEveryFrameHoldsItsPhoto(sequence, recovered);
|
|
}
|
|
|
|
[Test]
|
|
public void ANewNameTakenMeanwhileNeverStrandsAPhoto()
|
|
{
|
|
var sequence = Folder(out _);
|
|
var (manifest, journal) = Interrupted(sequence, "chain");
|
|
// Copied in under the name the second file gets after the crash: never written over. Its own old name is the third
|
|
// file's new one, so it takes the first free number of that name.
|
|
Write(sequence, "originals/2.jpg", "other");
|
|
FileRenameJournal.Delete(sequence);
|
|
Assert.NotNull(FileRenameJournal.Read(sequence));
|
|
|
|
var recovered = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
|
|
Assert.SequenceEqual(["originals/1.jpg", "originals/3_2.jpg", "originals/3.jpg"], recovered.Frames.Select(f => f.File));
|
|
Assert.Equal("other", Read(sequence, "originals/2.jpg"));
|
|
AssertEveryFrameHoldsItsPhoto(sequence, recovered);
|
|
// The new name is in the journal, so a recovery run again finds every file where it is.
|
|
Assert.Equal("originals/3_2.jpg", Assert.NotNull(FileRenameJournal.Read(sequence)).Files[1].To);
|
|
Assert.SequenceEqual(recovered.Frames.Select(f => f.File), Assert.NotNull(FileRenameJournal.Recover(sequence, manifest)).Frames.Select(f => f.File));
|
|
AssertEveryFrameHoldsItsPhoto(sequence, recovered);
|
|
Assert.Equal(journal.Files.Count, Directory.EnumerateFiles(sequence.Originals).Count() - 1);
|
|
}
|
|
|
|
[Test]
|
|
public void APhotoWhoseCompanionsNewNameIsTakenStaysWithItsCompanion()
|
|
{
|
|
var sequence = Folder(out _);
|
|
var manifest = Sequence("originals/A.CR2");
|
|
Write(sequence, "originals/A.CR2", "photo");
|
|
Write(sequence, "originals/A.xmp", "sidecar");
|
|
var id = manifest.Frames[0].Id;
|
|
FileRename[] moves = [new(id, "originals/A.CR2", "originals/0001.CR2"), new(id, "originals/A.xmp", "originals/0001.xmp", Companion: true)];
|
|
var journal = FileRenameJournal.Create(manifest.Versions.Frames, moves, "t5") with { Phase = 2 };
|
|
FileRenameJournal.Write(sequence, journal);
|
|
foreach (var f in journal.Files) File.Move(sequence.File(f.From), sequence.File(f.Temp));
|
|
Write(sequence, "originals/0001.xmp", "other");
|
|
|
|
// Both go back to their names, together; the frame keeps its file.
|
|
Assert.Null(FileRenameJournal.Recover(sequence, manifest));
|
|
Assert.Equal(("photo", "sidecar", "other"), (Read(sequence, "originals/A.CR2"), Read(sequence, "originals/A.xmp"), Read(sequence, "originals/0001.xmp")));
|
|
Assert.FileMissing(sequence.File("originals/0001.CR2"));
|
|
Assert.Empty(Directory.EnumerateFiles(sequence.Originals, ".chronos-rename-*"));
|
|
}
|
|
|
|
[Test]
|
|
public void APhotoThatTookItsNewNameGoesBackWithACompanionWhoseNewNameIsTaken()
|
|
{
|
|
var sequence = Folder(out _);
|
|
var manifest = Sequence("originals/A.CR2");
|
|
Write(sequence, "originals/A.CR2", "photo");
|
|
Write(sequence, "originals/A.xmp", "sidecar");
|
|
var id = manifest.Frames[0].Id;
|
|
FileRename[] moves = [new(id, "originals/A.CR2", "originals/0001.CR2"), new(id, "originals/A.xmp", "originals/0001.xmp", Companion: true)];
|
|
var journal = FileRenameJournal.Create(manifest.Versions.Frames, moves, "t6") with { Phase = 2 };
|
|
FileRenameJournal.Write(sequence, journal);
|
|
foreach (var f in journal.Files) File.Move(sequence.File(f.From), sequence.File(f.Temp));
|
|
// Stopped once the photo took its new name, before its companion did; then something took the companion's, and the
|
|
// photo's old name too.
|
|
File.Move(sequence.File(journal.Files[0].Temp), sequence.File(journal.Files[0].To));
|
|
Write(sequence, "originals/0001.xmp", "other");
|
|
Write(sequence, "originals/A.CR2", "another");
|
|
|
|
// The photo goes back with its companion, both to the first free number of its old name; the frame names the photo.
|
|
var recovered = Assert.NotNull(FileRenameJournal.Recover(sequence, manifest));
|
|
Assert.Equal("originals/A_2.CR2", recovered.Frames.Single().File);
|
|
Assert.Equal(("photo", "sidecar"), (Read(sequence, "originals/A_2.CR2"), Read(sequence, "originals/A_2.xmp")));
|
|
Assert.Equal(("other", "another"), (Read(sequence, "originals/0001.xmp"), Read(sequence, "originals/A.CR2")));
|
|
Assert.FileMissing(sequence.File("originals/0001.CR2"));
|
|
Assert.Empty(Directory.EnumerateFiles(sequence.Originals, ".chronos-rename-*"));
|
|
// Run again, every file stays where it is.
|
|
Assert.Equal("originals/A_2.CR2", Assert.NotNull(FileRenameJournal.Recover(sequence, manifest)).Frames.Single().File);
|
|
Assert.Equal(("photo", "sidecar"), (Read(sequence, "originals/A_2.CR2"), Read(sequence, "originals/A_2.xmp")));
|
|
}
|
|
}
|