summaryrefslogtreecommitdiff
path: root/site.go
blob: 5a64af5740af1d223cf2cf8d9f518d56b2c15b0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
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]
}