From 0377040a19fece07a97faad99b4a4864330df93f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 27 Oct 2026 18:27:59 +0100 Subject: [PATCH] fix(archive): a case-only target that is the sequence's own folder is kept; stored templates never fail other edits Reorganize refused a case-only folder target whenever a folder of that exact name was on disk. On a case-insensitive file system that folder can be the sequence's own, when the disk spells it as the template does and the index does not (renamed in Explorer, or an outer level a change of case left as it was), so the plan gave a needless " (n)" folder. RenamePlanner.Kept now refuses only when both exact names exist, the condition MassRenamer.TargetTaken and MoveFolder already use. ArchiveSettings.Problem held both templates to the template rules on every UpdateSettingsAsync, so an archive.json saved before the rules made every desktop Settings > Archive edit fail. A template the file already holds is now only checked for being usable; a template the edit gives, and both templates of a new archive, meet every rule. A broken rule throws TemplateRuleException (an ArgumentException naming the field), and the desktop toast shows that rule's sentence instead of "Something went wrong". Also corrects comments that ignored RenameBlock.Unreadable (the whole sequence stays as it is) and the ARCHITECTURE Naming row. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit ac7a0c36df83b6d43651caf0225c530466242c97) --- docs/ARCHITECTURE.md | 2 +- src/Chronos.App/Archive/ArchiveDialogs.xaml | 2 +- src/Chronos.App/Archive/ReorganizePlans.cs | 8 ++- src/Chronos.App/Shell/ErrorText.cs | 2 + src/Chronos.Core/Archiving/FileRenames.cs | 5 +- src/Chronos.Core/Archiving/MassRename.cs | 23 +++--- src/Chronos.Data/Archiving/ArchiveService.cs | 71 +++++++++++++++---- src/Chronos.Protocol/Library.cs | 5 +- src/Chronos.Server/Admin/web/reorganize.js | 5 +- src/Chronos.Server/Api/ArchiveEndpoints.cs | 3 +- .../Infrastructure/ErrorTextTests.cs | 13 ++++ .../Archiving/ReorganizeTests.cs | 53 ++++++++++++++ .../Archiving/ArchiveSettingsTests.cs | 32 +++++++++ 13 files changed, 193 insertions(+), 31 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5a7f6d8f..cd8b37be 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -42,7 +42,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Video` (+ `Mp4`, `Avi`, `Bitstream`, `Yuv`, `Managed`) | `IVideoEncoderProvider`, MP4 muxer and inspector, AVI-MJPEG, NV12/P010, managed encoders (MJPEG-AVI, GIF, APNG, image sequences) | | `Archiving` | Archive layout and paths, sidecars (`sequence.json`, `project.json`), scanner, index snapshot, leases, thumbnail packs, verify, adopt, rename plans (`RenamePlanner`: folder, title and file templates, `RenameTemplates`, the plan's fingerprint, which pins every file rename by its digest and not the frames version; `FileRenames`: a sequence's new file names; `FileRenameJournal`: two-phase renames through temporary names, `.chronos/rename-files.json`, a recovery safe to run again from wherever it stopped, a new name taken meanwhile sending that photo and its companions back together to their old names or a free `_2`, those that took their new names already with them; `FrameCompanions`: the XMP files that follow a photo, one rule for the trash and Reorganize, matched whatever their case and each folder listed once by `FrameCompanions.Index`) | | `Import` | Card scan, session detection, import plan, hash-verified copy, card eraser (re-hash before delete) | -| `Naming` | Folder/file templates and tokens (folder levels scans skip escaped with `_`; `ExpandText` for titles); `FrameNaming` (the naming context and unique file name of a frame, shared by import, upload and Reorganize: the sequence's camera and lens, the first frame for folders; `UniqueNames`: `_2`, `_3`… in linear time); `TemplateRules` (what every place a template is typed or sent refuses, the archive engine's settings included: a folder scans skip, a lost extension, names that repeat; a long file name is shortened before its `.{ext}`) | +| `Naming` | Folder/file templates and tokens (folder levels scans skip escaped with `_`; `ExpandText` for titles; `ExpandFile` shortens a long file name before its `.{ext}`); `FrameNaming` (the naming context and unique file name of a frame, shared by import, upload and Reorganize: the sequence's camera and lens, the first frame for folders; `UniqueNames`: `_2`, `_3`… in linear time); `TemplateRules` (what every place a template is typed or sent refuses, the archive engine's new or changed templates included: a folder scans skip, a lost extension, names that repeat) | | `Model` | Domain entities and enums (§5) shared by Data, Server and clients | | `Packaging` | TPK1 installer payload writer/reader, staged install transaction | | `Diagnostics` | `Log` (never throws: a line its sink cannot write is dropped), `FileLogSink` with `LogFileOptions` (level, daily or hourly files, numbered parts past a size, pruning by age and by the total size, never the file being written), synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) | diff --git a/src/Chronos.App/Archive/ArchiveDialogs.xaml b/src/Chronos.App/Archive/ArchiveDialogs.xaml index de21e020..3411efe6 100644 --- a/src/Chronos.App/Archive/ArchiveDialogs.xaml +++ b/src/Chronos.App/Archive/ArchiveDialogs.xaml @@ -166,7 +166,7 @@ - + diff --git a/src/Chronos.App/Archive/ReorganizePlans.cs b/src/Chronos.App/Archive/ReorganizePlans.cs index 6452d98d..cf897784 100644 --- a/src/Chronos.App/Archive/ReorganizePlans.cs +++ b/src/Chronos.App/Archive/ReorganizePlans.cs @@ -20,7 +20,8 @@ public sealed record ReorganizeLine(string Label, string From, string To, bool I /// /// One sequence of the Reorganize dry run: its name, what concerns it as a whole (it follows its folder, how many of its -/// files get a new name), its changes (the first renamed files as samples) and the photos that keep their names, with why. +/// files get a new name), its changes (the first renamed files as samples) and the photos that keep their names, with why, +/// or why the whole sequence stays as it is. /// /// The sequence has no title: is its folder, read left to right. public sealed record ReorganizeRow(Guid SequenceId, string Name, bool IsNamePath, string Note, IReadOnlyList Lines, IReadOnlyList Kept) @@ -70,7 +71,10 @@ public static class ReorganizePlans return null; } - /// The rows of a plan, in the order it applies them; a step that changes nothing lists why photos keep their names. + /// + /// The rows of a plan, in the order it applies them; a step that changes nothing lists why photos keep their names, or + /// why the whole sequence stays as it is. + /// public static IReadOnlyList Rows(RenamePlan plan) => [.. plan.Steps.Where(s => s.Changes || s.Blocked.Count > 0).Select(Row)]; public static ReorganizeRow Row(RenameStep step) diff --git a/src/Chronos.App/Shell/ErrorText.cs b/src/Chronos.App/Shell/ErrorText.cs index ca370ef4..682f5c73 100644 --- a/src/Chronos.App/Shell/ErrorText.cs +++ b/src/Chronos.App/Shell/ErrorText.cs @@ -42,6 +42,8 @@ public static class ErrorText { LeaseUnavailableException or ArchiveOfflineException or NewerFormatException or ImportSourceUnavailableException or CopyVerificationException or StaleRenamePlanException or SyncConflictChangedException => ex.Message, + // A template an archive refused (Settings › Archive, or this PC's templates for a new archive): the rule it breaks. + TemplateRuleException rule => Loc.L("Errors.Template." + rule.Rule), // The server words its errors in the client's language (Accept-Language). ChronosApiException api when FromServer(api.Error) => api.Error.Message, // Any other reply (a reverse proxy's 502 page while the server restarts, its 413 for a large body, a bare 500) holds diff --git a/src/Chronos.Core/Archiving/FileRenames.cs b/src/Chronos.Core/Archiving/FileRenames.cs index ebfaebe0..db57ce8b 100644 --- a/src/Chronos.Core/Archiving/FileRenames.cs +++ b/src/Chronos.Core/Archiving/FileRenames.cs @@ -27,7 +27,10 @@ public enum RenameBlock Unreadable, } -/// Frames of a sequence that keep their names, and why. +/// +/// Frames of a sequence that keep their names, and why; or, for (0 frames), why the +/// whole sequence stays as it is. +/// public sealed record RenameBlocked(RenameBlock Reason, int Frames); /// diff --git a/src/Chronos.Core/Archiving/MassRename.cs b/src/Chronos.Core/Archiving/MassRename.cs index 10545893..51aff951 100644 --- a/src/Chronos.Core/Archiving/MassRename.cs +++ b/src/Chronos.Core/Archiving/MassRename.cs @@ -91,8 +91,8 @@ public sealed record RenameTemplates(string? Folder = null, string? File = null, /// titleTemplate): blank, not valid (), with a format a sample cannot be written /// with ({date:%}), expanding to nothing, or, for a folder or file template, breaking a rule of the archive's /// templates (: 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 - /// (ArchiveSettings.Problem). + /// repeat); null when every one given can. The archive settings' templates are checked alike, except for the rules a + /// template archive.json already holds breaks (ArchiveSettings.Problem). /// public string? Problem() => Check()?.Field; @@ -259,7 +259,8 @@ public static class RenamePlanner /// The archive's other sequences inside a subject's folder, with their titles. /// Whether a folder of exactly that name, in every level's case, is on disk /// (): on a case-sensitive file system Trip (2) beside a sequence at trip (2) is - /// another folder, which a change of case could never move onto. Null when no folder but the sequences' own counts. + /// another folder, which a change of case could never move onto; on a case-insensitive one only the sequence's own + /// folder is found, under one of the two names. Null when no folder but the sequences' own counts. /// A target lies inside a sequence's folder, or inside another target. public static RenamePlan Plan(Guid archiveId, IReadOnlyList subjects, string? folderTemplate, string? titleTemplate, IEnumerable occupied, Func existsOnDisk, IReadOnlyList? nested = null, string? fileTemplate = null, @@ -504,11 +505,12 @@ public static class RenamePlanner /// /// The folder a sequence keeps (in the template's case) when it already is , or the /// " (n)" 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 any on a case-sensitive file system: - /// ), which the change of case could never move onto, or when this plan already gave it - /// to another sequence (, whatever its case: trip (2) and TRIP (2) both keep - /// Trip (2) otherwise). Without it a sequence at 2026-09-28 (2) would be planned to (3), its own - /// folder being taken, and back to (2) by the next Reorganize. + /// 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: finds both names), which the change of case could + /// never move onto, or when this plan already gave it to another sequence (, whatever its case: + /// trip (2) and TRIP (2) both keep Trip (2) otherwise). Without it a sequence at + /// 2026-09-28 (2) would be planned to (3), its own folder being taken, and back to (2) by the next + /// Reorganize. /// private static string? Kept(string current, string expanded, IReadOnlyList occupied, IReadOnlySet given, Func existsExactly) { @@ -518,7 +520,10 @@ public static class RenamePlanner // "(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; - return occupied.Any(o => o.Equals(same, StringComparison.Ordinal)) || existsExactly(same) ? null : 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 claimed, Func existsOnDisk) diff --git a/src/Chronos.Data/Archiving/ArchiveService.cs b/src/Chronos.Data/Archiving/ArchiveService.cs index c6d00cd0..3b4a50d7 100644 --- a/src/Chronos.Data/Archiving/ArchiveService.cs +++ b/src/Chronos.Data/Archiving/ArchiveService.cs @@ -2,6 +2,7 @@ using System.Text.Json; using Chronos.Core.Archiving; using Chronos.Core.Diagnostics; using Chronos.Core.Import; +using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Core.Naming; using Chronos.Data.Archiving.Jobs; @@ -104,13 +105,14 @@ public sealed class ArchiveService : IJobHandlerProvider /// becomes the folder's name; a longer one than is shortened. /// /// The folder already is an archive (open it instead). - /// A template or policy is invalid ( names it). + /// A template or policy is invalid ( names it; + /// for a template that breaks a rule). public async Task CreateAsync(string root, ArchiveSettings settings, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(settings); var paths = new ArchivePaths(root); settings = WithUsableName(settings, paths); - if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field); + settings.Validate(); if (File.Exists(paths.ManifestPath)) throw new InvalidOperationException($"{paths.Root} already is a Chronos archive."); Directory.CreateDirectory(paths.MetaDirectory); var manifest = new ArchiveManifest @@ -211,9 +213,12 @@ public sealed class ArchiveService : IJobHandlerProvider /// a client sharing the archive never undo each other's change; the file is replaced atomically. Folders and files /// already in the archive keep their names: templates and policies apply to the next imports, proxies and thumbnails. /// A blank or overlong name in the file (archives made at a drive root, or before names were checked) is made usable - /// as does, instead of failing every edit. + /// as does, instead of failing every edit. Likewise + /// a template the file holds that breaks a rule of the archive's templates (saved before the rules existed) stays as it + /// is through an edit of anything else: only a template the edit gives is held to them (). /// - /// An edited setting is invalid ( names it). + /// An edited setting is invalid ( names it; + /// for a template that breaks a rule). /// The archive is offline or read-only. /// Another process kept the archive's settings busy. public async Task UpdateSettingsAsync(Guid archiveId, Func edit, CancellationToken cancellationToken = default) @@ -230,7 +235,8 @@ public sealed class ArchiveService : IJobHandlerProvider if (current.Id != archive.Id) throw new InvalidDataException($"{paths.ManifestPath} belongs to archive {current.Id}, not {archive.Id}."); // The name read is made usable before the edit sees it; a name the edit sets is checked as given. var settings = edit(WithUsableName(ArchiveSettings.Of(current), paths)); - if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field); + // A template the file already holds stays as it is, rules or not: only one the edit gives is held to them. + settings.Validate(current.LayoutTemplates); var manifest = current with { Name = settings.Name.Trim(), @@ -536,21 +542,60 @@ public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, Pro /// /// The first invalid field by its API name (name, folderTemplate, fileTemplate, - /// proxyLongEdge, thumbnailLongEdge); null when every field is valid. The templates are held to the rules - /// they meet wherever they are typed (, ): besides - /// parsing, a folder template may not write a level scans never enter, and a file template must keep the photo's - /// extension, tell a session's photos apart and hold no slash. + /// proxyLongEdge, thumbnailLongEdge); null when every field is valid. A template has to be usable + /// (), and one given anew is held to the rules it meets wherever it is typed + /// (): a folder template may not write a level scans never enter, and a file template must + /// keep the photo's extension, tell a session's photos apart and hold no slash. /// - public string? Problem() + /// The templates archive.json holds before an edit: one the edit leaves as it is, saved before the + /// rules existed (0.1.0-rc.5 and earlier), never fails an edit of another setting. Null holds both to every rule (a new + /// archive). + public string? Problem(LayoutTemplates? stored = null) { if (string.IsNullOrWhiteSpace(Name) || Name.Trim().Length > MaxNameLength) return "name"; - if (string.IsNullOrWhiteSpace(Templates.Folder)) return "folderTemplate"; - if (string.IsNullOrWhiteSpace(Templates.File)) return "fileTemplate"; - if (new RenameTemplates(Templates.Folder, Templates.File).Problem() is { } template) return template; + if (CheckTemplates(stored) is { } template) return template.Field; if (!ProxyPolicy.IsValidLongEdge(Proxies.LongEdge) || Proxies.Quality is < 1 or > 100) return "proxyLongEdge"; if (!ThumbnailPolicy.IsValidLongEdge(Thumbnails.LongEdge) || Thumbnails.Quality is < 1 or > 100) return "thumbnailLongEdge"; return null; } + + /// + /// The first template that cannot be used (), with the rule it breaks + /// (); null when both can. A rule broken by a template + /// already holds does not count. + /// + public TemplateProblem? CheckTemplates(LayoutTemplates? stored = null) + { + if (string.IsNullOrWhiteSpace(Templates.Folder)) return new TemplateProblem("folderTemplate", null); + if (string.IsNullOrWhiteSpace(Templates.File)) return new TemplateProblem("fileTemplate", null); + static TemplateProblem? Given(RenameTemplates template, bool kept) => template.Check() is { } problem && (problem.Rule is null || !kept) ? problem : null; + return Given(new RenameTemplates(Folder: Templates.Folder), Templates.Folder == stored?.Folder) + ?? Given(new RenameTemplates(File: Templates.File), Templates.File == stored?.File); + } + + /// Refuses these settings when a field is invalid (). + /// A template breaks a rule of the archive's templates. + /// Another field is invalid ( names it). + internal void Validate(LayoutTemplates? stored = null) + { + if (Problem(stored) is not { } field) return; + if (CheckTemplates(stored) is { Rule: { } rule } template && template.Field == field) throw new TemplateRuleException(field, rule); + throw new ArgumentException($"The archive setting {field} is invalid.", field); + } +} + +/// +/// An archive setting's template breaks a rule of the archive's templates (): the message says +/// which in one sentence (Errors.Template.<Rule>, in the language of the moment it was refused), and +/// names the template by its API name (folderTemplate, fileTemplate). +/// +public sealed class TemplateRuleException(string field, string rule) : ArgumentException(Loc.L("Errors.Template." + rule)) +{ + // Not the base's: its message would end in "(Parameter '…')". + public override string? ParamName { get; } = field; + + /// The rule broken (). + public string Rule { get; } = rule; } /// Builds the archive jobs; enqueue with . diff --git a/src/Chronos.Protocol/Library.cs b/src/Chronos.Protocol/Library.cs index b7054f69..e7eb308e 100644 --- a/src/Chronos.Protocol/Library.cs +++ b/src/Chronos.Protocol/Library.cs @@ -116,7 +116,8 @@ public sealed record ReorganizeStepDto(Guid SequenceId, string FromFolder, strin int FramesVersion, int FileChanges, IReadOnlyList FileSamples, IReadOnlyList Blocked); /// -/// The dry run of a Reorganize: its steps, the sequences that change (carried ones included), the photos renamed, the photos -/// that keep their names, and the fingerprint the change sends back. +/// The dry run of a Reorganize: its steps (those that change nothing list only what stays as it is), the sequences that +/// change (carried ones included), the photos renamed, the photos that keep their names (a sequence that stays as it is +/// whole, unreadable, counts none), and the fingerprint the change sends back. /// public sealed record ReorganizePlanDto(IReadOnlyList Steps, int Sequences, int Files, int Kept, string Fingerprint); diff --git a/src/Chronos.Server/Admin/web/reorganize.js b/src/Chronos.Server/Admin/web/reorganize.js index 8d8daf70..ad7299e7 100644 --- a/src/Chronos.Server/Admin/web/reorganize.js +++ b/src/Chronos.Server/Admin/web/reorganize.js @@ -255,7 +255,10 @@ export function openReorganize({ api, target, names = new Map(), templates = nul shownText.textContent = t("Admin.Library.Shown", formatNumber(Math.min(shown, steps.length)), formatNumber(steps.length)); } - /** One step: the sequence's title, its folder and its renamed files, before and after, with the photos that keep their names. */ + /** + * One step: the sequence's title, its folder and its renamed files, before and after, with the photos that keep their + * names, or why the whole sequence stays as it is. + */ function rowHtml(s) { const fromTitle = s.fromTitle ?? null; const toTitle = s.toTitle ?? null; diff --git a/src/Chronos.Server/Api/ArchiveEndpoints.cs b/src/Chronos.Server/Api/ArchiveEndpoints.cs index 1e239826..4303737a 100644 --- a/src/Chronos.Server/Api/ArchiveEndpoints.cs +++ b/src/Chronos.Server/Api/ArchiveEndpoints.cs @@ -132,7 +132,8 @@ public static class ArchiveEndpoints /// /// Reorganize: folder, file and title templates applied to sequenceIds or, with all, to every sequence of the /// archive (BRIEF §12.5). With dryRun the plan, nothing touched: per sequence its folder and title before and after, - /// the photos renamed with the first of them, and the photos that keep their names and why. Otherwise the request carries + /// the photos renamed with the first of them, and the photos that keep their names and why, or why the whole sequence + /// stays as it is. Otherwise the request carries /// that plan's fingerprint and the server queues a move job (202) that applies exactly that plan, refused when the /// archive changed before it ran. 400 bad_request (details sequenceIds: neither or both of them, none, or /// more than ; templates: none; fingerprint), 400 diff --git a/tests/Chronos.App.Tests/Infrastructure/ErrorTextTests.cs b/tests/Chronos.App.Tests/Infrastructure/ErrorTextTests.cs index 7840b050..9f56e5d7 100644 --- a/tests/Chronos.App.Tests/Infrastructure/ErrorTextTests.cs +++ b/tests/Chronos.App.Tests/Infrastructure/ErrorTextTests.cs @@ -2,9 +2,11 @@ using System.Globalization; using System.IO; using System.Net; using System.Net.Http; +using Chronos.App.Infrastructure; using Chronos.App.Shell; using Chronos.Core.Archiving; using Chronos.Core.Localization; +using Chronos.Data.Archiving; using Chronos.Protocol; using Chronos.Protocol.Client; using Chronos.Testing; @@ -60,4 +62,15 @@ public sealed class ErrorTextTests Assert.Equal("Something went wrong.", ErrorText.For(new IOException(@"Access to the path 'D:\Archive' is denied."))); Assert.Equal(@"The archive D:\Shoots is read-only.", ErrorText.For(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.ReadOnly))); } + + [Test] + public void ATemplateAnArchiveRefusesSaysTheRuleItBreaks() + { + // A new archive with this PC's templates, one saved before the rules existed: the toast says what to change. + var refused = new TemplateRuleException("fileTemplate", "NotUnique"); + const string Sentence = "Names would repeat: add the frame number, the time or the original name."; + Assert.Equal(Sentence, ErrorText.For(refused)); + Assert.Equal(Sentence, ArchiveActions.Cause(refused)); + Assert.Equal("Something went wrong.", ArchiveActions.Cause(new ArgumentException("The archive setting name is invalid.", "name"))); + } } diff --git a/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs b/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs index d1374fd8..f89a1a06 100644 --- a/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs +++ b/tests/Chronos.Core.Tests/Archiving/ReorganizeTests.cs @@ -429,6 +429,59 @@ public sealed class ReorganizeTests(TestContext context) Assert.Equal("a", File.ReadAllText(Path.Combine(archive.FromRelative("Trip/day"), "a.txt"))); } + [Test] + public void AFolderTheDiskSpellsAsTheTemplateDoesIsTheSequencesOwn() + { + // A case-insensitive file system: the index has "trip (2)" and "Trip/day", the disk spells them "Trip (2)" (renamed in + // Explorer since the last scan) and "trip/day" (an outer level a change of case left as it was). The folders found + // under the template's exact names are the sequences' own: a change of case is all the plan makes, never " (n)". + var disk = new HashSet(["Trip", "Trip (2)", "trip", "trip/day"], StringComparer.Ordinal); + bool OnDisk(string f) => disk.Contains(f, StringComparer.OrdinalIgnoreCase); + var renamed = new RenameSubject(Guid.NewGuid(), "trip (2)", "Trip", Start, null, null, null); + var plan = RenamePlanner.Plan(Guid.NewGuid(), [renamed], "{title}", null, ["trip (2)", "Trip"], OnDisk, existsExactly: disk.Contains); + Assert.Equal("Trip (2)", plan.Steps.Single().ToFolder); + var outer = new RenameSubject(Guid.NewGuid(), "Trip/day", "day", Start, null, null, null); + plan = RenamePlanner.Plan(Guid.NewGuid(), [outer], "trip/day", null, ["Trip/day"], OnDisk, existsExactly: disk.Contains); + Assert.Equal("trip/day", plan.Steps.Single().ToFolder); + } + + [Test] + public void ACaseOnlyTargetOnDiskIsRefusedOnlyBesideTheSequencesOwnFolder() + { + var archive = new ArchivePaths(context.CreateTempDirectory("archive")); + foreach (var folder in (string[])["Trip", "Trip (2)", "walk/day"]) + { + Directory.CreateDirectory(archive.FromRelative(folder)); + File.WriteAllText(Path.Combine(archive.FromRelative(folder), "a.txt"), folder); + } + // The index has "trip (2)" and "Walk/day": on a case-sensitive file system those are folders of their own beside the + // ones the template names. + var caseSensitive = !Directory.Exists(archive.FromRelative("trip (2)")); + if (caseSensitive) + { + Directory.CreateDirectory(archive.FromRelative("trip (2)")); + Directory.CreateDirectory(archive.FromRelative("Walk/day")); + } + bool OnDisk(string f) => Directory.Exists(archive.FromRelative(f)); + bool Exactly(string f) => RenamePlanner.ExistsExactly(archive, f); + var renamed = new RenameSubject(Guid.NewGuid(), "trip (2)", "Trip", Start, null, null, null); + var outer = new RenameSubject(Guid.NewGuid(), "Walk/day", "day", Start, null, null, null); + var first = RenamePlanner.Plan(Guid.NewGuid(), [renamed], "{title}", null, ["trip (2)", "Trip", "Walk/day"], OnDisk, existsExactly: Exactly).Steps.Single(); + var second = RenamePlanner.Plan(Guid.NewGuid(), [outer], "walk/day", null, ["trip (2)", "Trip", "Walk/day"], OnDisk, existsExactly: Exactly).Steps.Single(); + if (caseSensitive) + { + Assert.Equal(("Trip (3)", "walk/day (2)"), (first.ToFolder, second.ToFolder)); + return; + } + // Case-insensitive: each sequence keeps its own folder, which is already as the template spells it, so applying the + // steps (twice, as a resumed plan does) moves nothing and loses nothing. + Assert.Equal(("Trip (2)", "walk/day"), (first.ToFolder, second.ToFolder)); + foreach (var step in (RenameStep[])[first, second, first, second]) RenamePlanner.MoveFolder(archive, step); + Assert.SequenceEqual(["Trip", "Trip (2)", "walk"], Directory.EnumerateDirectories(archive.Root).Select(Path.GetFileName).Order(StringComparer.Ordinal)); + Assert.Equal("Trip (2)", File.ReadAllText(Path.Combine(archive.FromRelative("Trip (2)"), "a.txt"))); + Assert.Equal("walk/day", File.ReadAllText(Path.Combine(archive.FromRelative("walk/day"), "a.txt"))); + } + [Test] public void PhotosOfALongTitleKeepTheirExtension() { diff --git a/tests/Chronos.Data.Tests/Archiving/ArchiveSettingsTests.cs b/tests/Chronos.Data.Tests/Archiving/ArchiveSettingsTests.cs index bb9d37e4..33d39de7 100644 --- a/tests/Chronos.Data.Tests/Archiving/ArchiveSettingsTests.cs +++ b/tests/Chronos.Data.Tests/Archiving/ArchiveSettingsTests.cs @@ -2,6 +2,7 @@ using System.Text.Json.Nodes; using Chronos.Core.Archiving; using Chronos.Core.Codecs.Jpeg; using Chronos.Core.Imaging; +using Chronos.Core.Localization; using Chronos.Core.Metadata; using Chronos.Core.Model; using Chronos.Data.Archiving; @@ -115,6 +116,37 @@ public sealed class ArchiveSettingsTests(TestContext context) Assert.Equal(before, await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct)); } + [Test] + public async Task TemplatesSavedBeforeTheRulesNeverFailAnEditOfAnotherSetting() + { + await using var fx = await ArchiveFixture.CreateAsync(context); + // An archive.json of 0.1.0-rc.5 or earlier: both templates break a rule new templates are held to. + var manifest = ManifestStore.ReadArchive(fx.Paths.ManifestPath); + ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { LayoutTemplates = new LayoutTemplates { Folder = "exports/{date}", File = "{title}" } }); + + // The desktop saves one row at a time: each edit keeps the templates it does not change. + var proxies = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 2560 } }, fx.Ct); + Assert.Equal(("exports/{date}", "{title}", 2560), (proxies.FolderTemplate, proxies.FileTemplate, proxies.ProxyLongEdge)); + await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Name = "Studio" }, fx.Ct); + var folder = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { Folder = "{year}/{date}" } }, fx.Ct); + Assert.Equal(("{year}/{date}", "{title}"), (folder.FolderTemplate, folder.FileTemplate)); + + // A template given anew is held to every rule, and the refusal says which. + var before = await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct); + var refused = await Assert.ThrowsAsync(() => + fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{n}{ext}" } }, fx.Ct)); + Assert.Equal(("fileTemplate", "Extension", Loc.L("Errors.Template.Extension")), (refused.ParamName, refused.Rule, refused.Message)); + Assert.Equal(before, await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct)); + + var file = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{date}_{n:0000}" } }, fx.Ct); + Assert.Equal(("Studio", "{year}/{date}", "{date}_{n:0000}", 2560), (file.Name, file.FolderTemplate, file.FileTemplate, file.ProxyLongEdge)); + + // A new archive has nothing to keep: its templates meet every rule. + var created = await Assert.ThrowsAsync(() => fx.Service.CreateAsync(context.CreateTempDirectory("other"), "Other", + new LayoutTemplates { Folder = "exports/{date}", File = "{date}_{n:0000}" }, null, fx.Ct)); + Assert.Equal(("folderTemplate", "ReservedFolder"), (created.ParamName, created.Rule)); + } + [Test] public async Task AnOfflineArchiveIsNotChangedAndItsIndexSettingsAreShown() {