diff --git a/lib/sloane_sh/front_matter.ex b/lib/sloane_sh/front_matter.ex new file mode 100644 index 0000000..c761b9e --- /dev/null +++ b/lib/sloane_sh/front_matter.ex @@ -0,0 +1,17 @@ +defmodule SloaneSH.FrontMatter do + @moduledoc """ + Parses TOML front matter out put files + """ + + def parse("+++" <> rest, _ctx) do + [toml, body] = String.split(rest, ["+++\n", "+++\r\n"], parts: 2) + + with {:ok, attrs} <- Toml.decode(toml, keys: :atoms) do + {:ok, attrs, body} + end + end + + def parse(body, _ctx) do + {:ok, %{}, body} + end +end diff --git a/test/sloane_sh/front_matter_test.exs b/test/sloane_sh/front_matter_test.exs new file mode 100644 index 0000000..001c281 --- /dev/null +++ b/test/sloane_sh/front_matter_test.exs @@ -0,0 +1,42 @@ +defmodule SloaneSH.FrontMatterTest do + use ExUnit.Case + + alias SloaneSH.FrontMatter + + test "parses TOML front matter" do + document = ~S""" + +++ + foo = "bar" + +++ + # Hello, World! + + This is a document with front matter. + """ + + assert {:ok, %{foo: "bar"}, "# Hello, World!" <> _} = FrontMatter.parse(document, %{}) + end + + test "returns an empty map is the document doesn't have front matter" do + document = ~S""" + # Hello, World! + + This is a document with front matter. + """ + + assert {:ok, %{} = map, document} = FrontMatter.parse(document, %{}) + assert %{} = map + end + + test "errors in TOML front matter produce an error" do + document = ~S""" + +++ + foo = "bar + +++ + # Hello, World! + + This is a document with front matter. + """ + + assert {:error, _} = FrontMatter.parse(document, %{}) + end +end