Files
Chronos/src/Chronos.Core/Archiving/MassRename.cs
T
Alby96andClaude Opus 5.5 7e4a3b481d
CI / Build and test (push) Successful in 9m15s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 15m35s
CI / PostgreSQL 16 integration (push) Successful in 7m26s
CI / PostgreSQL 17 integration (push) Successful in 6m47s
CI / Docker image (push) Successful in 59s
Release / Server image (push) Successful in 1m24s
feat: owner review 2 phase 4a: Reorganize sequences after import (#12)
- Reorganize… on the web panel and the desktop: folder, file and title templates applied to existing sequences, with a dry run and an explicit Apply that runs as a job.
- One naming rule (FrameNaming) for import, upload and Reorganize.
- Crash-safe plan and file journals, held plans, stale-plan refusal; exports move with their folder.
- Writers refuse a folder another program moved or gave to another sequence.
- Server: POST /api/v1/archive/reorganize with a bounded plan cache; template rules.
- Phase 3 docs and translations merged; strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-10-27 21:58:39 +01:00

566 lines
33 KiB
C#

using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Naming;
namespace Chronos.Core.Archiving;
/// <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, 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>
public sealed record SequenceFiles(SequenceManifest Manifest, IReadOnlyCollection<string> Present);
/// <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: 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)
{
public bool MovesFolder => !string.Equals(FromFolder, ToFolder, StringComparison.Ordinal);
public bool Retitles => !string.Equals(FromTitle, ToTitle, StringComparison.Ordinal);
/// <summary>Whether applying the step changes anything: the folder, the title or file names.</summary>
public bool Changes => MovesFolder || Retitles || FileChanges > 0;
/// <summary>
/// The new folder or file names come from the sequence's title (the folder or file template uses <c>{title}</c>): a title
/// edited since the plan would leave them named after the old one.
/// </summary>
public bool NamedByTitle { get; init; }
/// <summary>Whether what the step changes depends on the sequence's title: it changes it, or names the folder or files after it.</summary>
public bool UsesTitle => Retitles || NamedByTitle;
/// <summary>
/// The sidecar's frames version the file names were planned at; 0 when no file gets a new name. What the apply checks the
/// files by only in a plan journaled without <see cref="FileDigest"/>.
/// </summary>
public int FramesVersion { get; init; }
/// <summary>Frames whose file gets a new name (their companions follow them).</summary>
public int FileChanges { get; init; }
/// <summary>The first renamed frames (<see cref="FileRenames.SampleCount"/>), old and new name relative to the sequence folder.</summary>
public IReadOnlyList<FileRename> FileSamples { get; init; } = [];
/// <summary>
/// Every file rename of the step, as a digest (<see cref="FileRenamePlan.Digest"/>): the apply renames the files only
/// while they plan to exactly these. Null when no file gets a new name (or in a plan journaled before it existed).
/// </summary>
public string? FileDigest { get; init; }
/// <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; } = [];
}
/// <summary>
/// The templates of a Reorganize (owner review 2, R7): the folder (<c>{title}</c> = the new title), the file names and the
/// title (<c>{title}</c> = the current title); null leaves that part as it is.
/// </summary>
public sealed record RenameTemplates(string? Folder = null, string? File = null, string? Title = null)
{
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 (<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, except for the rules a
/// template <c>archive.json</c> already holds breaks (<c>ArchiveSettings.Problem</c>).
/// </summary>
public string? Problem() => Check()?.Field;
/// <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 null;
if (string.IsNullOrWhiteSpace(template)) return new TemplateProblem(field, null);
var parsed = PathTemplate.Parse(template);
if (!parsed.IsValid) return new TemplateProblem(field, null);
try
{
if (expand(parsed).Length == 0) return new TemplateProblem(field, null);
return rule?.Invoke(parsed) is { } broken ? new TemplateProblem(field, broken) : null;
}
catch (FormatException)
{
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))
{
public string Target { get; } = target;
public string Folder { get; } = folder;
}
/// <summary>The exact changes a mass rename will make (its dry run); applying it makes exactly these.</summary>
public sealed record RenamePlan(Guid Id, Guid ArchiveId, IReadOnlyList<RenameStep> Steps)
{
/// <summary>The file template the steps' file names come from; null when files keep their names.</summary>
public string? FileTemplate { get; init; }
/// <summary>
/// The folder template the steps' folders come from; null when folders stay, or in a plan journaled before it was kept
/// (whose steps' folders are then taken as planned).
/// </summary>
public string? FolderTemplate { get; init; }
/// <summary>The title template the steps' titles come from; null when titles stay, or in a plan journaled before it was kept.</summary>
public string? TitleTemplate { get; init; }
/// <summary>The sequences the plan was made for, in the order they were given (the order that decides which new folder gets " (2)").</summary>
public IReadOnlyList<Guid> Subjects { get; init; } = [];
/// <summary>
/// A digest of what the plan changes (its steps in order, as a dry run shows them, every file rename by its digest, and
/// the file template), the same for two plans of the same archive state: what a confirmation sends back so the change
/// made is the one that was shown. The frames version is not part of it: photos a sequence received since under the names
/// the plan gives them (an upload filed with the same template) leave the plan as it was, and the apply renames the files
/// only while they rename exactly as planned (<see cref="RenameStep.FileDigest"/>).
/// </summary>
public string Fingerprint()
{
var text = new StringBuilder(FileTemplate).Append('\n');
foreach (var s in Steps)
{
text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FromFolder}|{s.ToFolder}|{s.FromTitle}|{s.ToTitle}|{s.Carried}|{s.FileChanges}|{s.FileDigest}|");
foreach (var sample in s.FileSamples) text.Append(sample.From).Append('>').Append(sample.To).Append(';');
foreach (var blocked in s.Blocked) text.Append(CultureInfo.InvariantCulture, $"{blocked.Reason}:{blocked.Frames};");
text.Append('\n');
}
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
}
}
/// <summary>
/// What the completed steps of a plan did, over every run that applied them (<see cref="RenameJournal.Done"/>): the
/// sequences changed, the frames whose file got a new name, and the sequences not changed as planned: because they changed
/// since, left as they were (<see cref="Dropped"/>), their file names kept (<see cref="FilesKept"/>) or their title and file
/// names kept (<see cref="TitlesKept"/>); their file names kept because a photo was in use or a new name was taken
/// (<see cref="FilesBusy"/>); their title and file names kept because a newer Chronos wrote their sidecar (<see cref="Newer"/>);
/// left as they were because the folder around them that was to carry them stayed, for its own reason
/// (<see cref="CarriedKept"/>).
/// </summary>
public sealed record RenameTally
{
public IReadOnlyList<Guid> Changed { get; init; } = [];
public int Files { get; init; }
public IReadOnlyList<Guid> Dropped { get; init; } = [];
public IReadOnlyList<Guid> FilesKept { get; init; } = [];
public IReadOnlyList<Guid> TitlesKept { get; init; } = [];
public IReadOnlyList<Guid> FilesBusy { get; init; } = [];
public IReadOnlyList<Guid> Newer { get; init; } = [];
public IReadOnlyList<Guid> CarriedKept { get; init; } = [];
}
/// <summary>A plan being applied, with the steps already completed; lets an interrupted rename resume (BRIEF §7).</summary>
/// <param name="Held">The job applying the plan was paused, cancelled or failed between two steps: an archive open leaves the
/// plan to that job, which completes it when it is resumed or retried.</param>
public sealed record RenameJournal(RenamePlan Plan, IReadOnlyList<Guid> Completed, bool Held = false)
{
/// <summary>What the completed steps did, so a resumed run reports the whole plan.</summary>
public RenameTally Done { get; init; } = new();
public static string PathFor(ArchivePaths archive, Guid planId) => Path.Combine(archive.JournalDirectory, $"rename-{planId:N}.json");
public static void Write(ArchivePaths archive, RenameJournal journal)
{
Directory.CreateDirectory(archive.JournalDirectory);
AtomicFile.WriteAllBytes(PathFor(archive, journal.Plan.Id), JsonSerializer.SerializeToUtf8Bytes(journal, ArchiveJsonIndented.Default.RenameJournal));
}
/// <summary>
/// Journals left by interrupted renames, held ones included. A journal that cannot be read (damaged by hand, or by a
/// disk) is logged and left where it is, so the archive still opens; its plan is not resumed, and the file renames of
/// its steps are completed by their own journals (<see cref="FileRenameJournal"/>).
/// </summary>
public static IReadOnlyList<RenameJournal> ListPending(ArchivePaths archive)
{
if (!Directory.Exists(archive.JournalDirectory)) return [];
var list = new List<RenameJournal>();
foreach (var path in Directory.EnumerateFiles(archive.JournalDirectory, "rename-*.json").Order(StringComparer.Ordinal))
{
try
{
if (Parse(File.ReadAllBytes(path)) is { } journal) list.Add(journal);
else Log.Warning("archive", $"The rename journal {Path.GetFileName(path)} is empty or incomplete; its plan is not resumed");
}
catch (JsonException ex)
{
Log.Warning("archive", $"The rename journal {Path.GetFileName(path)} cannot be read; its plan is not resumed", ex);
}
}
return list;
}
/// <summary>
/// The journal of the plan <paramref name="planId"/>; null when there is none (the plan completed, or never started).
/// Throws <see cref="InvalidDataException"/> when the journal is there but cannot be read, so its job fails with the
/// reason instead of planning again over a half-applied plan.
/// </summary>
public static RenameJournal? Read(ArchivePaths archive, Guid planId)
{
var path = PathFor(archive, planId);
if (!File.Exists(path)) return null;
try
{
return Parse(File.ReadAllBytes(path)) ?? throw new InvalidDataException($"The rename journal {Path.GetFileName(path)} is incomplete.");
}
catch (JsonException ex)
{
throw new InvalidDataException($"The rename journal {Path.GetFileName(path)} cannot be read.", ex);
}
}
private static RenameJournal? Parse(byte[] bytes) =>
JsonSerializer.Deserialize(bytes, ArchiveJson.Default.RenameJournal) is { Plan: not null, Completed: not null } journal ? journal : null;
public static void Delete(ArchivePaths archive, Guid planId) => File.Delete(PathFor(archive, planId));
}
/// <summary>Builds rename plans from folder, title and file templates (BRIEF §7.1, §12.5; Reorganize, owner review 2, R7).</summary>
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, 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)"…; 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
/// 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>
/// <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; on a case-insensitive one only the sequence's own
/// folder can be found, under at most one of the two names (under neither when the disk spells it another way, such as
/// <c>TRIP (2)</c>). 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,
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);
bool folderByTitle = folder?.Uses("title") == true, filesByTitle = file?.Uses("title") == true;
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)
{
if (Unreadable(s))
{
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 = NewTitle(context, s.Title, 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 && context is not null && s.Folder.Length > 0 && NewFolder(context, newTitle, folder) is { } expanded
&& !expanded.Equals(s.Folder, StringComparison.Ordinal))
{
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, existsExactly) ?? Unique(expanded, claimed, existsOnDisk);
claimed.Add(newFolder);
given.Add(newFolder);
}
}
var step = new RenameStep(s.SequenceId, s.Folder, newFolder, s.Title, newTitle);
if (file is not null) step = WithFiles(step, s.Files!, file, newTitle);
own.Add(step with { NamedByTitle = (folderByTitle && step.MovesFolder) || (filesByTitle && step.FileChanges > 0) });
}
var moving = own.Where(s => s.MovesFolder).ToList();
foreach (var step in moving)
{
// Into a sequence's folder (its own included) or another target: one sequence would end up inside another.
var host = taken.Concat(moving.Where(m => m != step).Select(m => m.ToFolder)).FirstOrDefault(f => IsInside(f, step.ToFolder));
if (host is not null) throw new NestedRenameException(step.ToFolder, host);
}
var steps = new List<(RenameStep Step, int Order)>();
// 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);
if (carrier is not null)
steps.Add((step with { ToFolder = carrier.ToFolder + step.FromFolder[carrier.FromFolder.Length..], Carried = true }, 1));
else if (step.MovesFolder)
steps.Add((step, -moving.Count(m => m != step && IsInside(m.FromFolder, step.FromFolder))));
else if (step.Retitles || step.FileChanges > 0 || step.Blocked.Count > 0)
steps.Add((step, 0));
}
// Stable: subjects keep their order, sequences inside moving folders move out first, carried ones come last.
return new RenamePlan(Guid.CreateVersion7(), archiveId, [.. steps.OrderBy(s => s.Order).Select(s => s.Step)])
{
FileTemplate = fileTemplate,
FolderTemplate = folderTemplate,
TitleTemplate = titleTemplate,
Subjects = [.. subjects.Select(s => s.SequenceId)],
};
}
/// <summary>
/// The title and the folder the templates give a sequence from its sidecar (<paramref name="manifest"/>) as
/// <see cref="Plan"/> gives them, where <c>{title}</c> of the title template is <paramref name="title"/>: the title is
/// <paramref name="title"/> without a title template or when it expands to nothing; the folder is the expansion itself,
/// before any <c>" (2)"</c> (<see cref="Gives"/>), null without a folder template or when it expands to nothing.
/// </summary>
public static (string? Title, string? Folder) Names(SequenceManifest manifest, string? title, string? folderTemplate, string? titleTemplate)
{
ArgumentNullException.ThrowIfNull(manifest);
var context = Context(manifest, title);
var newTitle = NewTitle(context, title, titleTemplate is null ? null : PathTemplate.Parse(titleTemplate));
return (newTitle, folderTemplate is null ? null : NewFolder(context, newTitle, PathTemplate.Parse(folderTemplate)));
}
/// <summary>
/// Whether <paramref name="folder"/> is a folder a plan gives for the expansion <paramref name="expanded"/>
/// (<see cref="Names"/>): that one, or the <c>" (n)"</c> of it that a folder of that name already there made it take.
/// </summary>
public static bool Gives(string expanded, string folder)
{
ArgumentNullException.ThrowIfNull(expanded);
ArgumentNullException.ThrowIfNull(folder);
return folder.Equals(expanded, StringComparison.Ordinal) || (Numbered(folder, expanded, StringComparison.Ordinal) is { } n && n >= 2
&& folder.Equals(string.Create(CultureInfo.InvariantCulture, $"{expanded} ({n})"), StringComparison.Ordinal));
}
/// <summary>The <c>n</c> of <paramref name="folder"/> when it is <paramref name="expanded"/> followed by <c>" (n)"</c>; null otherwise.</summary>
private static int? Numbered(string folder, string expanded, StringComparison comparison) =>
folder.Length > expanded.Length + 3 && folder.StartsWith(expanded + " (", comparison) && folder[^1] == ')'
&& int.TryParse(folder.AsSpan(expanded.Length + 2, folder.Length - expanded.Length - 3), NumberStyles.None, CultureInfo.InvariantCulture, out var n)
? n
: null;
private static string? NewTitle(NamingContext? context, string? title, PathTemplate? template) =>
template is null || context is null ? title : Blank(template.ExpandText(context)) ?? title;
private static string? NewFolder(NamingContext context, string? newTitle, PathTemplate template) => Blank(template.ExpandFolder(context with { Title = newTitle }));
/// <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) return Context(manifest, 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>What the folder and title templates see in a sidecar: its first frame (<see cref="Context(RenameSubject)"/>).</summary>
private static NamingContext Context(SequenceManifest manifest, string? title)
{
if (manifest.Frames.Count > 0) return FrameNaming.Context(manifest.Frames[0], manifest, 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 = 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)
{
var plan = FileRenames.Plan(files.Manifest, title, template, files.Present);
return step with
{
FramesVersion = plan.Frames > 0 ? files.Manifest.Versions.Frames : 0,
FileChanges = plan.Frames,
FileSamples = plan.Samples,
FileDigest = plan.Frames > 0 ? plan.Digest() : null,
Blocked = plan.Blocked,
};
}
/// <summary>
/// Whether <paramref name="path"/> lies inside <paramref name="folder"/> (archive-relative, forward slashes); the
/// archive root, a sequence only when a folder was adopted in place, counts as containing nothing.
/// </summary>
public static bool IsInside(string folder, string path) =>
folder.Length > 0 && path.Length > folder.Length + 1 && path[folder.Length] == '/' && path.StartsWith(folder, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// 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 (for a case-only change, a folder of its own
/// 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 || 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 || 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.");
Directory.CreateDirectory(Path.GetDirectoryName(to)!);
if (caseOnly)
{
var temp = from + ".rename-" + Guid.NewGuid().ToString("N")[..8];
Directory.Move(from, temp);
Directory.Move(temp, to);
}
else
{
Directory.Move(from, to);
}
}
/// <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 folder holds that name exactly (a sequence's, or one on disk beside the sequence's own folder,
/// on a case-sensitive file system: <paramref name="existsExactly"/> finds both names), 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, Func<string, bool> existsExactly)
{
string? same = null;
if (current.Equals(expanded, StringComparison.OrdinalIgnoreCase)) same = expanded;
else if (Numbered(current, expanded, StringComparison.OrdinalIgnoreCase) is { } 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) || given.Contains(same)) return null;
if (same.Equals(current, StringComparison.Ordinal)) return same;
// The new name on disk is another folder only while the sequence's own is there under the index's name too, as
// MoveFolder throws: on a case-insensitive file system the disk may spell the sequence's own folder as the template
// does (renamed in Explorer, or an outer level a change of case left as it was), and that folder is no other.
return occupied.Any(o => o.Equals(same, StringComparison.Ordinal)) || (existsExactly(same) && existsExactly(current)) ? null : same;
}
private static string Unique(string folder, HashSet<string> claimed, Func<string, bool> existsOnDisk)
{
var candidate = folder;
for (var n = 2; claimed.Contains(candidate) || existsOnDisk(candidate); n++)
candidate = string.Create(CultureInfo.InvariantCulture, $"{folder} ({n})");
return candidate;
}
}