refactoring; began implementing embedding

This commit is contained in:
Daniel Fichtinger 2024-11-25 14:55:45 -05:00
parent 12ebba687b
commit 4d1b18fd12
11 changed files with 96 additions and 50 deletions

View file

@ -1 +0,0 @@
package main

View file

@ -6,7 +6,7 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/ficcdaf/zona/internal/build" "github.com/ficcdaf/zona/internal/builder"
) )
// // validateFile checks whether a given path // // validateFile checks whether a given path
@ -41,7 +41,8 @@ func main() {
} }
} }
err := build.Traverse(*rootPath, "foobar") settings := builder.GetSettings()
err := builder.Traverse(*rootPath, "foobar", settings)
if err != nil { if err != nil {
fmt.Printf("Error: %s\n", err.Error()) fmt.Printf("Error: %s\n", err.Error())
} }

View file

@ -1,4 +1,4 @@
package build package builder
import ( import (
"bytes" "bytes"
@ -6,6 +6,7 @@ import (
"html/template" "html/template"
"strings" "strings"
"github.com/ficcdaf/zona/internal/util"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
@ -18,6 +19,7 @@ type PageData struct {
NextPost string NextPost string
PrevPost string PrevPost string
Footer string Footer string
Template string
} }
type Metadata map[string]interface{} type Metadata map[string]interface{}
@ -41,37 +43,37 @@ func processWithYaml(f []byte) (Metadata, []byte, error) {
return meta, []byte(split[2]), nil return meta, []byte(split[2]), nil
} }
func buildPageData(m Metadata, path string) *PageData { func buildPageData(m Metadata, path string, settings *Settings) *PageData {
p := &PageData{} p := &PageData{}
if title, ok := m["title"].(string); ok { if title, ok := m["title"].(string); ok {
p.Title = wordsToTitle(title) p.Title = util.WordsToTitle(title)
} else { } else {
p.Title = pathToTitle(path) p.Title = util.PathToTitle(path)
} }
if icon, ok := m["icon"].(string); ok { if icon, ok := m["icon"].(string); ok {
p.Icon = icon p.Icon = icon
} else { } else {
p.Icon = DefaultIcon p.Icon = settings.Icon
} }
if style, ok := m["style"].(string); ok { if style, ok := m["style"].(string); ok {
p.Stylesheet = style p.Stylesheet = style
} else { } else {
p.Stylesheet = DefaultStylesheet p.Stylesheet = settings.Stylesheet
} }
if header, ok := m["header"].(string); ok { if header, ok := m["header"].(string); ok {
p.Header = header p.Header = header
} else { } else {
p.Header = DefaultHeader p.Header = settings.Header
} }
if footer, ok := m["footer"].(string); ok { if footer, ok := m["footer"].(string); ok {
p.Footer = footer p.Footer = footer
} else { } else {
p.Footer = DefaultFooter p.Footer = settings.Footer
} }
return p return p
} }
func ConvertFile(in string, out string) error { func ConvertFile(in string, out string, settings *Settings) error {
mdPre, err := ReadFile(in) mdPre, err := ReadFile(in)
if err != nil { if err != nil {
return err return err
@ -80,7 +82,7 @@ func ConvertFile(in string, out string) error {
if err != nil { if err != nil {
return err return err
} }
pd := buildPageData(metadata, in) pd := buildPageData(metadata, in, settings)
fmt.Println("Title: ", pd.Title) fmt.Println("Title: ", pd.Title)
// build according to template here // build according to template here
@ -90,7 +92,7 @@ func ConvertFile(in string, out string) error {
} }
pd.Content = template.HTML(html) pd.Content = template.HTML(html)
tmpl, err := template.New("webpage").Parse(DefaultTemplate) tmpl, err := template.New("webpage").Parse(settings.DefaultTemplate)
if err != nil { if err != nil {
return err return err
} }

View file

@ -1,4 +1,8 @@
package build package builder
import (
"embed"
)
const ( const (
DefaultHeader = "" DefaultHeader = ""
@ -35,18 +39,31 @@ const (
</html>` </html>`
) )
//go:embed embed
var embedDir embed.FS
type Settings struct { type Settings struct {
Header string Header string
Footer string Footer string
Stylesheet string Stylesheet string
Icon string Icon string
DefaultTemplate string
} }
func NewSettings(header string, footer string, style string, icon string) *Settings { func NewSettings(header string, footer string, style string, icon string, temp string) *Settings {
return &Settings{ return &Settings{
header, header,
footer, footer,
style, style,
icon, icon,
temp,
} }
} }
func GetSettings() *Settings {
// TODO: Read a config file to override defaults
// "Defaults" should be a default config file via embed package,
// so the settings func should need to handle one case:
// check if config file exists, if not, use embedded one
return NewSettings(DefaultHeader, DefaultFooter, DefaultStylesheet, DefaultIcon, DefaultTemplate)
}

View file

@ -1,12 +1,12 @@
package build package builder
import ( import (
"fmt" "fmt"
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"github.com/ficcdaf/zona/internal/util"
"github.com/gomarkdown/markdown" "github.com/gomarkdown/markdown"
"github.com/gomarkdown/markdown/ast" "github.com/gomarkdown/markdown/ast"
"github.com/gomarkdown/markdown/html" "github.com/gomarkdown/markdown/html"
@ -47,7 +47,7 @@ func processLink(p string) string {
// Only process if it points to an existing, local markdown file // Only process if it points to an existing, local markdown file
if ext == ".md" && filepath.IsLocal(p) { if ext == ".md" && filepath.IsLocal(p) {
// fmt.Println("Markdown link detected...") // fmt.Println("Markdown link detected...")
return ChangeExtension(p, ".html") return util.ChangeExtension(p, ".html")
} else { } else {
return p return p
} }
@ -130,7 +130,3 @@ func CopyFile(inPath string, outPath string) error {
return nil return nil
} }
} }
func ChangeExtension(in string, outExt string) string {
return strings.TrimSuffix(in, filepath.Ext(in)) + outExt
}

View file

@ -1,11 +1,11 @@
package build_test package builder_test
import ( import (
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/ficcdaf/zona/internal/build" "github.com/ficcdaf/zona/internal/builder"
"github.com/ficcdaf/zona/internal/util" "github.com/ficcdaf/zona/internal/util"
) )
@ -13,7 +13,7 @@ func TestMdToHTML(t *testing.T) {
md := []byte("# Hello World\n\nThis is a test.") md := []byte("# Hello World\n\nThis is a test.")
expectedHTML := "<h1 id=\"hello-world\">Hello World</h1>\n<p>This is a test.</p>\n" expectedHTML := "<h1 id=\"hello-world\">Hello World</h1>\n<p>This is a test.</p>\n"
nExpectedHTML := util.NormalizeContent(expectedHTML) nExpectedHTML := util.NormalizeContent(expectedHTML)
html, err := build.MdToHTML(md) html, err := builder.MdToHTML(md)
nHtml := util.NormalizeContent(string(html)) nHtml := util.NormalizeContent(string(html))
if err != nil { if err != nil {
t.Fatalf("Expected no error, got %v", err) t.Fatalf("Expected no error, got %v", err)
@ -27,7 +27,7 @@ func TestWriteFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "test.txt") path := filepath.Join(t.TempDir(), "test.txt")
content := []byte("Hello, World!") content := []byte("Hello, World!")
err := build.WriteFile(content, path) err := builder.WriteFile(content, path)
if err != nil { if err != nil {
t.Fatalf("Expected no error, got %v", err) t.Fatalf("Expected no error, got %v", err)
} }
@ -51,7 +51,7 @@ func TestReadFile(t *testing.T) {
t.Fatalf("Error writing file: %v", err) t.Fatalf("Error writing file: %v", err)
} }
data, err := build.ReadFile(path) data, err := builder.ReadFile(path)
if err != nil { if err != nil {
t.Fatalf("Expected no error, got %v", err) t.Fatalf("Expected no error, got %v", err)
} }
@ -70,7 +70,7 @@ func TestCopyFile(t *testing.T) {
t.Fatalf("Error writing source file: %v", err) t.Fatalf("Error writing source file: %v", err)
} }
err = build.CopyFile(src, dst) err = builder.CopyFile(src, dst)
if err != nil { if err != nil {
t.Fatalf("Expected no error, got %v", err) t.Fatalf("Expected no error, got %v", err)
} }
@ -96,7 +96,7 @@ func TestConvertFile(t *testing.T) {
t.Fatalf("Error writing source Markdown file: %v", err) t.Fatalf("Error writing source Markdown file: %v", err)
} }
err = build.ConvertFile(src, dst) err = builder.ConvertFile(src, dst)
if err != nil { if err != nil {
t.Fatalf("Expected no error, got %v", err) t.Fatalf("Expected no error, got %v", err)
} }
@ -113,7 +113,7 @@ func TestConvertFile(t *testing.T) {
func TestChangeExtension(t *testing.T) { func TestChangeExtension(t *testing.T) {
input := "test.md" input := "test.md"
output := build.ChangeExtension(input, ".html") output := builder.ChangeExtension(input, ".html")
expected := "test.html" expected := "test.html"
if output != expected { if output != expected {

View file

@ -0,0 +1,28 @@
<!doctype html>
<html>
<head>
<title>{{ .Title }}</title>
<link rel="icon" href="{{ .Icon }}" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="UTF-8" />
<link
href="{{ .Stylesheet }}"
rel="stylesheet"
type="text/css"
media="all"
/>
</head>
<body>
<div id="container">
<header id="header">{{ .Header }}</header>
<article id="content">
{{ .Content }}
<nav id="nextprev">
{{ .NextPost }}<br />
{{ .PrevPost }}
</nav>
</article>
<footer id="footer">{{ .Footer }}</footer>
</div>
</body>
</html>

View file

View file

@ -1,4 +1,4 @@
package build package builder
import ( import (
"errors" "errors"
@ -8,7 +8,7 @@ import (
"github.com/ficcdaf/zona/internal/util" "github.com/ficcdaf/zona/internal/util"
) )
func processFile(inPath string, entry fs.DirEntry, err error, outRoot string) error { func processFile(inPath string, entry fs.DirEntry, err error, outRoot string, settings *Settings) error {
if err != nil { if err != nil {
return err return err
} }
@ -18,11 +18,11 @@ func processFile(inPath string, entry fs.DirEntry, err error, outRoot string) er
switch ext { switch ext {
case ".md": case ".md":
// fmt.Println("Processing markdown...") // fmt.Println("Processing markdown...")
outPath = ChangeExtension(outPath, ".html") outPath = util.ChangeExtension(outPath, ".html")
if err := util.CreateParents(outPath); err != nil { if err := util.CreateParents(outPath); err != nil {
return err return err
} }
if err := ConvertFile(inPath, outPath); err != nil { if err := ConvertFile(inPath, outPath, settings); err != nil {
return errors.Join(errors.New("Error processing file "+inPath), err) return errors.Join(errors.New("Error processing file "+inPath), err)
} else { } else {
return nil return nil
@ -44,10 +44,9 @@ func processFile(inPath string, entry fs.DirEntry, err error, outRoot string) er
return nil return nil
} }
func Traverse(root string, outRoot string) error { func Traverse(root string, outRoot string, settings *Settings) error {
// err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
walkFunc := func(path string, entry fs.DirEntry, err error) error { walkFunc := func(path string, entry fs.DirEntry, err error) error {
return processFile(path, entry, err, outRoot) return processFile(path, entry, err, outRoot, settings)
} }
err := filepath.WalkDir(root, walkFunc) err := filepath.WalkDir(root, walkFunc)
return err return err

View file

@ -18,6 +18,10 @@ func CheckExtension(path, ext string) error {
} }
} }
func ChangeExtension(in string, outExt string) string {
return strings.TrimSuffix(in, filepath.Ext(in)) + outExt
}
func getRoot(path string) string { func getRoot(path string) string {
for { for {
parent := filepath.Dir(path) parent := filepath.Dir(path)

View file

@ -1,4 +1,4 @@
package build package util
import ( import (
"path/filepath" "path/filepath"
@ -8,23 +8,23 @@ import (
"golang.org/x/text/language" "golang.org/x/text/language"
) )
// pathToWords takes a full path // PathToWords takes a full path
// and strips separators and extension // and strips separators and extension
// from the file name // from the file name
func pathToWords(path string) string { func PathToWords(path string) string {
stripped := ChangeExtension(filepath.Base(path), "") stripped := ChangeExtension(filepath.Base(path), "")
replaced := strings.NewReplacer("-", " ", "_", " ", `\ `, " ").Replace(stripped) replaced := strings.NewReplacer("-", " ", "_", " ", `\ `, " ").Replace(stripped)
return strings.ToTitle(replaced) return strings.ToTitle(replaced)
} }
func wordsToTitle(words string) string { func WordsToTitle(words string) string {
caser := cases.Title(language.English) caser := cases.Title(language.English)
return caser.String(words) return caser.String(words)
} }
// pathToTitle converts a full path to a string // PathToTitle converts a full path to a string
// in title case // in title case
func pathToTitle(path string) string { func PathToTitle(path string) string {
words := pathToWords(path) words := PathToWords(path)
return wordsToTitle(words) return WordsToTitle(words)
} }