From b38e4e4a0066e808a48430770d3f026736f326d9 Mon Sep 17 00:00:00 2001 From: Amalkrishna A S <77876890+AmalkrishnaAS@users.noreply.github.com> Date: Tue, 20 Oct 2026 10:52:05 +0530 Subject: [PATCH] feat(naming): add {AuthorSort} template variable (#1484) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #1178. Adds `{AuthorSort}`, the first author surname-first ("Arthur Conan Doyle" → "Doyle, Arthur Conan"), for rename and organize templates, alongside `{FirstAuthor}`. - A value already in "Last, First" form (one word before the comma) is kept as is; Jr/Sr/II/III/IV stay at the end. - Known limits, same as calibre's default: the last word is treated as the surname, so particles ("Le Guin") and surname-first names aren't detected. - Added to the settings help, env docs, the frontend variable picker/preview, and tests. --- docs/environment-variables.md | 16 ++--- shelfmark/config/settings.py | 8 +-- shelfmark/core/naming.py | 40 +++++++++++ .../src/tests/namingTemplatePreview.test.ts | 22 ++++++ .../src/utils/namingTemplatePreview.ts | 40 +++++++++++ tests/config/test_generate_env_docs.py | 2 +- .../test_author_sort_template_variable.py | 70 +++++++++++++++++++ 7 files changed, 185 insertions(+), 13 deletions(-) create mode 100644 tests/core/test_author_sort_template_variable.py diff --git a/docs/environment-variables.md b/docs/environment-variables.md index accd63fa..ce3b9672 100644 --- a/docs/environment-variables.md +++ b/docs/environment-variables.md @@ -513,8 +513,8 @@ Audiobooks only. AudiobookBay lists it for most releases. In Prowlarr results it | `INGEST_DIR` | Directory where downloaded files are saved. Use {User} for per-user folders (e.g. /books/{User}). | string | `/books` | | `FILE_ORGANIZATION` | Choose how downloaded book files are named and organized. | string (choice) | `rename` | | `NAMING_WORD_SEPARATOR` | Replaces spaces inside naming template values (e.g. 'Conan Doyle' -> 'Conan.Doyle' with '.'). Applies to books and audiobooks, rename and organize templates alike. Literal characters typed into a template (like the '-' in '{Author} - {Title}') are left as-is. Leave empty to keep spaces as-is. | string | _empty string_ | -| `TEMPLATE_RENAME` | Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension). Universal adds: {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. Rename templates are filename-only (no '/' or '\'); use Organize for folders. Applies to single-file downloads. | string | `{Author} - {Title} ({Year})` | -| `TEMPLATE_ORGANIZE` | Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension). Universal adds: {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. | string | `{Author}/{Title} ({Year})` | +| `TEMPLATE_RENAME` | Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension). Universal adds: {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. Rename templates are filename-only (no '/' or '\'); use Organize for folders. Applies to single-file downloads. | string | `{Author} - {Title} ({Year})` | +| `TEMPLATE_ORGANIZE` | Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension). Universal adds: {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. | string | `{Author}/{Title} ({Year})` | | `HARDLINK_TORRENTS` | Create hardlinks instead of copying. Preserves seeding but archives won't be extracted. Don't use if destination is a library ingest folder. | boolean | `false` | | `BOOKLORE_HOST` | Base URL of your Grimmory instance | string | _none_ | | `BOOKLORE_USERNAME` | Grimmory account username | string | _none_ | @@ -535,8 +535,8 @@ Audiobooks only. AudiobookBay lists it for most releases. In Prowlarr results it | `EMAIL_ALLOW_UNVERIFIED_TLS` | Disable TLS certificate verification (not recommended). | boolean | `false` | | `DESTINATION_AUDIOBOOK` | Directory where downloaded audiobook files are saved. Leave empty to use the Books destination. | string | _none_ | | `FILE_ORGANIZATION_AUDIOBOOK` | Choose how downloaded audiobook files are named and organized. | string (choice) | `rename` | -| `TEMPLATE_AUDIOBOOK_RENAME` | Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension), {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. Rename templates are filename-only (no '/' or '\'); use Organize for folders. Applies to single-file downloads. | string | `{Author} - {Title}` | -| `TEMPLATE_AUDIOBOOK_ORGANIZE` | Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension), {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. {Narrator} and a Series fallback come from MyAnonamouse results (needs a MAM session ID); {{Narrator}} writes Audiobookshelf's '{Name}' style and is left out entirely when there is no narrator. | string | `{Author}/{Title}/{Title}` | +| `TEMPLATE_AUDIOBOOK_RENAME` | Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension), {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. Rename templates are filename-only (no '/' or '\'); use Organize for folders. Applies to single-file downloads. | string | `{Author} - {Title}` | +| `TEMPLATE_AUDIOBOOK_ORGANIZE` | Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension), {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. {Narrator} and a Series fallback come from MyAnonamouse results (needs a MAM session ID); {{Narrator}} writes Audiobookshelf's '{Name}' style and is left out entirely when there is no narrator. | string | `{Author}/{Title}/{Title}` | | `HARDLINK_TORRENTS_AUDIOBOOK` | Create hardlinks instead of copying. Preserves seeding but archives won't be extracted. Don't use if destination is a library ingest folder. | boolean | `true` | | `AUTO_OPEN_DOWNLOADS_SIDEBAR` | Automatically open the downloads sidebar when a new download is queued. | boolean | `false` | | `DOWNLOAD_TO_BROWSER_CONTENT_TYPES` | Automatically download completed files to your browser for the selected content types. | string (comma-separated) | _empty list_ | @@ -589,7 +589,7 @@ Replaces spaces inside naming template values (e.g. 'Conan Doyle' -> 'Conan.Doyl **Naming Template** -Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension). Universal adds: {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. Rename templates are filename-only (no '/' or '\'); use Organize for folders. Applies to single-file downloads. +Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension). Universal adds: {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. Rename templates are filename-only (no '/' or '\'); use Organize for folders. Applies to single-file downloads. - **Type:** string - **Default:** `{Author} - {Title} ({Year})` @@ -598,7 +598,7 @@ Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, **Path Template** -Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension). Universal adds: {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. +Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension). Universal adds: {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. - **Type:** string - **Default:** `{Author}/{Title} ({Year})` @@ -799,7 +799,7 @@ Choose how downloaded audiobook files are named and organized. **Naming Template** -Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension), {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. Rename templates are filename-only (no '/' or '\'); use Organize for folders. Applies to single-file downloads. +Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension), {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. Rename templates are filename-only (no '/' or '\'); use Organize for folders. Applies to single-file downloads. - **Type:** string - **Default:** `{Author} - {Title}` @@ -808,7 +808,7 @@ Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, **Path Template** -Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension), {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. {Narrator} and a Series fallback come from MyAnonamouse results (needs a MAM session ID); {{Narrator}} writes Audiobookshelf's '{Name}' style and is left out entirely when there is no narrator. +Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, {OriginalName} (source filename without extension), {Series}, {SeriesPosition}, {Subtitle}, {PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix: {Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. {Narrator} and a Series fallback come from MyAnonamouse results (needs a MAM session ID); {{Narrator}} writes Audiobookshelf's '{Name}' style and is left out entirely when there is no narrator. - **Type:** string - **Default:** `{Author}/{Title}/{Title}` diff --git a/shelfmark/config/settings.py b/shelfmark/config/settings.py index 6ad7c9d2..ee064b64 100644 --- a/shelfmark/config/settings.py +++ b/shelfmark/config/settings.py @@ -1138,7 +1138,7 @@ def download_settings() -> list[SettingsField]: key="TEMPLATE_RENAME", label="Naming Template", description=( - "Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, {OriginalName} " + "Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, {OriginalName} " "(source filename without extension). Universal adds: {Series}, " "{SeriesPosition}, {Subtitle}, {PrimaryTitle}. Use arbitrary prefix/suffix: " "{Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. " @@ -1157,7 +1157,7 @@ def download_settings() -> list[SettingsField]: key="TEMPLATE_ORGANIZE", label="Path Template", description=( - "Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, " + "Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, " "{OriginalName} (source filename without extension). Universal adds: {Series}, " "{SeriesPosition}, {Subtitle}, {PrimaryTitle}. Use arbitrary prefix/suffix: " "{Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty." @@ -1425,7 +1425,7 @@ def download_settings() -> list[SettingsField]: key="TEMPLATE_AUDIOBOOK_RENAME", label="Naming Template", description=( - "Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, {OriginalName} " + "Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, {OriginalName} " "(source filename without extension), {Series}, {SeriesPosition}, {Subtitle}, " "{PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix: " "{Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. " @@ -1445,7 +1445,7 @@ def download_settings() -> list[SettingsField]: key="TEMPLATE_AUDIOBOOK_ORGANIZE", label="Path Template", description=( - "Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, {User}, " + "Use / to create folders. Variables: {Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, {User}, " "{OriginalName} (source filename without extension), {Series}, {SeriesPosition}, " "{Subtitle}, {PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix: " "{Vol. SeriesPosition - } outputs 'Vol. 2 - ' when set, nothing when empty. " diff --git a/shelfmark/core/naming.py b/shelfmark/core/naming.py index 2ea9f2c6..0d852b4c 100644 --- a/shelfmark/core/naming.py +++ b/shelfmark/core/naming.py @@ -20,6 +20,7 @@ KNOWN_TOKENS = [ "primarytitle", "originalname", "firstauthor", + "authorsort", "partnumber", "language", "narrator", @@ -76,6 +77,43 @@ def first_author(value: object) -> str: return AUTHOR_LIST_SEPARATOR.split(text, maxsplit=1)[0].strip() +# Generational suffixes kept after the given names: "King, Martin Luther, Jr." +NAME_SUFFIXES = frozenset({"jr", "jr.", "sr", "sr.", "ii", "iii", "iv"}) + + +def author_sort(value: object) -> str: + """Return the first author as "Last, First" for {AuthorSort}. + + "Arthur Conan Doyle" becomes "Doyle, Arthur Conan", and only the first of + several authors is kept. Exactly two comma-separated parts whose first part + is a single word ("Doyle, Arthur Conan") are taken to be one name already in + "Last, First" form and kept as is. Surname particles ("van", "Le") and + surname-first names are not detected; their last word is treated as the + surname (see #1178). + """ + text = " ".join(str(value or "").split()) + if not text: + return "" + + entries = [entry for entry in AUTHOR_LIST_SEPARATOR.split(text) if entry] + if not entries: + return "" + if len(entries) == 2 and " " not in entries[0] and ";" not in text: + return f"{entries[0]}, {entries[1]}" + + words = entries[0].split(" ") + suffix = "" + if len(entries) > 1 and entries[1].lower() in NAME_SUFFIXES: + suffix = entries[1] + elif len(words) > 2 and words[-1].lower() in NAME_SUFFIXES: + suffix = words.pop() + + if len(words) < 2: + return entries[0] + sorted_name = f"{words[-1]}, {' '.join(words[:-1])}" + return f"{sorted_name}, {suffix}" if suffix else sorted_name + + def format_series_position(position: str | float | None) -> str: """Format a series position for naming templates.""" if position is None: @@ -193,6 +231,8 @@ def parse_naming_template( value = format_series_position(value) elif placeholder_name == "firstauthor" and not value: value = first_author(normalized.get("author")) + elif placeholder_name == "authorsort" and not value: + value = author_sort(normalized.get("author")) if value is None: return "" return str(value).strip() diff --git a/src/frontend/src/tests/namingTemplatePreview.test.ts b/src/frontend/src/tests/namingTemplatePreview.test.ts index 5175dc38..a462c036 100644 --- a/src/frontend/src/tests/namingTemplatePreview.test.ts +++ b/src/frontend/src/tests/namingTemplatePreview.test.ts @@ -8,6 +8,13 @@ import { SAMPLE_NAMING_METADATA, } from '../utils/namingTemplatePreview'; +const renderAuthorSort = (author: string): string => + renderNamingTemplate( + '{AuthorSort}/{Year}', + { ...SAMPLE_NAMING_METADATA, Author: author, AuthorSort: '' }, + { allowPathSeparators: true }, + ).value; + describe('namingTemplatePreview', () => { it('renders Audiobookshelf-style {{Narrator}} and drops it cleanly when empty', () => { const template = '{Author}/{Title} {{Narrator}}/{Title}'; @@ -69,6 +76,21 @@ describe('namingTemplatePreview', () => { expect(preview.value).toBe('Terry Pratchett/1902'); }); + it('renders AuthorSort surname first from the first author', () => { + expect(renderAuthorSort('Arthur Conan Doyle')).toBe('Doyle, Arthur Conan/1902'); + expect(renderAuthorSort('Terry Pratchett, Neil Gaiman')).toBe('Pratchett, Terry/1902'); + expect(renderAuthorSort('Doyle, Arthur Conan')).toBe('Doyle, Arthur Conan/1902'); + // The trailing dot of "Jr." is stripped like any other trailing dot in a path component. + expect(renderAuthorSort('Martin Luther King Jr.')).toBe('King, Martin Luther, Jr/1902'); + }); + + it('offers AuthorSort as a core variable', () => { + const token = NAMING_TEMPLATE_TOKENS.find((t) => t.token === 'AuthorSort'); + + expect(token?.group).toBe('Core'); + expect(token?.audiobookOnly).toBeFalsy(); + }); + it('offers FirstAuthor as a core variable', () => { const token = NAMING_TEMPLATE_TOKENS.find((t) => t.token === 'FirstAuthor'); diff --git a/src/frontend/src/utils/namingTemplatePreview.ts b/src/frontend/src/utils/namingTemplatePreview.ts index c7fdfd85..b790ac80 100644 --- a/src/frontend/src/utils/namingTemplatePreview.ts +++ b/src/frontend/src/utils/namingTemplatePreview.ts @@ -36,6 +36,13 @@ export const NAMING_TEMPLATE_TOKENS: NamingTemplateToken[] = [ value: 'Arthur Conan Doyle', group: 'Core', }, + { + token: 'AuthorSort', + label: 'Author (surname first)', + description: 'First author as "Last, First"', + value: 'Doyle, Arthur Conan', + group: 'Core', + }, { token: 'Title', label: 'Full title', @@ -123,6 +130,7 @@ const KNOWN_TOKENS = [ 'primarytitle', 'originalname', 'firstauthor', + 'authorsort', 'partnumber', 'language', 'narrator', @@ -138,6 +146,35 @@ const KNOWN_TOKENS = [ // pre-joined with ',' or ';' and {FirstAuthor} keeps only the first entry. const firstAuthor = (value: string): string => value.split(/\s*[,;]\s*/)[0]?.trim() ?? ''; +// Mirrors author_sort() in shelfmark/core/naming.py. +const NAME_SUFFIXES = new Set(['jr', 'jr.', 'sr', 'sr.', 'ii', 'iii', 'iv']); + +const authorSort = (value: string): string => { + const text = value.split(/\s+/).filter(Boolean).join(' '); + const entries = text.split(/\s*[,;]\s*/).filter(Boolean); + const [first, second] = entries; + if (!first) { + return ''; + } + if (entries.length === 2 && second && !first.includes(' ') && !text.includes(';')) { + return `${first}, ${second}`; + } + + const words = first.split(' '); + let suffix = ''; + if (second && NAME_SUFFIXES.has(second.toLowerCase())) { + suffix = second; + } else if (words.length > 2 && NAME_SUFFIXES.has(words[words.length - 1].toLowerCase())) { + suffix = words.pop() ?? ''; + } + + if (words.length < 2) { + return first; + } + const sorted = `${words[words.length - 1]}, ${words.slice(0, -1).join(' ')}`; + return suffix ? `${sorted}, ${suffix}` : sorted; +}; + const BRACE_PATTERN = /\{([^}]+)\}/g; const INVALID_CHARS_PATTERN = /[\\/:*?"<>|]/g; const WHITESPACE_RUN_PATTERN = /\s+/g; @@ -191,6 +228,9 @@ export const renderNamingTemplate = ( if (placeholderName === 'firstauthor' && !normalized['firstauthor']) { return firstAuthor(normalized['author'] ?? ''); } + if (placeholderName === 'authorsort' && !normalized['authorsort']) { + return authorSort(normalized['author'] ?? ''); + } return (normalized[placeholderName] ?? '').trim(); }; diff --git a/tests/config/test_generate_env_docs.py b/tests/config/test_generate_env_docs.py index 475b28e1..40877e47 100644 --- a/tests/config/test_generate_env_docs.py +++ b/tests/config/test_generate_env_docs.py @@ -53,7 +53,7 @@ def test_generated_env_docs_include_custom_component_value_fields() -> None: assert ( "| `TEMPLATE_AUDIOBOOK_ORGANIZE` | Use / to create folders. Variables: " - "{Author}, {FirstAuthor} (first of several authors), {Title}, {Year}, {Language}, " + "{Author}, {FirstAuthor} (first of several authors), {AuthorSort} (first author, surname first), {Title}, {Year}, {Language}, " "{User}, {OriginalName} " "(source filename without extension), {Series}, {SeriesPosition}, {Subtitle}, " "{PrimaryTitle}, {PartNumber}, {Narrator}. Use arbitrary prefix/suffix:" diff --git a/tests/core/test_author_sort_template_variable.py b/tests/core/test_author_sort_template_variable.py new file mode 100644 index 00000000..2914cb73 --- /dev/null +++ b/tests/core/test_author_sort_template_variable.py @@ -0,0 +1,70 @@ +"""Tests for the {AuthorSort} template variable support (issue #1178).""" + +import pytest + +from shelfmark.core.naming import KNOWN_TOKENS, author_sort, parse_naming_template + + +class TestAuthorSortInKnownTokens: + def test_author_sort_in_known_tokens(self): + assert "authorsort" in KNOWN_TOKENS + + def test_author_sort_is_matched_before_author(self): + # "authorsort" contains "author"; the longest-first ordering must keep + # {AuthorSort} from being parsed as {Author} + literal "Sort". + assert KNOWN_TOKENS.index("authorsort") < KNOWN_TOKENS.index("author") + + +class TestAuthorSortHelper: + @pytest.mark.parametrize( + ("value", "expected"), + [ + ("Arthur Conan Doyle", "Doyle, Arthur Conan"), + ("Terry Pratchett", "Pratchett, Terry"), + (" Terry Pratchett ", "Pratchett, Terry"), + ("Terry Pratchett, Neil Gaiman", "Pratchett, Terry"), + ("Terry Pratchett; Neil Gaiman", "Pratchett, Terry"), + ("Martin Luther King Jr.", "King, Martin Luther, Jr."), + ("Martin Luther King, Jr.", "King, Martin Luther, Jr."), + ("Plato", "Plato"), + ("", ""), + (None, ""), + ], + ) + def test_author_sort(self, value, expected): + assert author_sort(value) == expected + + @pytest.mark.parametrize( + "value", + ["Doyle, Arthur Conan", "Pratchett, Terry"], + ) + def test_name_already_in_last_first_form_is_kept(self, value): + assert author_sort(value) == value + + def test_surname_particles_are_not_detected(self): + # Documented limitation: the last word is treated as the surname. + assert author_sort("Ursula K. Le Guin") == "Guin, Ursula K. Le" + + +class TestAuthorSortTemplateRendering: + def test_renders_last_first(self): + metadata = {"Author": "Arthur Conan Doyle", "Title": "A Study in Scarlet"} + assert parse_naming_template("{AuthorSort}/{Title}", metadata) == ( + "Doyle, Arthur Conan/A Study in Scarlet" + ) + + def test_case_insensitive(self): + assert parse_naming_template("{authorsort}", {"Author": "Terry Pratchett"}) == ( + "Pratchett, Terry" + ) + + def test_explicit_author_sort_key_wins_over_derivation(self): + metadata = {"Author": "Terry Pratchett", "AuthorSort": "Custom"} + assert parse_naming_template("{AuthorSort}", metadata) == "Custom" + + def test_empty_author_renders_nothing(self): + assert parse_naming_template("{AuthorSort}", {"Author": ""}) == "" + + def test_author_token_is_unaffected(self): + metadata = {"Author": "Terry Pratchett"} + assert parse_naming_template("{Author}", metadata) == "Terry Pratchett"