kiln/kiln.go
2020-09-29 16:42:27 -04:00

431 lines
9.6 KiB
Go

package main
import (
"bytes"
"fmt"
"html"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"text/template"
"time"
"git.sr.ht/~adnano/gmi"
)
// Site represents a kiln site.
type Site struct {
URL string // Site URL
Directory *Directory // Site directory
Templates *template.Template // Templates
}
// Load loads the Site from the specified source directory.
func (s *Site) Load(srcDir string) error {
s.Directory = NewDirectory("")
tmpl, err := template.New("templates").ParseGlob("templates/*.gmi")
if err != nil {
return err
}
s.Templates = tmpl
if err := site.Directory.Read(""); err != nil {
return err
}
return nil
}
// Write writes the contents of the Index to the provided destination directory.
func (s *Site) Write(dstDir string, format OutputFormat) error {
// Empty the destination directory
if err := os.RemoveAll(dstDir); err != nil {
return err
}
// Create the destination directory
if err := os.MkdirAll(dstDir, 0755); err != nil {
return err
}
// Write the directory
return s.Directory.Write(dstDir, format)
}
// Manipulate processes and manipulates the site's content.
func (s *Site) Manipulate(dir *Directory) error {
// Write the directory index file, if it doesn't exist
if dir.Index == nil {
path := filepath.Join(dir.Permalink, "index.gmi")
var b bytes.Buffer
tmpl := s.Templates.Lookup("index.gmi")
if tmpl == nil {
tmpl = indexTmpl
}
if err := tmpl.Execute(&b, dir); err != nil {
return err
}
content := b.Bytes()
permalink := filepath.Dir(path)
if permalink == "." {
permalink = ""
}
page := &Page{
Permalink: "/" + permalink,
content: content,
}
dir.Index = page
}
// Manipulate pages
for i := range dir.Pages {
var b bytes.Buffer
tmpl := s.Templates.Lookup("page.gmi")
if tmpl == nil {
tmpl = pageTmpl
}
if err := tmpl.Execute(&b, dir.Pages[i]); err != nil {
return err
}
dir.Pages[i].content = b.Bytes()
}
return nil
}
// Sort sorts the site's pages by date.
func (s *Site) Sort() {
s.Directory.Sort()
}
type Feed struct {
Title string
Path string
SiteURL string
Updated time.Time
Entries []*Page
}
// CreateFeeds creates Atom feeds.
func (s *Site) CreateFeeds() error {
const atomPath = "atom.xml"
var b bytes.Buffer
tmpl := s.Templates.Lookup(atomPath)
if tmpl == nil {
tmpl = atomTmpl
}
feed := &Feed{
Title: "Example Feed",
Path: filepath.Join(s.Directory.Permalink, atomPath),
SiteURL: s.URL,
Updated: time.Now(),
Entries: s.Directory.Pages,
}
if err := tmpl.Execute(&b, feed); err != nil {
return err
}
path := filepath.Join(s.Directory.Permalink, atomPath)
s.Directory.Static[path] = b.Bytes()
return nil
}
// Page represents a page.
type Page struct {
// The permalink to this page.
Permalink string
// The title of this page, parsed from the Gemini contents.
Title string
// The date of the page. Dates are specified in the filename.
// Ex: 2020-09-22-hello-world.gmi
Date time.Time
// The content of this page.
content []byte
}
func (p *Page) Content() string {
return string(p.content)
}
var titleRE = regexp.MustCompile("^# ?([^#\r\n]+)\r?\n?\r?\n?")
// NewPage returns a new Page with the given path and content.
func NewPage(path string, content []byte) *Page {
// Try to parse the date from the page filename
var date time.Time
const layout = "2006-01-02"
base := filepath.Base(path)
if len(base) >= len(layout) {
dateStr := base[:len(layout)]
if time, err := time.Parse(layout, dateStr); err == nil {
date = time
}
// Remove the date from the path
base = base[len(layout):]
if len(base) > 0 {
// Remove a leading dash
if base[0] == '-' {
base = base[1:]
}
if len(base) > 0 {
dir := filepath.Dir(path)
if dir == "." {
dir = ""
}
path = filepath.Join(dir, base)
}
}
}
// Try to parse the title from the contents
var title string
if submatches := titleRE.FindSubmatch(content); submatches != nil {
title = string(submatches[1])
// Remove the title from the contents
content = content[len(submatches[0]):]
}
permalink := strings.TrimSuffix(path, ".gmi")
return &Page{
Permalink: "/" + permalink + "/",
Title: title,
Date: date,
content: content,
}
}
// Directory represents a directory of pages.
type Directory struct {
// The permalink to this directory.
Permalink string
// The pages in this directory.
Pages []*Page
// The subdirectories of this directory.
Directories []*Directory
// The index file (index.gmi).
Index *Page
// Static files
Static map[string][]byte
}
// NewDirectory returns a new Directory with the given path.
func NewDirectory(path string) *Directory {
var permalink string
if path == "" {
permalink = "/"
} else {
permalink = "/" + path + "/"
}
return &Directory{
Permalink: permalink,
Static: map[string][]byte{},
}
}
// Read reads from a directory and indexes the files and directories within it.
func (d *Directory) Read(path string) error {
entries, err := ioutil.ReadDir(filepath.Join("src", path))
if err != nil {
return err
}
for _, entry := range entries {
name := entry.Name()
if entry.IsDir() {
// Gather directory data
path := filepath.Join(path, name)
dir := NewDirectory(path)
if err := dir.Read(path); err != nil {
return err
}
d.Directories = append(d.Directories, dir)
} else {
srcPath := filepath.Join("src", path, name)
content, err := ioutil.ReadFile(srcPath)
if err != nil {
return err
}
switch filepath.Ext(name) {
case ".gmi", ".gemini":
path := filepath.Join(path, name)
// Gather page data
page := NewPage(path, content)
if name == "index.gmi" {
d.Index = page
} else {
d.Pages = append(d.Pages, page)
}
default:
// Static file
path := filepath.Join(path, name)
d.Static[path] = content
}
}
}
return nil
}
// Write writes the Directory to the provided destination path.
func (d *Directory) Write(dstDir string, format OutputFormat) error {
// Create the directory
dirPath := filepath.Join(dstDir, d.Permalink)
if err := os.MkdirAll(dirPath, 0755); err != nil {
return err
}
// Write static files
for path := range d.Static {
dstPath := filepath.Join(dstDir, path)
f, err := os.Create(dstPath)
if err != nil {
return err
}
data := d.Static[path]
if _, err := f.Write(data); err != nil {
return err
}
}
// Write the files
for _, page := range d.Pages {
path, content := format(page)
dstPath := filepath.Join(dstDir, path)
dir := filepath.Dir(dstPath)
os.MkdirAll(dir, 0755)
f, err := os.Create(dstPath)
if err != nil {
return err
}
if _, err := f.Write(content); err != nil {
return err
}
}
// Write the index file
if d.Index != nil {
path, content := format(d.Index)
dstPath := filepath.Join(dstDir, path)
f, err := os.Create(dstPath)
if err != nil {
return err
}
if _, err := f.Write(content); err != nil {
return err
}
}
// Write subdirectories
for _, dir := range d.Directories {
dir.Write(dstDir, format)
}
return nil
}
// Sort sorts the directory's pages by date.
func (d *Directory) Sort() {
sort.Slice(d.Pages, func(i, j int) bool {
return d.Pages[i].Date.After(d.Pages[j].Date)
})
// Sort subdirectories
for _, d := range d.Directories {
d.Sort()
}
}
// OutputFormat represents an output format.
type OutputFormat func(*Page) (path string, content []byte)
func OutputGemini(p *Page) (path string, content []byte) {
const indexPath = "index.gmi"
path = filepath.Join(p.Permalink, indexPath)
content = p.content
return
}
func OutputHTML(p *Page) (path string, content []byte) {
const indexPath = "index.html"
const meta = `<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="/style.css">
<title>%s</title>
`
path = filepath.Join(p.Permalink, indexPath)
var b bytes.Buffer
fmt.Fprintf(&b, meta, html.EscapeString(p.Title))
var pre bool
var list bool
r := bytes.NewReader(p.content)
text := gmi.Parse(r)
for _, l := range text {
if _, ok := l.(gmi.LineListItem); ok {
if !list {
list = true
fmt.Fprint(&b, "<ul>\n")
}
} else if list {
list = false
fmt.Fprint(&b, "</ul>\n")
}
switch l.(type) {
case gmi.LineLink:
link := l.(gmi.LineLink)
url := html.EscapeString(link.URL)
name := html.EscapeString(link.Name)
if name == "" {
name = url
}
fmt.Fprintf(&b, "<p><a href='%s'>%s</a></p>\n", url, name)
case gmi.LinePreformattingToggle:
pre = !pre
if pre {
fmt.Fprint(&b, "<pre>\n")
} else {
fmt.Fprint(&b, "</pre>\n")
}
case gmi.LinePreformattedText:
text := string(l.(gmi.LinePreformattedText))
fmt.Fprintf(&b, "%s\n", html.EscapeString(text))
case gmi.LineHeading1:
text := string(l.(gmi.LineHeading1))
fmt.Fprintf(&b, "<h1>%s</h1>\n", html.EscapeString(text))
case gmi.LineHeading2:
text := string(l.(gmi.LineHeading2))
fmt.Fprintf(&b, "<h2>%s</h2>\n", html.EscapeString(text))
case gmi.LineHeading3:
text := string(l.(gmi.LineHeading3))
fmt.Fprintf(&b, "<h3>%s</h3>\n", html.EscapeString(text))
case gmi.LineListItem:
text := string(l.(gmi.LineListItem))
fmt.Fprintf(&b, "<li>%s</li>\n", html.EscapeString(text))
case gmi.LineQuote:
text := string(l.(gmi.LineQuote))
fmt.Fprintf(&b, "<blockquote>%s</blockquote>\n", html.EscapeString(text))
case gmi.LineText:
text := string(l.(gmi.LineText))
if text == "" {
fmt.Fprint(&b, "<br>\n")
} else {
fmt.Fprintf(&b, "<p>%s</p>\n", html.EscapeString(text))
}
}
}
if pre {
fmt.Fprint(&b, "</pre>\n")
}
if list {
fmt.Fprint(&b, "</ul>\n")
}
content = b.Bytes()
return
}