Skip to content

Commit

Permalink
Strip out frontmatter from markdown
Browse files Browse the repository at this point in the history
  • Loading branch information
MatMoore committed May 26, 2024
1 parent 1611875 commit c8c5b93
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 10 deletions.
14 changes: 11 additions & 3 deletions lib/obsidian/parser/frontmatter_parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def parse(content)
complete = false

if first_line.chomp != "---"
return {}
return [{}, content]
end

lines = []
Expand All @@ -24,8 +24,16 @@ def parse(content)
lines << line
end

complete ? YAML.safe_load(lines.join) : {}
return {}, content if !complete

metadata = YAML.safe_load(lines.join)
rest = []
loop do
line = enumerator.next
rest << line
end
[metadata, rest.join]
rescue YAML::SyntaxError, StopIteration
{}
[{}, content]
end
end
4 changes: 2 additions & 2 deletions lib/obsidian/parser/markdown_parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ def expand_attachments(markdown_text, root:, media_root:)
end
end

def parse(markdown_text, root: nil, media_root: nil)
frontmatter = frontmatter_parser.parse(markdown_text)
def parse(raw_text, root: nil, media_root: nil)
frontmatter, markdown_text = frontmatter_parser.parse(raw_text)
normalized1 = expand_attachments(markdown_text, root: root, media_root: media_root)
normalized2 = expand_wikilinks(normalized1, root: root)
document = Markly.parse(normalized2, flags: Markly::SMART | Markly::UNSAFE | Markly::HARD_BREAKS, extensions: [:table, :tasklist, :autolink])
Expand Down
10 changes: 5 additions & 5 deletions spec/obsidian/parser/frontmatter_parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
bar: banana
---
some text
)
expect(parser.parse(content)).to eq({"foo" => 1, "bar" => "banana"})
)
expect(parser.parse(content)).to eq([{"foo" => 1, "bar" => "banana"}, "some text\n"])
end

it "returns empty hash for invalid yaml" do
Expand All @@ -19,18 +19,18 @@
---
some text
)
expect(parser.parse(content)).to eq({})
expect(parser.parse(content)).to eq([{}, content])
end

it "returns empty hash if the frontmatter is not terminated" do
content = %(---
some text
)
expect(parser.parse(content)).to eq({})
expect(parser.parse(content)).to eq([{}, content])
end

it "returns empty hash if no frontmatter" do
content = "hello world"
expect(parser.parse(content)).to eq({})
expect(parser.parse(content)).to eq([{}, content])
end
end

0 comments on commit c8c5b93

Please sign in to comment.