summaryrefslogtreecommitdiff
path: root/markdown
diff options
context:
space:
mode:
authora73x <[email protected]>2024-08-27 19:43:56 +0100
committera73x <[email protected]>2024-08-27 20:23:18 +0100
commitd38fc83df3824b840f0b3930e4cb7236bdab84b2 (patch)
tree586a7f940291f933ef2a7e05b20dff21ded6d78a /markdown
parentcffb105a9ff8ed5d7aa04e5f4097368f6be38b8e (diff)
feat(content): support templating in content
this is tired person code don't write tired person code
Diffstat (limited to 'markdown')
-rw-r--r--markdown/markdown.go76
1 files changed, 76 insertions, 0 deletions
diff --git a/markdown/markdown.go b/markdown/markdown.go
new file mode 100644
index 0000000..0924208
--- /dev/null
+++ b/markdown/markdown.go
@@ -0,0 +1,76 @@
+package markdown
+
+import (
+ "bytes"
+ "fmt"
+ "io/fs"
+ "path/filepath"
+ "strings"
+
+ "git.sr.ht/~a73x/home"
+ "github.com/adrg/frontmatter"
+)
+
+type Content struct {
+ Meta map[string]any
+ Body string
+ Path string
+}
+
+func ParseContents() ([]Content, error) {
+ contentFS, err := fs.Sub(home.Content, "content")
+ if err != nil {
+ return nil, fmt.Errorf("no content found: %v", err)
+ }
+ contentFiles, err := glob(contentFS, ".", ".md")
+ if err != nil {
+ return nil, fmt.Errorf("failed to glob: %v", err)
+ }
+
+ res := make([]Content, 0, len(contentFiles))
+ for _, contentFile := range contentFiles {
+ c, err := parseMarkdownFile(contentFS, contentFile)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read markdown file: %v", err)
+ }
+
+ res = append(res, c)
+ }
+
+ return res, nil
+}
+
+func glob(embedded fs.FS, dir string, ext string) ([]string, error) {
+ files := []string{}
+ err := fs.WalkDir(embedded, dir, func(path string, d fs.DirEntry, err error) error {
+ if filepath.Ext(path) == ext {
+ files = append(files, path)
+ }
+ return nil
+ })
+
+ return files, err
+}
+
+func parseMarkdownFile(embedded fs.FS, path string) (Content, error) {
+ input, err := fs.ReadFile(embedded, path)
+ if err != nil {
+ return Content{}, fmt.Errorf("failed to read post: %v", err)
+ }
+
+ matter := map[string]any{}
+ matter["template"] = "default"
+ rest, err := frontmatter.Parse(bytes.NewBuffer(input), &matter)
+ if err != nil {
+ return Content{}, fmt.Errorf("failed to parse frontmatter: %v", err)
+ }
+ path = strings.Replace(path, ".md", "", 1)
+
+ mc := Content{
+ Body: string(rest),
+ Path: path,
+ Meta: matter,
+ }
+
+ return mc, nil
+}