Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 31 additions & 18 deletions bibtexparser/middlewares/fieldkeys.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import logging
from typing import Literal

from bibtexparser.library import Library
from bibtexparser.model import Entry
Expand All @@ -12,40 +13,52 @@
class NormalizeFieldKeys(BlockMiddleware):
"""Normalize field keys to lowercase.

In case of conflicts (e.g. both 'author' and 'Author' exist in the same entry),
a warning is emitted, and the last value wins.
When field keys collide after lowercasing (e.g. 'author' and 'Author'),
a warning is logged for each duplicate. The last value wins by default.

Some other middlewares, such as `SeparateCoAuthors`, assume lowercase key names.

:param allow_inplace_modification: See corresponding property.
:param collision_policy: Keep the ``"first"`` or ``"last"`` field encountered
for each normalized key. In both cases the output key keeps its first position.
"""

def __init__(self, allow_inplace_modification: bool = True):
def __init__(
self,
allow_inplace_modification: bool = True,
*,
collision_policy: Literal["first", "last"] = "last",
):
if collision_policy not in ("first", "last"):
raise ValueError(
f"collision_policy must be 'first' or 'last', got {collision_policy!r}"
)
super().__init__(
allow_inplace_modification=allow_inplace_modification,
allow_parallel_execution=True,
)
self._collision_policy = collision_policy

# docstr-coverage: inherited
def transform_entry(self, entry: Entry, library: "Library") -> Entry:
seen_normalized_keys: set[str] = set()
new_fields_dict: dict[str, Field] = {}
keep_first = self._collision_policy == "first"
action = "keeping previous value" if keep_first else "overriding previous value"
for field in entry.fields:
normalized_key: str = field.key.lower()
# if the normalized key is already present, apply "last one wins"
# otherwise preserve insertion order
# if a key is overwritten, emit a detailed warning
# if performance is a concern, we could emit a warning with only {entry.key}
# to remove "seen_normalized_keys" and this if statement
if normalized_key in seen_normalized_keys:
normalized_key = field.key.lower()
if normalized_key in new_fields_dict:
logger.warning(
f"NormalizeFieldKeys: in entry '{entry.key}': "
+ f"duplicate normalized key '{normalized_key}' "
+ f"(original '{field.key}'); overriding previous value"
"NormalizeFieldKeys: in entry '%s': duplicate normalized key '%s' "
"(original '%s'); %s",
entry.key,
normalized_key,
field.key,
action,
)
seen_normalized_keys.add(normalized_key)
if keep_first:
continue
field.key = normalized_key
new_fields_dict[normalized_key] = field

new_fields: list[Field] = list(new_fields_dict.values())
entry.fields = new_fields

entry.fields = list(new_fields_dict.values())
return entry
19 changes: 19 additions & 0 deletions docs/source/customize.rst
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,25 @@ Core Middleware

bibtexparser comes with a number of middleware options:

Field Key Normalization
:::::::::::::::::::::::

:class:`bibtexparser.middlewares.NormalizeFieldKeys` converts field keys to lowercase.
If keys such as ``Title`` and ``title`` collide, the middleware logs a warning and
keeps the last field by default. Pass ``collision_policy="first"`` to keep the first
field instead. The position of the resulting key is determined by its first occurrence.

.. code-block:: python

import bibtexparser
from bibtexparser.middlewares import NormalizeFieldKeys

library = bibtexparser.parse_string(
"@misc{example, Title={First}, title={Last}}",
append_middleware=[NormalizeFieldKeys(collision_policy="first")],
)
assert library.entries_dict["example"]["title"] == "First"

.. _middleware_encoding:

Encoding and Enclosing of Values
Expand Down
62 changes: 62 additions & 0 deletions tests/middleware_tests/test_fieldkeys.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import re

import pytest

from bibtexparser import Library
from bibtexparser import parse_string
from bibtexparser import write_string
from bibtexparser.middlewares.fieldkeys import NormalizeFieldKeys
from bibtexparser.model import Entry
from bibtexparser.model import Field
Expand Down Expand Up @@ -68,3 +72,61 @@ def test_normalize_fieldkeys_force_last(caplog):

for key in lib.entries_dict:
assert lib.entries_dict[key] == ref.entries_dict[key]


@pytest.mark.parametrize("policy", ["first", "last"])
@pytest.mark.parametrize("inplace", [False, True])
@pytest.mark.parametrize("reverse", [False, True])
def test_normalize_fieldkeys_collision_policy(policy, inplace, reverse, caplog):
collisions = [("Title", "Alpha"), ("title", "Beta"), ("TITLE", "Gamma")]
if reverse:
collisions.reverse()
original_fields = [collisions[0], ("Year", "2026"), collisions[1], ("note", "N"), collisions[2]]
entry = Entry("Article", "ExampleKey", [Field(key, value) for key, value in original_fields])
library = Library(blocks=[entry])

middleware = NormalizeFieldKeys(inplace, collision_policy=policy)
result = middleware.transform(library).entries[0]

winner = collisions[0 if policy == "first" else -1][1]
expected_fields = [("title", winner), ("year", "2026"), ("note", "N")]
assert [(field.key, field.value) for field in result.fields] == expected_fields
assert (result.entry_type, result.key) == ("Article", "ExampleKey")
assert (result is entry) == inplace
if not inplace:
assert [(field.key, field.value) for field in entry.fields] == original_fields

action = "keeping previous value" if policy == "first" else "overriding previous value"
assert caplog.messages == [
f"NormalizeFieldKeys: in entry 'ExampleKey': duplicate normalized key 'title' "
f"(original '{key}'); {action}"
for key, _ in collisions[1:]
]

caplog.clear()
reapplied = middleware.transform(Library(blocks=[result])).entries[0]
assert [(field.key, field.value) for field in reapplied.fields] == expected_fields
assert not caplog.messages


@pytest.mark.parametrize("policy, title", [("first", "Alpha"), ("last", "Beta")])
def test_normalize_fieldkeys_round_trip(policy, title):
library = parse_string(
"@article{ExampleKey, Title={Alpha}, title={Beta}, Year={2026}}",
append_middleware=[NormalizeFieldKeys(collision_policy=policy)],
)

entry = parse_string(write_string(library)).entries_dict["ExampleKey"]
assert {field.key: field.value for field in entry.fields} == {"title": title, "year": "2026"}


def test_normalize_fieldkeys_invalid_collision_policy():
with pytest.raises(ValueError, match="collision_policy"):
NormalizeFieldKeys(collision_policy="unknown")


def test_normalize_fieldkeys_first_policy_accepts_empty_entry(caplog):
library = Library(blocks=[Entry("misc", "Empty", [])])
result = NormalizeFieldKeys(collision_policy="first").transform(library)
assert result.entries_dict["Empty"].fields == []
assert not caplog.messages