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

@ -6,7 +6,7 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/ficcdaf/zona/internal/util" "github.com/ficcdaf/zona/internal/convert"
) )
// // validateFile checks whether a given path // // validateFile checks whether a given path
@ -16,9 +16,9 @@ import (
// } // }
func main() { func main() {
mdPath := flag.String("file", "", "Path to the markdown file.") rootPath := flag.String("file", "", "Path to the markdown file.")
flag.Parse() flag.Parse()
if *mdPath == "" { if *rootPath == "" {
// no flag provided, check for positional argument instead // no flag provided, check for positional argument instead
n := flag.NArg() n := flag.NArg()
var e error var e error
@ -27,7 +27,7 @@ func main() {
// we read the positional arg // we read the positional arg
arg := flag.Arg(0) arg := flag.Arg(0)
// mdPath wants a pointer so we get arg's address // mdPath wants a pointer so we get arg's address
mdPath = &arg rootPath = &arg
case 0: case 0:
// in case of no flag and no arg, we fail // in case of no flag and no arg, we fail
e = errors.New("Required argument missing!") e = errors.New("Required argument missing!")
@ -41,7 +41,7 @@ func main() {
} }
} }
err := util.Traverse(*mdPath, "foobar") err := convert.Traverse(*rootPath, "foobar")
if err != nil { if err != nil {
fmt.Printf("Error: %s\n", err.Error()) fmt.Printf("Error: %s\n", err.Error())
} }

View file

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"fmt" "fmt"
"html/template" "html/template"
"path/filepath"
"strings" "strings"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@ -13,13 +14,15 @@ type PageData struct {
Title string Title string
Icon string Icon string
Stylesheet string Stylesheet string
Header template.HTML Header string
Content template.HTML Content template.HTML
NextPost template.HTML NextPost string
PrevPost template.HTML PrevPost string
Footer template.HTML Footer string
} }
type Metadata map[string]interface{}
func processWithYaml(f []byte) (Metadata, []byte, error) { func processWithYaml(f []byte) (Metadata, []byte, error) {
// Check if the file has valid metadata // Check if the file has valid metadata
if !bytes.HasPrefix(f, []byte("---\n")) { if !bytes.HasPrefix(f, []byte("---\n")) {
@ -31,12 +34,43 @@ func processWithYaml(f []byte) (Metadata, []byte, error) {
if len(split) < 3 { if len(split) < 3 {
return nil, nil, fmt.Errorf("Invalid frontmatter format.") return nil, nil, fmt.Errorf("Invalid frontmatter format.")
} }
var metadata Metadata var meta Metadata
// Parse YAML // 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 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 { func ConvertFile(in string, out string) error {
@ -48,14 +82,14 @@ func ConvertFile(in string, out string) error {
if err != nil { if err != nil {
return err return err
} }
metadata["path"] = in
pd := buildPageData(metadata)
fmt.Println("Page title: ", pd.Title)
pd.Content = template.HTML(md)
title, ok := metadata["title"].(string) tmlp, err := template.New("webpage").Parse("placeholder")
if !ok {
fmt.Println("No title in page.")
} else {
fmt.Println("Title found: ", title)
}
// build according to template here
html, err := MdToHTML(md) html, err := MdToHTML(md)
if err != nil { if err != nil {
return err return err

View file

@ -1,12 +1,15 @@
package convert package convert
import ( import (
"errors"
"fmt" "fmt"
"io" "io"
"io/fs"
"os" "os"
"path/filepath" "path/filepath"
"strings" "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"
@ -134,3 +137,48 @@ func CopyFile(inPath string, outPath string) error {
func ChangeExtension(in string, outExt string) string { func ChangeExtension(in string, outExt string) string {
return strings.TrimSuffix(in, filepath.Ext(in)) + outExt return strings.TrimSuffix(in, filepath.Ext(in)) + outExt
} }
func processFile(inPath string, entry fs.DirEntry, err error, outRoot string) error {
if err != nil {
return err
}
if !entry.IsDir() {
ext := filepath.Ext(inPath)
outPath := util.ReplaceRoot(inPath, outRoot)
switch ext {
case ".md":
fmt.Println("Processing markdown...")
outPath = ChangeExtension(outPath, ".html")
if err := util.CreateParents(outPath); err != nil {
return err
}
if err := ConvertFile(inPath, outPath); err != nil {
return errors.Join(errors.New("Error processing file "+inPath), err)
} else {
return nil
}
// If it's not a file we need to process,
// we simply copy it to the destination path.
default:
if err := util.CreateParents(outPath); err != nil {
return err
}
if err := CopyFile(inPath, outPath); err != nil {
return errors.Join(errors.New("Error processing file "+inPath), err)
} else {
return nil
}
}
}
// fmt.Printf("Visited: %s\n", inPath)
return nil
}
func Traverse(root string, outRoot string) error {
// err := filepath.WalkDir(root, 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)
}
err := filepath.WalkDir(root, walkFunc)
return err
}

View file

@ -3,13 +3,9 @@ package util
import ( import (
"errors" "errors"
"fmt"
"io/fs"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/ficcdaf/zona/internal/convert"
) )
// CheckExtension checks if the file located at path (string) // CheckExtension checks if the file located at path (string)
@ -34,13 +30,13 @@ func getRoot(path string) string {
return path return path
} }
func replaceRoot(inPath, outRoot string) string { func ReplaceRoot(inPath, outRoot string) string {
relPath := strings.TrimPrefix(inPath, getRoot(inPath)) relPath := strings.TrimPrefix(inPath, getRoot(inPath))
outPath := filepath.Join(outRoot, relPath) outPath := filepath.Join(outRoot, relPath)
return outPath return outPath
} }
func createParents(path string) error { func CreateParents(path string) error {
dir := filepath.Dir(path) dir := filepath.Dir(path)
// Check if the parent directory already exists // Check if the parent directory already exists
// before trying to create it // before trying to create it
@ -52,48 +48,3 @@ func createParents(path string) error {
} }
return nil return nil
} }
func processFile(inPath string, entry fs.DirEntry, err error, outRoot string) error {
if err != nil {
return err
}
if !entry.IsDir() {
ext := filepath.Ext(inPath)
outPath := replaceRoot(inPath, outRoot)
switch ext {
case ".md":
fmt.Println("Processing markdown...")
outPath = convert.ChangeExtension(outPath, ".html")
if err := createParents(outPath); err != nil {
return err
}
if err := convert.ConvertFile(inPath, outPath); err != nil {
return errors.Join(errors.New("Error processing file "+inPath), err)
} else {
return nil
}
// If it's not a file we need to process,
// we simply copy it to the destination path.
default:
if err := createParents(outPath); err != nil {
return err
}
if err := convert.CopyFile(inPath, outPath); err != nil {
return errors.Join(errors.New("Error processing file "+inPath), err)
} else {
return nil
}
}
}
// fmt.Printf("Visited: %s\n", inPath)
return nil
}
func Traverse(root string, outRoot string) error {
// err := filepath.WalkDir(root, 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)
}
err := filepath.WalkDir(root, walkFunc)
return err
}