From 9e7c608303ec0c7ff094512fc163f1e35ddcff5c Mon Sep 17 00:00:00 2001 From: sloane <1699281+sloanelybutsurely@users.noreply.github.com> Date: Sat, 24 Feb 2024 08:03:18 -0500 Subject: [PATCH] separate front matter parsing --- lib/sloane_sh/front_matter.ex | 17 +++++++++++ test/sloane_sh/front_matter_test.exs | 42 ++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 lib/sloane_sh/front_matter.ex create mode 100644 test/sloane_sh/front_matter_test.exs 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