Skip to content

Commit

Permalink
Add a frontmatter parser
Browse files Browse the repository at this point in the history
  • Loading branch information
MatMoore committed May 10, 2024
1 parent 0d9fa24 commit 3355e4e
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/obsidian/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
require_relative "parser/page"
require_relative "parser/html_renderer"
require_relative "parser/content_type"
require_relative "parser/frontmatter_parser"

require "forwardable"

Expand Down
27 changes: 27 additions & 0 deletions lib/obsidian/parser/frontmatter_parser.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
require 'yaml'

class Obsidian::MarkdownParser::FrontMatterParser
# Look for frontmatter delimited by '---' lines
# and try to interpret it as yaml.
# If it is valid YAML, then denotes properties.
# https://help.obsidian.md/Editing+and+formatting/Properties#Property+format
def parse(content)
enumerator = content.each_line
first_line = enumerator.next

if first_line.chomp != "---"
return {}
end

lines = []
while true
line = enumerator.next
break if line.chomp == "---"
lines << line
end

YAML.safe_load(lines.join)
rescue YAML::SyntaxError, StopIteration => ex
{}
end
end
36 changes: 36 additions & 0 deletions spec/obsidian/parser/frontmatter_parser.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# frozen_string_literal: true

RSpec.describe(Obsidian::MarkdownParser::FrontMatterParser) do
subject(:parser) { described_class.new }
it "parses valid yaml" do
content = %(---
foo: 1
bar: banana
---
some text
)
expect(parser.parse(content)).to eq({"foo" => 1, "bar" => "banana"})
end

it "returns empty hash for invalid yaml" do
content = %(---
{
---
some text
)
expect(parser.parse(content)).to eq({})
end

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


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

0 comments on commit 3355e4e

Please sign in to comment.