Skip to content

AddFrontmatter still strips header comments when every key being added already exists #213

Closed

Description

@matt-edmondson

What's wrong

#212 (fixing #170) made AddFrontmatter insert new keys in front of the closing delimiter instead of rebuilding the header. That fix does not cover the case where every key passed in is already in the header. In that case nothing is added, yet the code still rebuilds the header from the parsed dictionary. The rebuild drops every comment and rewrites the formatting, which is exactly what #170 set out to stop.

  • Frontmatter/Frontmatter.cs:269-275: TryInsertIntoHeader returns false when added.Count == 0.
  • Frontmatter/Frontmatter.cs:226-231: when that returns false, AddFrontmatter falls back to ReplaceFrontmatter(input, combined).

Repro (HEAD e9bff27)

Frontmatter.AddFrontmatter("---\n# keep me\ntitle: A # c\n---\nBody\n", new() { ["title"] = "X" });
// returns "---\ntitle: A\n---\nBody\n"   (both comments are gone)

The same no-op path also rewrites values:

  • title: ~ becomes title:
  • 'title': a becomes title: a

Why it matters

A common use is stamping a property such as date or id across a content repository. The files that already carry the key gain nothing, yet they lose their comments and show up as noisy diffs.

Suggested fix

When there is a single readable block and added.Count == 0, keep the existing header text exactly as written. Join it to the body with JoinHeaderAndBody, so the body is written the same way a rebuild writes it and the #210/#211 behaviour is kept. Stacked blocks keep the fold-and-rebuild path.

Acceptance criteria

  • AddFrontmatter on a single-block header whose keys are all already present returns the header text unchanged, comments and quoting included.
  • A test next to AddKeepsHeaderTextTests.AddFrontmatter_SomeKeysAlreadyPresent_... covers the case where every key is already present.

Activity

  1. added
    bug
    on Oct 25, 2026
  2. matt-edmondson commented on Oct 26, 2026

    @matt-edmondson
    ContributorAuthor

    Triage


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions