From 70837bf6b11329d812c5c67bfaa480af2fb279b3 Mon Sep 17 00:00:00 2001 From: Justin Lin Date: Fri, 25 Jul 2025 01:07:50 +1000 Subject: [PATCH] feat: add frontmatter extraction --- main.go | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index abe8be3..4656f0f 100644 --- a/main.go +++ b/main.go @@ -9,6 +9,9 @@ import ( ) var tmpl = ` +--- +title: This is the title +--- Hello this is the text: {{ sh "hledger bal assets" }} ` @@ -22,11 +25,33 @@ func sh(command string) string { return fmt.Sprintf("\n```\n%s\n```\n", string(out)) } +func parseDocument(doc string) (frontmatter string, body string, err error) { + doc = strings.TrimLeft(doc, " \n") + sep := "---\n" + if !strings.HasPrefix(doc, sep) { + err = fmt.Errorf("Invalid document: frontmatter required.\n%s", doc) + return + } + parts := strings.Split(doc, sep) + if len(parts) < 3 { + err = fmt.Errorf("Invalid document: frontmatter required.\n%s", doc) + return + } + frontmatter = parts[1] + body = parts[2] + return +} + func main() { funcMap := template.FuncMap{ "sh": sh, } - t, err := template.New("foo").Funcs(funcMap).Parse(tmpl) + frontmatter, body, err := parseDocument(tmpl) + if err != nil { + panic(err) + } + fmt.Printf("'%s'", frontmatter) + t, err := template.New("foo").Funcs(funcMap).Parse(body) if err != nil { panic(err) }