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

+8 -2
View File
@@ -5,7 +5,10 @@ using Chronos.Core.Naming;
namespace Chronos.Core.Archiving;
/// <summary>Why frames of a sequence keep their file names in a Reorganize (owner review 2, R7); nothing of them is touched.</summary>
/// <summary>
/// Why frames of a sequence keep their file names in a Reorganize (owner review 2, R7), nothing of them touched; or, for
/// <see cref="Unreadable"/>, why the whole sequence stays as it is.
/// </summary>
public enum RenameBlock
{
/// <summary>Photos adopted in place, outside <c>originals/</c>: they belong to a tree someone else keeps.</summary>
@@ -17,7 +20,10 @@ public enum RenameBlock
/// <summary>Photos whose file is not there.</summary>
Missing,
/// <summary>The sequence's sidecar cannot be read, is of a newer format this build does not rewrite, or belongs to another sequence.</summary>
/// <summary>
/// The sequence's sidecar cannot be read, is of a newer format this build does not rewrite, or belongs to another
/// sequence: the sequence keeps its folder, title and file names, and so does every folder it is inside (0 frames).
/// </summary>
Unreadable,
}
+73 -29
View File
@@ -32,7 +32,8 @@ public sealed record SequenceFiles(SequenceManifest Manifest, IReadOnlyCollectio
/// <summary>
/// One sequence's change: its folder, its title, the names of its files (Reorganize, owner review 2, R7), or several of
/// them. A step that changes nothing lists only why files keep their names (<see cref="Blocked"/>).
/// them. A step that changes nothing lists only why: frames that keep their file names, or a sequence that stays as it is
/// because its sidecar cannot be read (<see cref="Blocked"/>).
/// </summary>
/// <param name="Carried">The folder moves only because a folder it is inside moves (a sequence nested in another).</param>
public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFolder, string? FromTitle, string? ToTitle, bool Carried = false)
@@ -71,7 +72,7 @@ public sealed record RenameStep(Guid SequenceId, string FromFolder, string ToFol
/// </summary>
public string? FileDigest { get; init; }
/// <summary>Frames that keep their file names, and why.</summary>
/// <summary>Frames that keep their file names, and why; <see cref="RenameBlock.Unreadable"/> (0 frames) when the whole sequence stays as it is.</summary>
public IReadOnlyList<RenameBlocked> Blocked { get; init; } = [];
}
@@ -90,33 +91,45 @@ public sealed record RenameTemplates(string? Folder = null, string? File = null,
/// <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.
/// repeat); null when every one given can. The archive settings' templates are checked alike
/// (<c>ArchiveSettings.Problem</c>).
/// </summary>
public string? Problem()
{
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;
}
public string? Problem() => Check()?.Field;
private static bool Unusable(string? template, Func<PathTemplate, string> expand, Func<PathTemplate, string?>? rule = null)
/// <summary>
/// The first template that cannot be used (<see cref="Problem"/>), with the rule of <see cref="TemplateRules"/> it breaks
/// when it parses and expands (<see cref="TemplateProblem.Rule"/>); null when every one given can.
/// </summary>
public TemplateProblem? Check() =>
Unusable("folderTemplate", Folder, t => t.ExpandFolder(Sample), TemplateRules.FolderRule)
?? Unusable("fileTemplate", File, t => t.ExpandFile(Sample), TemplateRules.FileRule)
?? Unusable("titleTemplate", Title, t => t.ExpandText(Sample));
private static TemplateProblem? Unusable(string field, string? template, Func<PathTemplate, string> expand, Func<PathTemplate, string?>? rule = null)
{
if (template is null) return false;
if (string.IsNullOrWhiteSpace(template)) return true;
if (template is null) return null;
if (string.IsNullOrWhiteSpace(template)) return new TemplateProblem(field, null);
var parsed = PathTemplate.Parse(template);
if (!parsed.IsValid) return true;
if (!parsed.IsValid) return new TemplateProblem(field, null);
try
{
return expand(parsed).Length == 0 || rule?.Invoke(parsed) is not null;
if (expand(parsed).Length == 0) return new TemplateProblem(field, null);
return rule?.Invoke(parsed) is { } broken ? new TemplateProblem(field, broken) : null;
}
catch (FormatException)
{
return true;
return new TemplateProblem(field, null);
}
}
}
/// <summary>
/// A template that cannot be used: its API name (<c>folderTemplate</c>, <c>fileTemplate</c>, <c>titleTemplate</c>) and the
/// rule of <see cref="TemplateRules"/> it breaks (<c>ReservedFolder</c>, <c>FileSeparator</c>, <c>Extension</c>,
/// <c>NotUnique</c>, each explained by <c>Errors.Template.&lt;Rule&gt;</c>); no rule when it is blank, not valid or expands to nothing.
/// </summary>
public sealed record TemplateProblem(string Field, string? Rule);
/// <summary>A planned folder would lie inside a sequence's folder (nesting one sequence in another); nothing is planned.</summary>
public sealed class NestedRenameException(string target, string folder)
: ArgumentException(Loc.L("Archive.Error.NestedTarget", target, folder))
@@ -219,7 +232,8 @@ public static class RenamePlanner
/// <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
/// was given to an earlier subject (whatever its case) gets " (2)", " (3)"…; a sequence keeps its own folder in the
/// template's case only while no other folder holds that exact name. 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 step whose
/// new folder or file names come from <c>{title}</c> says so (<see cref="RenameStep.NamedByTitle"/>). A subject
@@ -231,10 +245,15 @@ public static class RenamePlanner
/// </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>
/// <param name="existsExactly">Whether a folder of exactly that name, in every level's case, is on disk
/// (<see cref="ExistsExactly"/>): on a case-sensitive file system <c>Trip (2)</c> beside a sequence at <c>trip (2)</c> is
/// another folder, which a change of case could never move onto. Null when no folder but the sequences' own counts.</param>
/// <exception cref="NestedRenameException">A target lies inside a sequence's folder, or inside another target.</exception>
public static RenamePlan Plan(Guid archiveId, IReadOnlyList<RenameSubject> subjects, string? folderTemplate, string? titleTemplate,
IEnumerable<string> occupied, Func<string, bool> existsOnDisk, IReadOnlyList<RenameSubject>? nested = null, string? fileTemplate = null)
IEnumerable<string> occupied, Func<string, bool> existsOnDisk, IReadOnlyList<RenameSubject>? nested = null, string? fileTemplate = null,
Func<string, bool>? existsExactly = null)
{
existsExactly ??= _ => false;
var folder = folderTemplate is null ? null : PathTemplate.Parse(folderTemplate);
var title = titleTemplate is null ? null : PathTemplate.Parse(titleTemplate);
var file = fileTemplate is null ? null : PathTemplate.Parse(fileTemplate);
@@ -269,7 +288,7 @@ public static class RenamePlanner
}
else
{
newFolder = Kept(s.Folder, expanded, taken, given) ?? Unique(expanded, claimed, existsOnDisk);
newFolder = Kept(s.Folder, expanded, taken, given, existsExactly) ?? Unique(expanded, claimed, existsOnDisk);
claimed.Add(newFolder);
given.Add(newFolder);
}
@@ -367,17 +386,17 @@ public static class RenamePlanner
/// a case-only change goes through a temporary name (case-insensitive file systems).
/// </summary>
/// <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>
/// on a case-sensitive file system, which the plan and the apply refuse first), or neither folder exists.</exception>
public static void MoveFolder(ArchivePaths archive, RenameStep step)
{
if (!step.MovesFolder) return;
var from = archive.FromRelative(step.FromFolder);
var to = archive.FromRelative(step.ToFolder);
var caseOnly = step.FromFolder.Equals(step.ToFolder, StringComparison.OrdinalIgnoreCase);
if (Directory.Exists(to) && (!caseOnly || HasExactName(to)))
if (Directory.Exists(to) && (!caseOnly || ExistsExactly(archive, step.ToFolder)))
{
// 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.");
if (Directory.Exists(from) && (!caseOnly || ExistsExactly(archive, step.FromFolder))) throw new IOException($"Rename target {step.ToFolder} already exists.");
return;
}
if (!Directory.Exists(from)) throw new DirectoryNotFoundException($"Sequence folder {step.FromFolder} is missing.");
@@ -394,21 +413,45 @@ public static class RenamePlanner
}
}
private static bool HasExactName(string path) =>
Directory.EnumerateDirectories(Path.GetDirectoryName(path)!, Path.GetFileName(path))
.Any(d => Path.GetFileName(d).Equals(Path.GetFileName(path), StringComparison.Ordinal));
/// <summary>
/// Whether the folder <paramref name="folder"/> (archive-relative, forward slashes) is on disk with exactly that name at
/// every level. On a case-insensitive file system a folder whose name differs in case only does not count, so a change
/// of case only finds its own folder under its old name alone; on a case-sensitive one this is any folder of that name.
/// </summary>
public static bool ExistsExactly(ArchivePaths archive, string folder)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(folder);
var path = archive.Root;
var options = new EnumerationOptions { MatchType = MatchType.Simple, AttributesToSkip = 0, IgnoreInaccessible = true };
foreach (var name in folder.Split('/', StringSplitOptions.RemoveEmptyEntries))
{
try
{
// The name as a pattern finds it whatever its case on Windows; only the exact one counts.
if (!Directory.EnumerateDirectories(path, name, options).Any(d => Path.GetFileName(d).Equals(name, StringComparison.Ordinal))) return false;
}
catch (DirectoryNotFoundException)
{
return false;
}
path = Path.Combine(path, name);
}
return Directory.Exists(path);
}
private static string? Blank(string value) => string.IsNullOrWhiteSpace(value) ? null : value;
/// <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, 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
/// neither, when another folder holds that name exactly (a sequence's, or any on a case-sensitive file system:
/// <paramref name="existsExactly"/>), which the change of case could never move onto, 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, IReadOnlySet<string> given)
private static string? Kept(string current, string expanded, IReadOnlyList<string> occupied, IReadOnlySet<string> given, Func<string, bool> existsExactly)
{
string? same = null;
if (current.Equals(expanded, StringComparison.OrdinalIgnoreCase)) same = expanded;
@@ -418,7 +461,8 @@ public static class RenamePlanner
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) || given.Contains(same)) return null;
return same.Equals(current, StringComparison.Ordinal) || !occupied.Any(o => o.Equals(same, StringComparison.Ordinal)) ? same : null;
if (same.Equals(current, StringComparison.Ordinal)) return same;
return occupied.Any(o => o.Equals(same, StringComparison.Ordinal)) || existsExactly(same) ? null : same;
}
private static string Unique(string folder, HashSet<string> claimed, Func<string, bool> existsOnDisk)