From a76695f2e913349606ca9331819d06c954072184 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 09:37:52 +0000 Subject: [PATCH] feat(core): naming templates with tokens, formats and sanitizing Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Core/Naming/NamingContext.cs | 36 +++ src/Titano.Core/Naming/PathTemplate.cs | 210 ++++++++++++++++++ .../Naming/PathTemplateTests.cs | 89 ++++++++ tests/Titano.Testing/Assert.cs | 11 + 4 files changed, 346 insertions(+) create mode 100644 src/Titano.Core/Naming/NamingContext.cs create mode 100644 src/Titano.Core/Naming/PathTemplate.cs create mode 100644 tests/Titano.Core.Tests/Naming/PathTemplateTests.cs diff --git a/src/Titano.Core/Naming/NamingContext.cs b/src/Titano.Core/Naming/NamingContext.cs new file mode 100644 index 00000000..59985897 --- /dev/null +++ b/src/Titano.Core/Naming/NamingContext.cs @@ -0,0 +1,36 @@ +namespace Titano.Core.Naming; + +/// Values available to folder/file templates for one frame (BRIEF §7.1). +public sealed record NamingContext +{ + /// Camera wall-clock capture time. + public DateTime CapturedAt { get; init; } + + /// Start of the session the frame belongs to. + public DateTime SessionStart { get; init; } + + /// 1-based session number within the import. + public int Session { get; init; } = 1; + + /// 1-based frame number across the import (or sequence). + public int Number { get; init; } = 1; + + /// 1-based frame number within the session. + public int NumberInSession { get; init; } = 1; + + public string? CameraMake { get; init; } + public string? CameraModel { get; init; } + public string? Lens { get; init; } + public int? Iso { get; init; } + public double? ExposureTime { get; init; } + public double? FNumber { get; init; } + + /// Original file name without extension. + public string OriginalName { get; init; } = string.Empty; + + /// Original extension without the dot, as found on the card. + public string Extension { get; init; } = string.Empty; + + /// Sequence title, when the user gave one. + public string? Title { get; init; } +} diff --git a/src/Titano.Core/Naming/PathTemplate.cs b/src/Titano.Core/Naming/PathTemplate.cs new file mode 100644 index 00000000..37d50da7 --- /dev/null +++ b/src/Titano.Core/Naming/PathTemplate.cs @@ -0,0 +1,210 @@ +using System.Globalization; +using System.Text; + +namespace Titano.Core.Naming; + +/// A parse problem in a template, with the character position for live validation in the UI. +public sealed record TemplateError(int Position, string Code, string? Token); + +/// +/// Folder/file naming templates (BRIEF §7.1). Tokens are written as {name} or {name:format}, where the +/// format is passed to the .NET formatter (e.g. {n:0000}, {date:yyyyMMdd}). {{ and }} are literal +/// braces. Characters that are illegal in Windows/Linux file names are replaced, never passed through. +/// +public sealed class PathTemplate +{ + /// Every token the templates understand. Descriptions are localized resources Import.Token.<name>. + public static readonly IReadOnlyList Tokens = + [ + "year", "month", "day", "date", "time", "hm", "session", "sessionstart", "camera", "lens", + "iso", "shutter", "aperture", "n", "nsession", "name", "ext", "title", + ]; + + private static readonly HashSet TokenSet = new(Tokens, StringComparer.OrdinalIgnoreCase); + private static readonly char[] Illegal = ['<', '>', ':', '"', '|', '?', '*', '\\', '/', '\0']; + private static readonly HashSet ReservedNames = new(StringComparer.OrdinalIgnoreCase) + { + "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + }; + + private readonly List _parts; + + private PathTemplate(string source, List parts, IReadOnlyList errors) + { + Source = source; + _parts = parts; + Errors = errors; + } + + public string Source { get; } + + /// Problems found while parsing; a template with errors still expands best-effort. + public IReadOnlyList Errors { get; } + + public bool IsValid => Errors.Count == 0; + + /// Parses a template; '/' separates folder levels (only meaningful for folder templates). + public static PathTemplate Parse(string template) + { + ArgumentNullException.ThrowIfNull(template); + var parts = new List(); + var errors = new List(); + var literal = new StringBuilder(); + for (var i = 0; i < template.Length; i++) + { + var c = template[i]; + if (c == '{') + { + if (i + 1 < template.Length && template[i + 1] == '{') + { + literal.Append('{'); + i++; + continue; + } + var close = template.IndexOf('}', i + 1); + if (close < 0) + { + errors.Add(new TemplateError(i, "UnclosedBrace", null)); + literal.Append(template, i, template.Length - i); + break; + } + if (literal.Length > 0) + { + parts.Add(Part.Literal(literal.ToString())); + literal.Clear(); + } + var body = template[(i + 1)..close]; + var colon = body.IndexOf(':', StringComparison.Ordinal); + var name = (colon < 0 ? body : body[..colon]).Trim(); + var format = colon < 0 ? null : body[(colon + 1)..]; + if (name.Length == 0) errors.Add(new TemplateError(i, "EmptyToken", null)); + else if (!TokenSet.Contains(name)) errors.Add(new TemplateError(i, "UnknownToken", name)); + parts.Add(Part.Token(name.ToLowerInvariant(), format)); + i = close; + } + else if (c == '}') + { + if (i + 1 < template.Length && template[i + 1] == '}') + { + literal.Append('}'); + i++; + continue; + } + errors.Add(new TemplateError(i, "UnopenedBrace", null)); + } + else + { + literal.Append(c); + } + } + if (literal.Length > 0) parts.Add(Part.Literal(literal.ToString())); + if (template.Trim().Length == 0) errors.Add(new TemplateError(0, "Empty", null)); + return new PathTemplate(template, parts, errors); + } + + /// Expands to a relative folder path (forward slashes; each segment sanitized). + public string ExpandFolder(NamingContext context) + { + var raw = Expand(context, allowSeparators: true); + var segments = raw.Split('/', StringSplitOptions.RemoveEmptyEntries) + .Select(SanitizeSegment) + .Where(s => s.Length > 0); + return string.Join('/', segments); + } + + /// Expands to a file name; the original extension is appended unless the template already ends with {ext}. + public string ExpandFile(NamingContext context) + { + var hasExt = _parts.Count > 0 && _parts[^1] is { IsToken: true, Text: "ext" }; + var name = SanitizeSegment(Expand(context, allowSeparators: false)); + if (name.Length == 0) name = SanitizeSegment(context.OriginalName); + if (!hasExt && context.Extension.Length > 0) name += "." + context.Extension; + return name; + } + + private string Expand(NamingContext c, bool allowSeparators) + { + var inv = CultureInfo.InvariantCulture; + var sb = new StringBuilder(); + foreach (var part in _parts) + { + if (!part.IsToken) + { + sb.Append(allowSeparators ? part.Text.Replace('\\', '/') : part.Text); + continue; + } + var f = part.Format; + var value = part.Text switch + { + "year" => c.CapturedAt.ToString(f ?? "yyyy", inv), + "month" => c.CapturedAt.ToString(f ?? "MM", inv), + "day" => c.CapturedAt.ToString(f ?? "dd", inv), + "date" => c.CapturedAt.ToString(f ?? "yyyy-MM-dd", inv), + "time" => c.CapturedAt.ToString(f ?? "HH-mm-ss", inv), + "hm" => c.CapturedAt.ToString(f ?? "HH-mm", inv), + "sessionstart" => c.SessionStart.ToString(f ?? "yyyy-MM-dd HH-mm", inv), + "session" => c.Session.ToString(f ?? "0", inv), + "n" => c.Number.ToString(f ?? "0000", inv), + "nsession" => c.NumberInSession.ToString(f ?? "0000", inv), + "camera" => CameraName(c.CameraMake, c.CameraModel), + "lens" => c.Lens ?? string.Empty, + "iso" => c.Iso?.ToString(f ?? "0", inv) ?? string.Empty, + "shutter" => Shutter(c.ExposureTime), + "aperture" => c.FNumber is { } fn ? "f" + fn.ToString(f ?? "0.#", inv) : string.Empty, + "name" => c.OriginalName, + "ext" => c.Extension, + "title" => c.Title ?? string.Empty, + _ => string.Empty, + }; + // Token values never introduce folder levels. + sb.Append(value.Replace('/', '-').Replace('\\', '-')); + } + return sb.ToString(); + } + + /// "Canon EOS R5" from make "Canon" + model "Canon EOS R5"; avoids the duplicated brand most cameras report. + public static string CameraName(string? make, string? model) + { + make = make?.Trim(); + model = model?.Trim(); + if (string.IsNullOrEmpty(model)) return make ?? string.Empty; + if (string.IsNullOrEmpty(make)) return model; + var brand = make.Split(' ', StringSplitOptions.RemoveEmptyEntries)[0]; + if (brand.Equals("NIKON", StringComparison.OrdinalIgnoreCase)) brand = "Nikon"; + if (model.StartsWith(brand, StringComparison.OrdinalIgnoreCase)) return brand + model[brand.Length..]; + return brand + " " + model; + } + + /// 1/250 s → "1-250", 2 s → "2s" (file-name safe). + public static string Shutter(double? seconds) + { + if (seconds is not > 0) return string.Empty; + var t = seconds.Value; + if (t >= 0.3) return t.ToString("0.#", CultureInfo.InvariantCulture) + "s"; + return "1-" + Math.Round(1 / t).ToString(CultureInfo.InvariantCulture); + } + + /// Replaces characters that are illegal on Windows or Linux and fixes reserved names and trailing dots/spaces. + public static string SanitizeSegment(string segment) + { + var sb = new StringBuilder(segment.Length); + foreach (var ch in segment) + { + if (ch < 32 || Array.IndexOf(Illegal, ch) >= 0) sb.Append('_'); + else sb.Append(ch); + } + var s = sb.ToString().Trim().TrimEnd('.'); + while (s.Contains(" ", StringComparison.Ordinal)) s = s.Replace(" ", " ", StringComparison.Ordinal); + var stem = s.Split('.')[0]; + if (ReservedNames.Contains(stem)) s = "_" + s; + if (s is "." or "..") s = "_"; + return s.Length > 200 ? s[..200].TrimEnd() : s; + } + + private readonly record struct Part(bool IsToken, string Text, string? Format) + { + public static Part Literal(string text) => new(false, text, null); + public static Part Token(string name, string? format) => new(true, name, format); + } +} diff --git a/tests/Titano.Core.Tests/Naming/PathTemplateTests.cs b/tests/Titano.Core.Tests/Naming/PathTemplateTests.cs new file mode 100644 index 00000000..7b92e391 --- /dev/null +++ b/tests/Titano.Core.Tests/Naming/PathTemplateTests.cs @@ -0,0 +1,89 @@ +using Titano.Core.Naming; +using Titano.Testing; + +namespace Titano.Core.Tests.Naming; + +public sealed class PathTemplateTests +{ + private static readonly NamingContext Frame = new() + { + CapturedAt = new DateTime(2026, 9, 28, 18, 2, 11, 250), + SessionStart = new DateTime(2026, 9, 28, 18, 2, 11), + Session = 2, + Number = 1, + NumberInSession = 1, + CameraMake = "Canon", + CameraModel = "Canon EOS R5", + Lens = "RF24-70mm F2.8 L IS USM", + Iso = 400, + ExposureTime = 1.0 / 8, + FNumber = 8, + OriginalName = "IMG_0001", + Extension = "CR2", + Title = "Harbour sunset", + }; + + [Test] + public void DefaultTemplatesMatchTheBriefExample() + { + Assert.Equal("2026/2026-09-28 Canon EOS R5", PathTemplate.Parse(TemplateDefaults.Folder).ExpandFolder(Frame)); + Assert.Equal("2026-09-28_18-02-11_0001.CR2", PathTemplate.Parse(TemplateDefaults.File).ExpandFile(Frame)); + } + + [Theory] + [Case("{n:000000}", "000001.CR2")] + [Case("{date:yyyyMMdd}_{name}", "20260928_IMG_0001.CR2")] + [Case("{iso}_{shutter}_{aperture}", "400_1-8_f8.CR2")] + [Case("{name}.{ext}", "IMG_0001.CR2")] + [Case("{{literal}}_{n}", "{literal}_0001.CR2")] + [Case("{session}-{nsession:00}", "2-01.CR2")] + public void FileTokens(string template, string expected) => + Assert.Equal(expected, PathTemplate.Parse(template).ExpandFile(Frame)); + + [Test] + public void IllegalCharactersAreReplaced() + { + var context = Frame with { Title = "a:b*c?|e\"f" }; + Assert.Equal("a_b_c__d__e_f.CR2", PathTemplate.Parse("{title}").ExpandFile(context)); + } + + [Test] + public void TokenValuesNeverCreateFolders() + { + var context = Frame with { Lens = "18/55 mm" }; + Assert.Equal("2026/18-55 mm", PathTemplate.Parse("{year}/{lens}").ExpandFolder(context)); + } + + [Test] + public void ReservedWindowsNamesAreEscaped() => + Assert.Equal("_CON.CR2", PathTemplate.Parse("{title}").ExpandFile(Frame with { Title = "CON" })); + + [Test] + public void ErrorsCarryPositionAndToken() + { + var t = PathTemplate.Parse("{date}_{bogus}_{n"); + Assert.False(t.IsValid); + Assert.Contains(new TemplateError(7, "UnknownToken", "bogus"), t.Errors); + Assert.Contains(t.Errors, e => e.Code == "UnclosedBrace"); + } + + [Test] + public void EmptyExpansionFallsBackToOriginalName() => + Assert.Equal("IMG_0001.CR2", PathTemplate.Parse("{title}").ExpandFile(Frame with { Title = null })); + + [Theory] + [Case("NIKON CORPORATION", "NIKON Z 8", "Nikon Z 8")] + [Case("SONY", "ILCE-7M4", "SONY ILCE-7M4")] + [Case("Canon", "Canon EOS R5", "Canon EOS R5")] + [Case(null, "HERO12 Black", "HERO12 Black")] + public void CameraNameAvoidsDuplicatedBrand(string? make, string model, string expected) => + Assert.Equal(expected, PathTemplate.CameraName(make, model)); + + [Test] + public void ShutterFormatting() + { + Assert.Equal("1-250", PathTemplate.Shutter(0.004)); + Assert.Equal("2s", PathTemplate.Shutter(2)); + Assert.Equal(string.Empty, PathTemplate.Shutter(null)); + } +} diff --git a/tests/Titano.Testing/Assert.cs b/tests/Titano.Testing/Assert.cs index 9982419f..95818620 100644 --- a/tests/Titano.Testing/Assert.cs +++ b/tests/Titano.Testing/Assert.cs @@ -142,6 +142,17 @@ public static class Assert if (!collection.Contains(expected)) Fail($"{expression}: does not contain {Format(expected)}"); } + /// At least one element satisfies . + public static T Contains(IEnumerable collection, Func predicate, [CallerArgumentExpression(nameof(predicate))] string? expression = null) + { + foreach (var item in collection) + { + if (predicate(item)) return item; + } + Fail($"No element matches {expression}"); + return default!; + } + public static void DoesNotContain(T unexpected, IEnumerable collection, [CallerArgumentExpression(nameof(collection))] string? expression = null) { if (collection.Contains(unexpected)) Fail($"{expression}: unexpectedly contains {Format(unexpected)}");