summaryrefslogtreecommitdiff
path: root/convert.go
blob: 16737857ceed511877dfe1096d3a6b5c9258701d (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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
package main

import (
	"flag"
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"time"
)

// runConvert is a one-time migrator for the old hand-written static site.
// It reads <src>/index.html and <src>/archives/*.html, extracts every
// <div id="pNN" class="entry"> block, merges each ">>> More / Read More"
// pointer with the article page it points to, and writes post fragments
// into <dst>/posts/. The boilerplate pages (about/special/releases and
// special/*) become page fragments, and static assets are copied to
// <dst>/static/. The source tree is never modified.
//
// It also rewrites the relative links inside content ("./assets/..." and
// "../assets/...") into absolute form ("/assets/..."), because fragments
// are now rendered at different URL depths than the old static pages; this
// incidentally fixes a few links that were already broken on the old site.
// Internal anchors like href="#p1" keep working because each converted
// post keeps its original id via an `id:` meta comment.

type convEntry struct {
	id          string
	title       string
	date        time.Time
	excerpt     string
	article     string // basename of the article page this entry points to, or ""
	articleBody string
	suffix      int
}

var (
	entryOpenRe = regexp.MustCompile(`<div id="(p\d+)" class="entry">`)
	divTokenRe  = regexp.MustCompile(`<div\b|</div>`)
	h1Re        = regexp.MustCompile(`(?s)<h1[^>]*>(.*?)</h1>`)
	datePRe     = regexp.MustCompile(`^<p>\s*(\d{4})\.(\d{1,2})\.(\d{1,2})\s*</p>`)
	dateBareRe  = regexp.MustCompile(`^(\d{4})\.(\d{1,2})\.(\d{1,2})(?:\s|$)`)
	// ">>> MORE" / ">>> More" / ">> Read More" links to ./ or ../articles/
	articleLinkRe = regexp.MustCompile(`(?s)<p>\s*<a href="(?:\./|\.\./)?articles/([0-9A-Za-z-]+\.html)">([^<]*&gt;[^<]*)</a>\s*</p>`)
	contentCellRe = regexp.MustCompile(`(?s)<td style="padding-left: 2em">\s*(.*?)\s*</td>`)
	titleTagRe    = regexp.MustCompile(`(?s)<title>(.*?)</title>`)
	backLinkRe    = regexp.MustCompile(`(?s)\s*<p>\s*<a href="(?:\./|\.\./)?index\.html">\s*Back\s*</a>\s*</p>\s*$`)
	subtitleRe    = regexp.MustCompile(`(?s)^<p class="subtitle">\s*</p>`)
)

var relRewrites = strings.NewReplacer(
	`href="./`, `href="/`,
	`href="../`, `href="/`,
	`src="./`, `src="/`,
	`src="../`, `src="/`,
)

func rewriteRelative(s string) string {
	return relRewrites.Replace(s)
}

func parseYMD(y, m, d string) (time.Time, error) {
	yy, err1 := strconv.Atoi(y)
	mm, err2 := strconv.Atoi(m)
	dd, err3 := strconv.Atoi(d)
	if err1 != nil || err2 != nil || err3 != nil || mm < 1 || mm > 12 || dd < 1 || dd > 31 {
		return time.Time{}, fmt.Errorf("bad date %s.%s.%s", y, m, d)
	}
	return time.Date(yy, time.Month(mm), dd, 0, 0, 0, 0, time.UTC), nil
}

func runConvert(args []string) error {
	fs := flag.NewFlagSet("convert", flag.ExitOnError)
	src := fs.String("src", ".", "path of the old static site (the directory containing index.html)")
	dst := fs.String("dst", "./site", "output content root (posts/, pages/, static/)")
	fs.Parse(args)

	if _, err := os.Stat(filepath.Join(*src, "index.html")); err != nil {
		return fmt.Errorf("cannot read %s/index.html: %w", *src, err)
	}
	postsDir := filepath.Join(*dst, "posts")
	pagesDir := filepath.Join(*dst, "pages")
	staticDir := filepath.Join(*dst, "static")
	for _, d := range []string{postsDir, pagesDir, staticDir} {
		if err := os.MkdirAll(d, 0o755); err != nil {
			return err
		}
	}

	// 1. Collect entries from all listing pages (index first, then archives,
	//    which are already in newest-first order).
	listings := []string{filepath.Join(*src, "index.html")}
	archiveFiles, err := filepath.Glob(filepath.Join(*src, "archives", "*.html"))
	if err != nil {
		return err
	}
	sort.Strings(archiveFiles)
	listings = append(listings, archiveFiles...)
	var entries []convEntry
	for _, f := range listings {
		data, err := os.ReadFile(f)
		if err != nil {
			return err
		}
		entries = append(entries, extractEntries(string(data))...)
	}
	if len(entries) == 0 {
		return fmt.Errorf("no entries found under %s", *src)
	}

	// 2. Merge article bodies into the entries that point at them.
	usedArticles := map[string]bool{}
	for i := range entries {
		e := &entries[i]
		if e.article == "" {
			continue
		}
		title, body, err := extractArticle(*src, e.article)
		if err != nil {
			return err
		}
		if e.title == "" {
			e.title = title
		}
		e.articleBody = body
		usedArticles[strings.TrimSuffix(e.article, ".html")] = true
	}

	// 3. Assign filename suffixes so several posts on the same date keep
	//    their display order: within one date every post gets -N.html
	//    where newer posts have larger N (the listing sorts by descending
	//    filename within a date), matching the old listing order.
	dateCount := map[string]int{}
	for _, e := range entries {
		dateCount[e.date.Format("20060102")]++
	}
	seen := map[string]int{}
	for i := range entries {
		key := entries[i].date.Format("20060102")
		seen[key]++
		entries[i].suffix = dateCount[key] - seen[key] + 1
	}

	// 4. Write post fragments.
	fmt.Println("posts:")
	for _, e := range entries {
		fname := e.date.Format("20060102")
		if dateCount[fname] > 1 {
			fname += "-" + strconv.Itoa(e.suffix)
		}
		fname += ".html"
		var b strings.Builder
		fmt.Fprintf(&b, "<!-- id: %s -->\n", e.id)
		if e.title != "" {
			fmt.Fprintf(&b, "<!-- title: %s -->\n", e.title)
		}
		content := rewriteRelative(e.excerpt)
		if e.article != "" {
			fmt.Fprintf(&b, "<!-- alias: %s -->\n", strings.TrimSuffix(e.article, ".html"))
			b.WriteString("<!-- more -->\n")
			if content != "" {
				b.WriteString(content)
				b.WriteString("\n")
			}
			b.WriteString(rewriteRelative(e.articleBody))
			b.WriteString("\n")
			fmt.Printf("  %-22s  <- #%s (%s), article %s merged\n", fname, e.id, e.date.Format("2006.1.2"), e.article)
		} else {
			b.WriteString(content)
			b.WriteString("\n")
			fmt.Printf("  %-22s  <- #%s (%s)\n", fname, e.id, e.date.Format("2006.1.2"))
		}
		if err := os.WriteFile(filepath.Join(postsDir, fname), []byte(b.String()), 0o644); err != nil {
			return err
		}
	}

	// 5. Convert boilerplate pages into fragments.
	fmt.Println("pages:")
	pages := []string{"about.html", "special.html", "releases.html"}
	specials, err := filepath.Glob(filepath.Join(*src, "special", "*.html"))
	if err != nil {
		return err
	}
	for _, sp := range specials {
		rel, err := filepath.Rel(*src, sp)
		if err != nil {
			return err
		}
		pages = append(pages, filepath.ToSlash(rel))
	}
	for _, rel := range pages {
		data, err := os.ReadFile(filepath.Join(*src, filepath.FromSlash(rel)))
		if err != nil {
			fmt.Fprintf(os.Stderr, "warning: page %s: %v\n", rel, err)
			continue
		}
		suffix, content, err := extractPage(data)
		if err != nil {
			fmt.Fprintf(os.Stderr, "warning: page %s: %v\n", rel, err)
			continue
		}
		var b strings.Builder
		if suffix != "" {
			fmt.Fprintf(&b, "<!-- title: %s -->\n", suffix)
		}
		b.WriteString(rewriteRelative(content))
		b.WriteString("\n")
		out := filepath.Join(pagesDir, filepath.FromSlash(rel))
		if err := os.MkdirAll(filepath.Dir(out), 0o755); err != nil {
			return err
		}
		if err := os.WriteFile(out, []byte(b.String()), 0o644); err != nil {
			return err
		}
		fmt.Printf("  /%s\n", rel)
	}

	// 6. Copy static assets.
	fmt.Println("static:")
	nStatic := copyStatic(*src, staticDir)

	// 7. Report anything that was not referenced by any entry.
	articleFiles, _ := filepath.Glob(filepath.Join(*src, "articles", "*.html"))
	for _, a := range articleFiles {
		stem := strings.TrimSuffix(filepath.Base(a), ".html")
		if !usedArticles[stem] {
			fmt.Printf("  skipped orphan article %s (no entry points to it; kept in source tree)\n", filepath.Base(a))
		}
	}
	fmt.Printf("\ndone: %d posts, %d pages, %d static files written to %s\n", len(entries), len(pages), nStatic, *dst)
	return nil
}

// extractEntries pulls every <div id="pNN" class="entry"> block out of a
// listing page, honouring div nesting when finding the matching </div>.
func extractEntries(src string) []convEntry {
	var out []convEntry
	for _, loc := range entryOpenRe.FindAllStringSubmatchIndex(src, -1) {
		id := src[loc[2]:loc[3]]
		start := loc[1]
		end := -1
		depth := 1
		for _, tok := range divTokenRe.FindAllStringIndex(src[start:], -1) {
			if strings.HasPrefix(src[start+tok[0]:], "</div>") {
				depth--
			} else {
				depth++
			}
			if depth == 0 {
				end = start + tok[0]
				break
			}
		}
		if end < 0 {
			fmt.Fprintf(os.Stderr, "warning: entry #%s: unbalanced divs, skipping the rest\n", id)
			break
		}
		e, err := parseConvEntry(id, src[start:end])
		if err != nil {
			fmt.Fprintf(os.Stderr, "warning: entry #%s: %v\n", id, err)
			continue
		}
		out = append(out, e)
	}
	return out
}

// parseConvEntry pulls the title (<h1>, which may come before or after the
// date), the date (wrapped in <p> or bare text, as found in the archives)
// and the optional ">>> More" article pointer out of one entry.
func parseConvEntry(id, inner string) (convEntry, error) {
	e := convEntry{id: id}
	if m := h1Re.FindStringSubmatchIndex(inner); m != nil {
		e.title = strings.TrimSpace(inner[m[2]:m[3]])
		inner = inner[:m[0]] + inner[m[1]:]
	}
	inner = strings.TrimSpace(inner)
	var date time.Time
	if m := datePRe.FindStringSubmatchIndex(inner); m != nil {
		var err error
		date, err = parseYMD(inner[m[2]:m[3]], inner[m[4]:m[5]], inner[m[6]:m[7]])
		if err != nil {
			return e, err
		}
		inner = strings.TrimSpace(inner[m[1]:])
	} else if m := dateBareRe.FindStringSubmatchIndex(inner); m != nil {
		var err error
		date, err = parseYMD(inner[m[2]:m[3]], inner[m[4]:m[5]], inner[m[6]:m[7]])
		if err != nil {
			return e, err
		}
		inner = strings.TrimSpace(inner[m[1]:])
	} else {
		return e, fmt.Errorf("no date found")
	}
	e.date = date
	if m := articleLinkRe.FindStringSubmatchIndex(inner); m != nil {
		e.article = inner[m[2]:m[3]]
		inner = inner[:m[0]] + inner[m[1]:]
	}
	e.excerpt = strings.TrimSpace(inner)
	return e, nil
}

// extractArticle returns the title and body of an old article page, with
// the surrounding boilerplate (h1, date, subtitle, "Back" link) removed.
func extractArticle(src, name string) (title, body string, err error) {
	data, err := os.ReadFile(filepath.Join(src, "articles", name))
	if err != nil {
		return "", "", err
	}
	m := contentCellRe.FindStringSubmatch(string(data))
	if m == nil {
		return "", "", fmt.Errorf("articles/%s: content cell not found", name)
	}
	body = m[1]
	if h := h1Re.FindStringSubmatchIndex(body); h != nil {
		title = strings.TrimSpace(body[h[2]:h[3]])
		body = body[:h[0]] + body[h[1]:]
	}
	body = strings.TrimSpace(body)
	body = subtitleRe.ReplaceAllString(body, "")
	if dm := datePRe.FindStringSubmatchIndex(body); dm != nil {
		body = strings.TrimSpace(body[dm[1]:])
	} else if dm := dateBareRe.FindStringSubmatchIndex(body); dm != nil {
		body = strings.TrimSpace(body[dm[1]:])
	}
	body = strings.TrimSpace(backLinkRe.ReplaceAllString(body, ""))
	return title, body, nil
}

// extractPage returns the <title> suffix and the content cell of a
// boilerplate page.
func extractPage(data []byte) (suffix, content string, err error) {
	suffix = ""
	if m := titleTagRe.FindStringSubmatch(string(data)); m != nil {
		suffix = strings.TrimSpace(m[1])
		suffix = strings.TrimSpace(strings.TrimSuffix(suffix, " :: 明月樓閒話 Mingyuet Comments"))
	}
	m := contentCellRe.FindStringSubmatch(string(data))
	if m == nil {
		return "", "", fmt.Errorf("content cell not found")
	}
	return suffix, strings.TrimSpace(m[1]), nil
}

// copyStatic copies the site's non-HTML assets: root-level files (style.css,
// images, robots.txt, ...) and the known asset directories (assets/,
// releases/). HTML files, editor backups (*~) and directories handled as
// content (archives/, articles/, special/) or code (server/) are excluded.
func copyStatic(src, dst string) int {
	n := 0
	rootEntries, err := os.ReadDir(src)
	if err != nil {
		fmt.Fprintf(os.Stderr, "warning: reading %s: %v\n", src, err)
		return 0
	}
	assetDirs := map[string]bool{"assets": true, "releases": true}
	for _, ent := range rootEntries {
		name := ent.Name()
		if ent.IsDir() {
			if assetDirs[name] {
				n += copyDir(filepath.Join(src, name), filepath.Join(dst, name))
				continue
			}
			fmt.Printf("  skipped directory %s/\n", name)
			continue
		}
		if strings.HasSuffix(name, "~") || strings.HasSuffix(name, ".html") || strings.HasPrefix(name, ".") {
			continue
		}
		if copyFile(filepath.Join(src, name), filepath.Join(dst, name)) {
			fmt.Printf("  /%s\n", name)
			n++
		}
	}
	return n
}

func copyDir(src, dst string) int {
	n := 0
	filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return nil
		}
		if d.IsDir() {
			return os.MkdirAll(filepath.Join(dst, mustRel(src, path)), 0o755)
		}
		if strings.HasSuffix(path, "~") || strings.HasPrefix(d.Name(), ".") {
			return nil
		}
		rel := mustRel(src, path)
		if copyFile(path, filepath.Join(dst, rel)) {
			fmt.Printf("  /%s\n", filepath.ToSlash(rel))
			n++
		}
		return nil
	})
	return n
}

func copyFile(src, dst string) bool {
	data, err := os.ReadFile(src)
	if err != nil {
		fmt.Fprintf(os.Stderr, "warning: %v\n", err)
		return false
	}
	if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
		fmt.Fprintf(os.Stderr, "warning: %v\n", err)
		return false
	}
	if err := os.WriteFile(dst, data, 0o644); err != nil {
		fmt.Fprintf(os.Stderr, "warning: %v\n", err)
		return false
	}
	return true
}

func mustRel(base, target string) string {
	rel, err := filepath.Rel(base, target)
	if err != nil {
		return filepath.Base(target)
	}
	return rel
}