summaryrefslogtreecommitdiff
path: root/site.go
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--site.go378
1 files changed, 378 insertions, 0 deletions
diff --git a/site.go b/site.go
new file mode 100644
index 0000000..5a64af5
--- /dev/null
+++ b/site.go
@@ -0,0 +1,378 @@
+package main
+
+import (
+ "fmt"
+ "html"
+ "html/template"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Post is a single blog post loaded from <root>/posts/<name>.html.
+type Post struct {
+ Name string // file stem, used in the /post/<name>.html URL
+ ID string // id= attribute of the entry <div> on listing pages
+ Title template.HTML
+ TitleText string // plain-text form of Title, for <title> and RSS
+ DateText string // raw value of the `date:` meta comment, if any
+ Date time.Time
+ DateStr string // display form, e.g. "2025.12.2"
+ Aliases []string
+ HasMore bool
+ Excerpt template.HTML // part before <!-- more -->
+ Body template.HTML // full content (excerpt + remainder)
+}
+
+// Page is a standalone page loaded from <root>/pages/**.html.
+type Page struct {
+ URL string // e.g. "/about.html"
+ TitleSuffix string // e.g. "About"
+ Content template.HTML
+}
+
+// Fragment format (see README):
+//
+// <!-- id: optional-div-id -->
+// <!-- title: optional raw HTML for the <h1> -->
+// <!-- date: 2006-01-02 --> (only needed when the filename is not YYYYMMDD[-N].html)
+// <!-- alias: old-url-stem -->
+// <body html>
+// <!-- more -->
+// <rest of body, only shown on the post page>
+//
+// Meta comments must sit on their own lines at the top of the file.
+
+var (
+ metaLineRe = regexp.MustCompile(`^<!--\s*(id|title|date|time|alias)\s*:\s*(.*?)\s*-->$`)
+ moreRe = regexp.MustCompile(`<!--\s*more\s*-->`)
+ nameDateRe = regexp.MustCompile(`^(\d{4})(\d{2})(\d{2})(?:-[0-9]+)?$`)
+ timeClockRe = regexp.MustCompile(`^(\d{1,2}):(\d{2})(?::(\d{2}))?$`)
+ zoneOffsetRe = regexp.MustCompile(`^([+-])(\d{2})(?::?(\d{2}))?$`)
+ tagRe = regexp.MustCompile(`<[^>]*>`)
+ wsRe = regexp.MustCompile(`\s+`)
+)
+
+func stripTags(s string) string {
+ s = tagRe.ReplaceAllString(s, " ")
+ s = html.UnescapeString(s)
+ return strings.TrimSpace(wsRe.ReplaceAllString(s, " "))
+}
+
+var dateLayouts = []string{"2006-01-02", "2006-1-2", "2006.01.02", "2006.1.2"}
+
+// parseMetaBlock consumes leading meta-comment lines (and blank lines) and
+// returns the rest of the file plus the collected values.
+func parseMetaBlock(data string) (rest, id, title, date, timeText, alias string) {
+ for data != "" {
+ line, remainder, _ := strings.Cut(data, "\n")
+ trimmed := strings.TrimSpace(line)
+ if m := metaLineRe.FindStringSubmatch(trimmed); m != nil {
+ switch m[1] {
+ case "id":
+ id = m[2]
+ case "title":
+ title = m[2]
+ case "date":
+ date = m[2]
+ case "time":
+ timeText = m[2]
+ case "alias":
+ alias = m[2]
+ }
+ data = remainder
+ } else if trimmed == "" {
+ data = remainder
+ } else {
+ break
+ }
+ }
+ return data, id, title, date, timeText, alias
+}
+
+// parsePostWhen resolves the post's date from its filename or `date:` meta
+// and, if a `time:` meta is present, applies that clock time in the given
+// time zone to the pubDate in the RSS feed. The site's own date display
+// stays date-only.
+func parsePostWhen(name, dateText, timeText string) (time.Time, error) {
+ var t time.Time
+ if m := nameDateRe.FindStringSubmatch(name); m != nil {
+ y, err1 := strconv.Atoi(m[1])
+ mo, err2 := strconv.Atoi(m[2])
+ d, err3 := strconv.Atoi(m[3])
+ if err1 != nil || err2 != nil || err3 != nil {
+ return time.Time{}, fmt.Errorf("bad date in filename %q", name)
+ }
+ t = time.Date(y, time.Month(mo), d, 0, 0, 0, 0, time.UTC)
+ } else {
+ if dateText == "" {
+ return time.Time{}, fmt.Errorf("no date: give the file a YYYYMMDD name or add a `date:` meta comment")
+ }
+ parsed := false
+ for _, layout := range dateLayouts {
+ if pt, err := time.Parse(layout, dateText); err == nil {
+ t = time.Date(pt.Year(), pt.Month(), pt.Day(), 0, 0, 0, 0, time.UTC)
+ parsed = true
+ break
+ }
+ }
+ if !parsed {
+ return time.Time{}, fmt.Errorf("unparseable date %q (want 2006-01-02 or 2006.1.2)", dateText)
+ }
+ }
+ if timeText == "" {
+ return t, nil
+ }
+ hh, mm, ss, loc, err := parseTimeSpec(timeText)
+ if err != nil {
+ return time.Time{}, err
+ }
+ return time.Date(t.Year(), t.Month(), t.Day(), hh, mm, ss, 0, loc), nil
+}
+
+// parseTimeSpec parses a `time:` meta value: "HH:MM[:SS]" optionally
+// followed by a time zone ("13:45 Asia/Hong_Kong", "21:05 +08:00").
+// Without a zone the time is taken as UTC.
+func parseTimeSpec(spec string) (hh, mm, ss int, loc *time.Location, err error) {
+ fields := strings.Fields(spec)
+ if len(fields) == 0 || len(fields) > 2 {
+ return 0, 0, 0, nil, fmt.Errorf("bad time %q (want HH:MM[:SS] [ZONE])", spec)
+ }
+ m := timeClockRe.FindStringSubmatch(fields[0])
+ if m == nil {
+ return 0, 0, 0, nil, fmt.Errorf("bad time %q (want HH:MM[:SS] [ZONE])", spec)
+ }
+ hh, _ = strconv.Atoi(m[1])
+ mm, _ = strconv.Atoi(m[2])
+ if m[3] != "" {
+ ss, _ = strconv.Atoi(m[3])
+ }
+ if hh > 23 || mm > 59 || ss > 59 {
+ return 0, 0, 0, nil, fmt.Errorf("time out of range %q", fields[0])
+ }
+ loc = time.UTC
+ if len(fields) == 2 {
+ if loc, err = parseZoneSpec(fields[1]); err != nil {
+ return 0, 0, 0, nil, err
+ }
+ }
+ return hh, mm, ss, loc, nil
+}
+
+// parseZoneSpec understands IANA zone names ("Asia/Hong_Kong", "Europe/Dublin"),
+// "UTC"/"Z", and fixed numeric offsets ("+08", "+08:00", "-0530").
+func parseZoneSpec(spec string) (*time.Location, error) {
+ switch strings.ToUpper(spec) {
+ case "UTC", "Z":
+ return time.UTC, nil
+ }
+ if m := zoneOffsetRe.FindStringSubmatch(spec); m != nil {
+ sign := 1
+ if m[1] == "-" {
+ sign = -1
+ }
+ hh, _ := strconv.Atoi(m[2])
+ mm := 0
+ if m[3] != "" {
+ mm, _ = strconv.Atoi(m[3])
+ }
+ if hh > 23 || mm > 59 {
+ return nil, fmt.Errorf("zone offset out of range %q", spec)
+ }
+ return time.FixedZone(spec, sign*(hh*3600+mm*60)), nil
+ }
+ loc, err := time.LoadLocation(spec)
+ if err != nil {
+ return nil, fmt.Errorf("unknown time zone %q", spec)
+ }
+ return loc, nil
+}
+
+func parsePost(path string) (*Post, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ name := strings.TrimSuffix(filepath.Base(path), ".html")
+ p := &Post{Name: name, ID: name}
+ rest, id, title, date, timeText, alias := parseMetaBlock(string(data))
+ if id != "" {
+ p.ID = id
+ }
+ if title != "" {
+ p.Title = template.HTML(title)
+ p.TitleText = stripTags(title)
+ }
+ p.DateText = date
+ if alias != "" {
+ p.Aliases = strings.Fields(alias)
+ }
+ t, err := parsePostWhen(name, date, timeText)
+ if err != nil {
+ return nil, err
+ }
+ p.Date = t
+ p.DateStr = fmt.Sprintf("%d.%d.%d", t.Year(), int(t.Month()), t.Day())
+
+ if loc := moreRe.FindStringIndex(rest); loc != nil {
+ p.HasMore = true
+ p.Excerpt = template.HTML(rest[:loc[0]])
+ p.Body = template.HTML(rest[:loc[0]] + rest[loc[1]:])
+ } else {
+ p.Excerpt = template.HTML(rest)
+ p.Body = p.Excerpt
+ }
+ return p, nil
+}
+
+func parsePage(path string) (*Page, error) {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ rest, _, title, _, _, _ := parseMetaBlock(string(data))
+ return &Page{TitleSuffix: title, Content: template.HTML(rest)}, nil
+}
+
+// Site loads and caches the content of a content root. It rescans the
+// directories at most once per interval so new posts appear without a
+// restart. Loaded slices/maps are never mutated after publication, so
+// concurrent readers can safely use the returned values.
+type Site struct {
+ root string
+ interval time.Duration
+
+ mu sync.Mutex
+ loadedAt time.Time
+ posts []*Post
+ byName map[string]*Post
+ byAlias map[string]*Post
+ pages map[string]*Page
+}
+
+func NewSite(root string, interval time.Duration) *Site {
+ if interval < 0 {
+ interval = 0
+ }
+ return &Site{root: root, interval: interval}
+}
+
+// Reload rescans the content root now. Unreadable or unparseable files are
+// reported on stderr and skipped; the rest of the site keeps working.
+func (s *Site) Reload() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.loadedAt = time.Now()
+
+ posts := []*Post{}
+ byName := map[string]*Post{}
+ byAlias := map[string]*Post{}
+ files, err := filepath.Glob(filepath.Join(s.root, "posts", "*.html"))
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "warning:", err)
+ }
+ for _, f := range files {
+ p, err := parsePost(f)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "warning: skipping post %s: %v\n", filepath.Base(f), err)
+ continue
+ }
+ if _, dup := byName[p.Name]; dup {
+ fmt.Fprintf(os.Stderr, "warning: duplicate post name %q\n", p.Name)
+ continue
+ }
+ posts = append(posts, p)
+ byName[p.Name] = p
+ for _, a := range p.Aliases {
+ byAlias[a] = p
+ }
+ }
+ // Newest first; ties broken by descending filename so that, within one
+ // date, 20250709-2.html is considered newer than 20250709-1.html.
+ sort.SliceStable(posts, func(i, j int) bool {
+ if !posts[i].Date.Equal(posts[j].Date) {
+ return posts[i].Date.After(posts[j].Date)
+ }
+ return posts[i].Name > posts[j].Name
+ })
+
+ pages := map[string]*Page{}
+ pagesRoot := filepath.Join(s.root, "pages")
+ filepath.WalkDir(pagesRoot, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return nil // missing pages/ dir or unreadable entry: keep going
+ }
+ if d.IsDir() || !strings.HasSuffix(path, ".html") || strings.HasSuffix(path, "~") {
+ return nil
+ }
+ pg, err := parsePage(path)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "warning: skipping page %s: %v\n", path, err)
+ return nil
+ }
+ rel, err := filepath.Rel(pagesRoot, path)
+ if err != nil {
+ return nil
+ }
+ pg.URL = "/" + filepath.ToSlash(rel)
+ pages[pg.URL] = pg
+ return nil
+ })
+
+ s.posts, s.byName, s.byAlias, s.pages = posts, byName, byAlias, pages
+}
+
+func (s *Site) maybeRefresh() {
+ s.mu.Lock()
+ stale := time.Since(s.loadedAt) > s.interval
+ s.mu.Unlock()
+ if stale {
+ s.Reload()
+ }
+}
+
+func (s *Site) Posts() []*Post {
+ s.maybeRefresh()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.posts
+}
+
+func (s *Site) Pages() map[string]*Page {
+ s.maybeRefresh()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.pages
+}
+
+func (s *Site) PostByName(name string) *Post {
+ s.maybeRefresh()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.byName[name]
+}
+
+// PostByAlias matches either the post's own name or one of its aliases
+// (used by the /articles/... compatibility redirect).
+func (s *Site) PostByAlias(name string) *Post {
+ s.maybeRefresh()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if p := s.byAlias[name]; p != nil {
+ return p
+ }
+ return s.byName[name]
+}
+
+func (s *Site) Page(url string) *Page {
+ s.maybeRefresh()
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.pages[url]
+}