2020-11-20 17:07:38 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2021-04-24 17:25:18 +00:00
|
|
|
"log"
|
2020-11-20 17:07:38 +00:00
|
|
|
pathpkg "path"
|
|
|
|
"strings"
|
|
|
|
"time"
|
2021-04-24 17:25:18 +00:00
|
|
|
|
|
|
|
"gopkg.in/yaml.v3"
|
2020-11-20 17:07:38 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Page represents a page.
|
|
|
|
type Page struct {
|
2021-04-24 17:25:18 +00:00
|
|
|
Title string
|
|
|
|
Date time.Time
|
|
|
|
Path string `yaml:"-"`
|
|
|
|
Content string `yaml:"-"`
|
|
|
|
Params map[string]string
|
2020-11-20 17:07:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewPage returns a new Page with the given path and content.
|
|
|
|
func NewPage(path string, content []byte) *Page {
|
|
|
|
var page Page
|
|
|
|
|
|
|
|
// Try to parse the date from the page filename
|
|
|
|
const layout = "2006-01-02"
|
|
|
|
base := pathpkg.Base(path)
|
|
|
|
if len(base) >= len(layout) {
|
|
|
|
dateStr := base[:len(layout)]
|
|
|
|
if time, err := time.Parse(layout, dateStr); err == nil {
|
|
|
|
page.Date = time
|
2021-04-21 17:49:47 +00:00
|
|
|
// Remove the date from the path
|
|
|
|
base = base[len(layout):]
|
2020-11-20 17:07:38 +00:00
|
|
|
if len(base) > 0 {
|
2021-04-21 17:49:47 +00:00
|
|
|
// Remove a leading dash
|
|
|
|
if base[0] == '-' {
|
|
|
|
base = base[1:]
|
|
|
|
}
|
|
|
|
if len(base) > 0 {
|
|
|
|
dir := pathpkg.Dir(path)
|
|
|
|
if dir == "." {
|
|
|
|
dir = ""
|
|
|
|
}
|
|
|
|
path = pathpkg.Join(dir, base)
|
2020-11-20 17:07:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-24 17:25:18 +00:00
|
|
|
// Extract frontmatter from content
|
|
|
|
var frontmatter []byte
|
|
|
|
frontmatter, content = extractFrontmatter(content)
|
|
|
|
if len(frontmatter) != 0 {
|
|
|
|
if err := yaml.Unmarshal(frontmatter, &page); err != nil {
|
2021-04-26 15:50:40 +00:00
|
|
|
log.Printf("failed to parse frontmatter for %q: %v", path, err)
|
2021-04-24 17:25:18 +00:00
|
|
|
}
|
2020-11-20 17:07:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Remove extension from path
|
2021-02-28 02:42:37 +00:00
|
|
|
page.Path = "/" + strings.TrimSuffix(path, pathpkg.Ext(path)) + "/"
|
2020-11-20 17:07:38 +00:00
|
|
|
page.Content = string(content)
|
|
|
|
return &page
|
|
|
|
}
|