Skip to content

Frontmatter that holds only a comment or null throws NullReferenceException from ExtractBody, ExtractFrontmatter and CombineFrontmatter #134

Description

@matt-edmondson

What's wrong

In Frontmatter/YamlSerializer.cs (around lines 71–75), TryParseYamlObject calls Deserializer.Deserialize<Dictionary<object, object>>(input) and then runs foreach over the result. YamlDotNet returns null for a YAML document with no content: a comment only (# TODO), ~, or null. The foreach then throws NullReferenceException.

The method catches only YamlException, InvalidOperationException and ArgumentException, so the NRE escapes through ExtractFrontmatterObjects into every public entry point that parses the block.

Failure scenario (reproduced)

A draft file with a placeholder comment where the metadata will go:

---
# TODO
---
Body text
  • Frontmatter.ExtractBody(input) throws instead of returning "Body text".
  • Frontmatter.ExtractFrontmatter(input) throws instead of returning null (or an empty dictionary).
  • RemoveFrontmatter and CombineFrontmatter throw as well.

Repro (MSTest, fails today):

[TestMethod]
public void CommentOnlyFrontmatter_DoesNotThrow()
{
    string input = "---\n# nothing here yet\n---\nBody text\n";
    Assert.AreEqual("Body text", Frontmatter.ExtractBody(input));
}

[TestMethod]
public void CommentOnlyFrontmatter_ExtractFrontmatter_DoesNotThrow()
{
    Assert.IsNull(Frontmatter.ExtractFrontmatter("---\n# draft\n---\nBody\n"));
}

Observed: System.NullReferenceException at ktsu.Frontmatter.YamlSerializer.TryParseYamlObject (YamlSerializer.cs:75).

A tool that walks a folder of Markdown files stops at the first file that has a commented-out or null frontmatter block.

Suggested fix

Straight after the Deserialize call, add if (rawData is null) { return false; }. If an empty block should count as "has frontmatter", return an empty dictionary instead.

Acceptance: tests covering comment-only, ~ and null frontmatter blocks. ExtractBody returns the body, and ExtractFrontmatter, RemoveFrontmatter and CombineFrontmatter don't throw.

Activity

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

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions