diff options
| author | Sebastian Zack Tin Lahm-Lee <bctnry@sdf.org> | 2026-10-04 12:58:12 +0800 |
|---|---|---|
| committer | Sebastian Zack Tin Lahm-Lee <bctnry@sdf.org> | 2026-10-04 12:58:12 +0800 |
| commit | 78b410c668354c30323a259167beb7eddaa2d58f (patch) | |
| tree | b45dc58e106686deba0c71ac65572ccc9d29f0af /convert.go | |
Diffstat (limited to 'convert.go')
| -rw-r--r-- | convert.go | 430 |
1 files changed, 430 insertions, 0 deletions
diff --git a/convert.go b/convert.go new file mode 100644 index 0000000..1673785 --- /dev/null +++ b/convert.go @@ -0,0 +1,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)">([^<]*>[^<]*)</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 +} |
