Skip to content

Commit 6c93c47

Browse files
committed
tomlkit may omit the newline: workaround limitations with regexes
Refs: python-poetry/tomlkit#48 python-poetry/tomlkit#352 python-poetry/tomlkit#400
1 parent 5388398 commit 6c93c47

1 file changed

Lines changed: 20 additions & 3 deletions

File tree

‎repomatic/init_project.py‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -333,10 +333,27 @@ def _update_tool_config(
333333

334334
modified = tomlkit.dumps(doc)
335335

336-
# tomlkit may omit the newline before ``[[header]]`` when appending
337-
# AoT entries, producing invalid TOML. Normalize so every ``[[``
338-
# starts on its own line with a preceding blank line.
336+
# tomlkit may omit the newline before section headers when replacing
337+
# or appending entries. Normalize so every ``[`` or ``[[`` starts on
338+
# its own line with a preceding blank line. This is a workaround for
339+
# several long-standing tomlkit bugs around whitespace after
340+
# programmatic edits:
341+
# - https://github.com/python-poetry/tomlkit/issues/48
342+
# - https://github.com/python-poetry/tomlkit/issues/352
343+
# - https://github.com/python-poetry/tomlkit/issues/400
344+
# No normalization API exists in tomlkit; revisit if one is added.
345+
# Regex on the serialized string is preferred over manipulating
346+
# tomlkit's per-item ``_trivia.indent`` because the internal
347+
# representation of dotted tables (``[tool.X]``) is non-trivial to
348+
# walk, and the trivia heuristics in ``_replace_at``/``_insert_at``
349+
# are themselves the source of the inconsistencies.
350+
#
351+
# 1. Fix ``[[`` not starting on its own line (AoT appending).
339352
modified = re.sub(r"(?<!\n)(\[\[)", r"\n\n\1", modified)
353+
# 2. Ensure a blank line before single-bracket ``[table]`` headers.
354+
# ``(?!\[)`` avoids matching the inner ``[`` of ``[[``.
355+
modified = re.sub(r"([^\n])\n(\[(?!\[))", r"\1\n\n\2", modified)
356+
# 3. Collapse excessive blank lines (3+) down to exactly one.
340357
modified = re.sub(r"\n{3,}\[", r"\n\n[", modified)
341358
if modified.strip() == content.strip():
342359
logging.info(f"[{comp.tool_section}] already up to date.")

0 commit comments

Comments
 (0)