refactored some modules

This commit is contained in:
Daniel Fichtinger 2024-11-24 21:14:38 -05:00
parent 68d2ddb692
commit 11f724732d
4 changed files with 102 additions and 69 deletions

View file

@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"html/template"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
@ -13,13 +14,15 @@ type PageData struct {
Title string
Icon string
Stylesheet string
Header template.HTML
Header string
Content template.HTML
NextPost template.HTML
PrevPost template.HTML
Footer template.HTML
NextPost string
PrevPost string
Footer string
}
type Metadata map[string]interface{}
func processWithYaml(f []byte) (Metadata, []byte, error) {
// Check if the file has valid metadata
if !bytes.HasPrefix(f, []byte("---\n")) {
@ -31,12 +34,43 @@ func processWithYaml(f []byte) (Metadata, []byte, error) {
if len(split) < 3 {
return nil, nil, fmt.Errorf("Invalid frontmatter format.")
}
var metadata Metadata
var meta Metadata
// Parse YAML
if err := yaml.Unmarshal([]byte(split[1]), &metadata); err != nil {
if err := yaml.Unmarshal([]byte(split[1]), &meta); err != nil {
return nil, nil, err
}
return metadata, []byte(split[2]), nil
return meta, []byte(split[2]), nil
}
// this function converts a file path to its title form
func pathToTitle(path string) string {
stripped := ChangeExtension(filepath.Base(path), "")
replaced := strings.NewReplacer("-", " ", "_", " ", `\ `, " ").Replace(stripped)
return strings.ToTitle(replaced)
}
func buildPageData(m Metadata) *PageData {
p := &PageData{}
if title, ok := m["title"].(string); ok {
p.Title = title
} else {
p.Title = pathToTitle(m["path"].(string))
}
if icon, ok := m["icon"].(string); ok {
p.Icon = icon
} else {
p.Icon = ""
}
if style, ok := m["style"].(string); ok {
p.Stylesheet = style
}
if header, ok := m["header"].(string); ok {
p.Header = header
}
if footer, ok := m["footer"].(string); ok {
p.Footer = footer
}
return p
}
func ConvertFile(in string, out string) error {
@ -48,14 +82,14 @@ func ConvertFile(in string, out string) error {
if err != nil {
return err
}
metadata["path"] = in
pd := buildPageData(metadata)
fmt.Println("Page title: ", pd.Title)
pd.Content = template.HTML(md)
title, ok := metadata["title"].(string)
if !ok {
fmt.Println("No title in page.")
} else {
fmt.Println("Title found: ", title)
}
tmlp, err := template.New("webpage").Parse("placeholder")
// build according to template here
html, err := MdToHTML(md)
if err != nil {
return err