fix(archive): Reorganize names as filing does and refuses templates that lose or hide photos

Reorganize with the archive's own templates planned renames and moves for
photos just filed, and some templates could strip extensions, hide sequences
from scans or stall a dry run. Owner review 2, phase 4a findings.

- Filing and Reorganize share one context: uploads and imports name every
  photo with the sequence's camera and lens (its first photo's, or the
  creator's hint), an upload's folder from its first frame in the new
  sequence, and a missing capture time from the sequence start instead of
  the current time. The planner expands folder and title templates from the
  first frame in the sidecar ({name}, {ext}, {iso}...), never today's date.
- Titles expand as text (ExpandText): "Paris: night" stays as typed.
- A sequence whose sidecar cannot be read (torn, another sequence's) keeps
  its folder, title and names, listed with why, and so does every folder
  around it; the dry run reads every sidecar, nested ones included.
- Kept never gives one folder to two sequences of a plan whatever the case,
  and a case-only move onto another folder is refused instead of taken as
  done.
- Shared template rules (TemplateRules) for the server's Reorganize and
  archive settings and the desktop's fields: a file template must keep the
  photo's extension ("{n}{ext}" refused) and tell a session's photos apart;
  a folder template may not write a level scans skip (a leading dot,
  originals, proxies, exports). Levels a title gives are escaped with "_".
- {ext} comes from the file, or from the original name when the file lost
  a photo's extension, so a Reorganize can put it back.
- Unique names cost linear time (UniqueNames) with the same names as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 6c734777e01476881a3f34b3188571cc3f7150ab)
This commit is contained in:
Alby96 committed 2026-10-27 16:29:31 +01:00
1 parent 13c2ac321c
commit b253cac8d4
25 files changed
+777 -173

No files matched your search

+7 -6
View File
@@ -49,9 +49,10 @@ public sealed record FileRenamePlan(IReadOnlyList<FileRename> Moves, int Frames,
/// <summary>
/// Plans the new file names of a sequence's frames from a file template (Reorganize, owner review 2, R7; BRIEF §7.1, §12.5).
/// Frames are named in index order exactly as filing names them (<see cref="FrameNaming"/>); a name already given, or held
/// by a file that stays (a frame left alone, a file no frame lists), gets <c>_2</c>, <c>_3</c>… as filing does, so the same
/// frames, template and folder always give the same names. Only photos under <c>originals/</c> whose SHA-256 is known and
/// Frames are named in index order with the context an upload in capture order is filed with (<see cref="FrameNaming"/>,
/// which says where filing gave other names); a name already given, or held by a file that stays (a frame left alone, a file
/// no frame lists), gets <c>_2</c>, <c>_3</c>… as filing does, so the same frames, template and folder always give the same
/// names. Only photos under <c>originals/</c> whose SHA-256 is known and
/// whose file is there are renamed, each within its folder; the XMP companions of a photo follow it
/// (<see cref="FrameCompanions"/>; one named by a stem two frames share follows the first). The sidecar's frame order never
/// changes.
@@ -101,14 +102,14 @@ public static class FileRenames
var moves = new List<FileRename>();
var samples = new List<FileRename>();
var renamed = 0;
var names = new UniqueNames(taken);
foreach (var frame in eligible)
{
var own = companions[frame.Id];
var tails = own.ConvertAll(c => FrameCompanions.Tail(c, frame.File));
var directory = frame.File[..(frame.File.LastIndexOf('/') + 1)];
var file = FrameNaming.FileName(template, FrameNaming.Context(frame, manifest, title),
candidate => !taken.Contains(candidate) && tails.TrueForAll(t => !taken.Contains(Stem(candidate) + t)), directory);
taken.Add(file);
var file = names.Claim(directory + template.ExpandFile(FrameNaming.Context(frame, manifest, title)),
candidate => tails.TrueForAll(t => !taken.Contains(Stem(candidate) + t)));
foreach (var tail in tails) taken.Add(Stem(file) + tail);
if (string.Equals(file, frame.File, StringComparison.Ordinal)) continue;
var move = new FileRename(frame.Id, frame.File, file);
+112 -56
View File
@@ -8,11 +8,23 @@ using Chronos.Core.Naming;
namespace Chronos.Core.Archiving;
/// <summary>What the planner needs to know about a sequence to rename it.</summary>
/// <summary>
/// What the planner needs to know about a sequence to rename it. Without its sidecar (<see cref="Files"/>) the templates see
/// the index row's capture time, camera and lens, and a sequence without a capture time keeps its folder and title.
/// </summary>
public sealed record RenameSubject(Guid SequenceId, string Folder, string? Title, DateTime? FirstCapture, string? CameraMake, string? CameraModel, string? Lens)
{
/// <summary>The sidecar and the files beside its frames, which a file template renames; null when they cannot be read.</summary>
/// <summary>
/// The sidecar, whose first frame the folder and title templates see as filing saw it, and the files beside its frames,
/// which a file template renames (empty without one); null when it was not read, or could not be.
/// </summary>
public SequenceFiles? Files { get; init; }
/// <summary>
/// The sidecar could not be read, or belongs to another sequence: the sequence stays as it is, and so does every folder
/// it is inside, which could not take it along (<see cref="RenameBlock.Unreadable"/>).
/// </summary>
public bool Unreadable { get; init; }
}
/// <summary>A sequence's sidecar as read for a plan, and every file in the folders of its frames (<see cref="FileRenames.ListPresent"/>).</summary>
@@ -57,37 +69,26 @@ public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFol
/// </summary>
public sealed record RenameTemplates(string? Folder = null, string? File = null, string? Title = null)
{
private static readonly NamingContext Sample = new()
{
CapturedAt = new DateTime(2026, 9, 28, 18, 2, 11),
SessionStart = new DateTime(2026, 9, 28, 18, 2, 11),
CameraMake = "Canon",
CameraModel = "Canon EOS R5",
Lens = "RF15-35mm F2.8 L IS USM",
Iso = 100,
ExposureTime = 1.0 / 250,
FNumber = 8,
OriginalName = "IMG_4211",
Extension = "CR2",
Title = "Sunset",
};
private static readonly NamingContext Sample = TemplateRules.Sample()[0];
public bool IsEmpty => Folder is null && File is null && Title is null;
/// <summary>
/// The first template that cannot be used, by its API name (<c>folderTemplate</c>, <c>fileTemplate</c>,
/// <c>titleTemplate</c>): blank, not valid as the archive settings' templates (<see cref="PathTemplate.IsValid"/>), or
/// with a format a sample cannot be written with (<c>{date:%}</c>); null when every one given can.
/// <c>titleTemplate</c>): blank, not valid (<see cref="PathTemplate.IsValid"/>), with a format a sample cannot be written
/// with (<c>{date:%}</c>), expanding to nothing, or, for a folder or file template, breaking a rule of the archive's
/// templates (<see cref="TemplateRules"/>: a folder scans never enter; a slash, a lost extension or names that would
/// repeat); null when every one given can. The archive settings' templates are checked alike.
/// </summary>
public string? Problem()
{
if (Unusable(Folder, t => t.ExpandFolder(Sample))) return "folderTemplate";
if (Unusable(File, t => t.ExpandFile(Sample))) return "fileTemplate";
if (Unusable(Title, t => t.ExpandFile(Sample))) return "titleTemplate";
if (Unusable(Folder, t => t.ExpandFolder(Sample), TemplateRules.FolderRule)) return "folderTemplate";
if (Unusable(File, t => t.ExpandFile(Sample), TemplateRules.FileRule)) return "fileTemplate";
if (Unusable(Title, t => t.ExpandText(Sample))) return "titleTemplate";
return null;
}
private static bool Unusable(string? template, Func<PathTemplate, string> expand)
private static bool Unusable(string? template, Func<PathTemplate, string> expand, Func<PathTemplate, string?>? rule = null)
{
if (template is null) return false;
if (string.IsNullOrWhiteSpace(template)) return true;
@@ -95,7 +96,7 @@ public sealed record RenameTemplates(string? Folder = null, string? File = null,
if (!parsed.IsValid) return true;
try
{
return expand(parsed).Length == 0;
return expand(parsed).Length == 0 || rule?.Invoke(parsed) is not null;
}
catch (FormatException)
{
@@ -198,15 +199,17 @@ public static class RenamePlanner
{
/// <summary>
/// Expands <paramref name="titleTemplate"/> (where <c>{title}</c> is the current title) and then
/// <paramref name="folderTemplate"/> (where <c>{title}</c> 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)"….
/// With <paramref name="fileTemplate"/> every subject's frames get their names from it as filing names them
/// (<see cref="FileRenames.Plan"/>, with the new title), counted and sampled in its step, and the frames that keep
/// their names are listed there with the reason; a subject whose sidecar could not be read
/// (<see cref="RenameSubject.Files"/> null) keeps them all. Null templates leave that part unchanged; subjects without a
/// change produce no step, unless frames of theirs keep their names. A folder that moves takes the sequences inside
/// it along: each gets a <see cref="RenameStep.Carried"/> step after every move, so the index follows its files; a
/// selected sequence inside a moving folder that moves elsewhere leaves first.
/// <paramref name="folderTemplate"/> (where <c>{title}</c> is the new title) for every subject, from its first frame as
/// filing saw it (<see cref="FrameNaming.Context(SidecarFrame, SequenceManifest, string?)"/>); a title is text, not a file
/// name (<see cref="PathTemplate.ExpandText"/>). A target folder that is any current sequence folder, exists on disk or
/// was given to an earlier subject (whatever its case) gets " (2)", " (3)"…. With <paramref name="fileTemplate"/> every
/// subject's frames get their names from it as filing names them (<see cref="FileRenames.Plan"/>, with the new title),
/// counted and sampled in its step, and the frames that keep their names are listed there with the reason. A subject
/// whose sidecar could not be read (<see cref="RenameSubject.Unreadable"/>, or no <see cref="RenameSubject.Files"/> for a
/// file template) stays as it is, listed with the reason, and so does the folder of every subject it is inside. Null
/// templates leave that part unchanged; subjects without a change produce no step, unless frames of theirs keep their
/// names. A folder that moves takes the sequences inside it along: each gets a <see cref="RenameStep.Carried"/> step after
/// every move, so the index follows its files; a selected sequence inside a moving folder that moves elsewhere leaves first.
/// </summary>
/// <param name="occupied">Every sequence folder of the archive (renamed or not).</param>
/// <param name="nested">The archive's other sequences inside a subject's folder, with their titles.</param>
@@ -219,29 +222,41 @@ public static class RenamePlanner
var file = fileTemplate is null ? null : PathTemplate.Parse(fileTemplate);
var taken = occupied.ToList();
var claimed = new HashSet<string>(taken, StringComparer.OrdinalIgnoreCase);
// The folders given in this plan so far: Kept never gives one twice (two folders that differ only in case).
var given = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
bool Unreadable(RenameSubject s) => s.Unreadable || (file is not null && s.Files is null);
// A folder that holds a sequence whose sidecar cannot be read cannot take it along.
var stuck = subjects.Where(Unreadable).Concat((nested ?? []).Where(n => n.Unreadable)).ToList();
var blockers = new HashSet<Guid>();
var own = new List<RenameStep>(subjects.Count);
foreach (var s in subjects)
{
var context = new NamingContext
if (Unreadable(s))
{
CapturedAt = s.FirstCapture ?? DateTime.Today,
SessionStart = s.FirstCapture ?? DateTime.Today,
CameraMake = s.CameraMake,
CameraModel = s.CameraModel,
Lens = s.Lens,
Title = s.Title,
};
var newTitle = title is null ? s.Title : Blank(title.ExpandFile(context)) ?? s.Title;
own.Add(new RenameStep(s.SequenceId, s.Folder, s.Folder, s.Title, s.Title) { Blocked = [new RenameBlocked(RenameBlock.Unreadable, 0)] });
continue;
}
var context = Context(s);
var newTitle = title is null || context is null ? s.Title : Blank(title.ExpandText(context)) ?? s.Title;
var newFolder = s.Folder;
// The archive root itself (a folder adopted in place) cannot move; only its title changes.
if (folder is not null && s.Folder.Length > 0 && Blank(folder.ExpandFolder(context with { Title = newTitle })) is { } expanded
if (folder is not null && context is not null && s.Folder.Length > 0 && Blank(folder.ExpandFolder(context with { Title = newTitle })) is { } expanded
&& !expanded.Equals(s.Folder, StringComparison.Ordinal))
{
newFolder = Kept(s.Folder, expanded, taken) ?? Unique(expanded, claimed, existsOnDisk);
claimed.Add(newFolder);
var inside = stuck.Where(u => IsInside(s.Folder, u.Folder)).Select(u => u.SequenceId).ToList();
if (inside.Count > 0)
{
blockers.UnionWith(inside);
}
else
{
newFolder = Kept(s.Folder, expanded, taken, given) ?? Unique(expanded, claimed, existsOnDisk);
claimed.Add(newFolder);
given.Add(newFolder);
}
}
var step = new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle);
own.Add(file is null ? step : WithFiles(step, s.Files, file, newTitle));
own.Add(file is null ? step : WithFiles(step, s.Files!, file, newTitle));
}
var moving = own.Where(s => s.MovesFolder).ToList();
@@ -252,7 +267,12 @@ public static class RenamePlanner
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))))
// An unreadable sequence that kept a folder around it in place is listed with why, as an unreadable subject is.
var inner = (nested ?? []).Select(n => new RenameStep(n.SequenceId, n.Folder, n.Folder, n.Title, n.Title)
{
Blocked = n.Unreadable && blockers.Contains(n.SequenceId) ? [new RenameBlocked(RenameBlock.Unreadable, 0)] : [],
});
foreach (var step in own.Concat(inner))
{
// 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);
@@ -267,10 +287,43 @@ public static class RenamePlanner
return new RenamePlan(Guid.CreateVersion7(), archiveId, [.. steps.OrderBy(s => s.Order).Select(s => s.Step)]) { FileTemplate = fileTemplate, Subjects = [.. subjects.Select(s => s.SequenceId)] };
}
/// <summary>The step with the file renames of its sequence (<see cref="FileRenames.Plan"/>), or all its frames kept when its sidecar could not be read.</summary>
private static RenameStep WithFiles(RenameStep step, SequenceFiles? files, PathTemplate template, string? title)
/// <summary>
/// What the folder and title templates of a subject see: its first frame in its sidecar, as an upload filed it and as
/// Reorganize names its files (a sidecar without frames: when the sequence was made); without the sidecar, the index
/// row's capture time, camera and lens. Null when no time is known: never today's date, which would move the folder
/// again on another day.
/// </summary>
private static NamingContext? Context(RenameSubject s)
{
if (s.Files?.Manifest is { } manifest)
{
if (manifest.Frames.Count > 0) return FrameNaming.Context(manifest.Frames[0], manifest, s.Title);
var start = FrameNaming.SessionStart(manifest);
return new NamingContext
{
CapturedAt = start,
SessionStart = start,
CameraMake = manifest.Camera?.Make,
CameraModel = manifest.Camera?.Model,
Lens = manifest.Lens,
Title = s.Title,
};
}
if (s.FirstCapture is not { } first) return null;
return new NamingContext
{
CapturedAt = first,
SessionStart = first,
CameraMake = s.CameraMake,
CameraModel = s.CameraModel,
Lens = s.Lens,
Title = s.Title,
};
}
/// <summary>The step with the file renames of its sequence (<see cref="FileRenames.Plan"/>).</summary>
private static RenameStep WithFiles(RenameStep step, SequenceFiles files, PathTemplate template, string? title)
{
if (files is null) return step with { Blocked = [new RenameBlocked(RenameBlock.Unreadable, 0)] };
var plan = FileRenames.Plan(files.Manifest, title, template, files.Present);
return step with
{
@@ -293,7 +346,8 @@ public static class RenamePlanner
/// 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).
/// </summary>
/// <exception cref="IOException">The target is occupied by something else, or neither folder exists.</exception>
/// <exception cref="IOException">The target is occupied by something else (for a case-only change, a folder of its own
/// on a case-sensitive file system), or neither folder exists.</exception>
public static void MoveFolder(ArchivePaths archive, RenameStep step)
{
if (!step.MovesFolder) return;
@@ -302,7 +356,8 @@ public static class RenamePlanner
var caseOnly = step.FromFolder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase);
if (Directory.Exists(to) && (!caseOnly || HasExactName(to)))
{
if (Directory.Exists(from) && !caseOnly) throw new IOException($"Rename target {step.ToFolder} already exists.");
// Both names there: the target is another folder (for a case-only change, on a case-sensitive file system).
if (Directory.Exists(from) && (!caseOnly || HasExactName(from))) throw new IOException($"Rename target {step.ToFolder} already exists.");
return;
}
if (!Directory.Exists(from)) throw new DirectoryNotFoundException($"Sequence folder {step.FromFolder} is missing.");
@@ -328,11 +383,12 @@ public static class RenamePlanner
/// <summary>
/// The folder a sequence keeps (in the template's case) when it already is <paramref name="expanded"/>, or the
/// <c>" (n)"</c> of it that filing or an earlier Reorganize gave it beside another sequence of that name; null when it is
/// neither, or when another sequence holds that name exactly (a case-sensitive file system). Without it a sequence at
/// <c>2026-09-28 (2)</c> would be planned to <c>(3)</c>, its own folder being taken, and back to <c>(2)</c> by the
/// next Reorganize.
/// neither, when another sequence holds that name exactly (a case-sensitive file system), or when this plan already gave
/// it to another sequence (<paramref name="given"/>, whatever its case: <c>trip (2)</c> and <c>TRIP (2)</c> both keep
/// <c>Trip (2)</c> otherwise). Without it a sequence at <c>2026-09-28 (2)</c> would be planned to <c>(3)</c>, its own
/// folder being taken, and back to <c>(2)</c> by the next Reorganize.
/// </summary>
private static string? Kept(string current, string expanded, IReadOnlyList<string> occupied)
private static string? Kept(string current, string expanded, IReadOnlyList<string> occupied, IReadOnlySet<string> given)
{
string? same = null;
if (current.Equals(expanded, StringComparison.OrdinalIgnoreCase)) same = expanded;
@@ -341,7 +397,7 @@ public static class RenamePlanner
out var n) && n >= 2)
same = string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})");
// "(02)" is not a number Unique gives: that folder moves to a name of its own.
if (same is null || !same.Equals(current, StringComparison.OrdinalIgnoreCase)) return null;
if (same is null || !same.Equals(current, StringComparison.OrdinalIgnoreCase) || given.Contains(same)) return null;
return same.Equals(current, StringComparison.Ordinal) || !occupied.Any(o => o.Equals(same, StringComparison.Ordinal)) ? same : null;
}