Packages

A frontmatter parser for gleam.

Current section

Files

Jump to
facet src facet.erl
Raw

src/facet.erl

-module(facet).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([parse/1]).
-export_type([error/0, frontmatter/0, document/0]).
-type error() :: empty | {parse_error, binary()}.
-type frontmatter() :: {toml, binary()} | {json, binary()} | {yaml, binary()}.
-type document() :: {document, gleam@option:option(frontmatter()), binary()}.
-file("/home/blu/git/ssg/facet/src/facet.gleam", 22).
-spec grab_frontmatter(
list(binary()),
list(binary()),
fun((binary()) -> frontmatter()),
binary()
) -> {ok, document()} | {error, error()}.
grab_frontmatter(Input, Frontmatter, Format_constructor, Delimiter) ->
case Input of
[] ->
{error, {parse_error, <<"expected ending delimitor"/utf8>>}};
[Line | Rest] when Line =:= Delimiter ->
Final_content = case Delimiter of
<<"}"/utf8>> ->
gleam@string:join(
lists:append(Frontmatter, [<<"}"/utf8>>]),
<<"\n"/utf8>>
);
_ ->
gleam@string:join(Frontmatter, <<"\n"/utf8>>)
end,
{ok,
{document,
{some, Format_constructor(Final_content)},
gleam@string:join(Rest, <<"\n"/utf8>>)}};
[Line@1 | Rest@1] ->
grab_frontmatter(
Rest@1,
lists:append(Frontmatter, [Line@1]),
Format_constructor,
Delimiter
)
end.
-file("/home/blu/git/ssg/facet/src/facet.gleam", 55).
-spec parse(binary()) -> {ok, document()} | {error, error()}.
parse(In) ->
Lines = begin
_pipe = In,
gleam@string:split(_pipe, <<"\n"/utf8>>)
end,
case Lines of
[] ->
{error, empty};
[<<"+++"/utf8>> | Rest] ->
grab_frontmatter(
Rest,
[],
fun(Field@0) -> {toml, Field@0} end,
<<"+++"/utf8>>
);
[<<"{"/utf8>> | Rest@1] ->
grab_frontmatter(
Rest@1,
[<<"{"/utf8>>],
fun(Field@0) -> {json, Field@0} end,
<<"}"/utf8>>
);
[<<"---"/utf8>> | Rest@2] ->
grab_frontmatter(
Rest@2,
[],
fun(Field@0) -> {yaml, Field@0} end,
<<"---"/utf8>>
);
Rest@3 ->
{ok, {document, none, gleam@string:join(Rest@3, <<"\n"/utf8>>)}}
end.