diff --git a/.editorconfig b/.editorconfig index d52cabe..2da1302 100644 --- a/.editorconfig +++ b/.editorconfig @@ -63,7 +63,7 @@ end_of_line = unset insert_final_newline = false trim_trailing_whitespace = false -# Caddy map files are tab-separated redirect tables generated by `checks/build-redirects.py`. +# Caddy map files are space-separated redirect tables generated by `capture/build-redirects.py`. # Trailing whitespace is significant to the parse, and the generator owns the formatting. [deploy/maps/*.map] trim_trailing_whitespace = false diff --git a/.gitattributes b/.gitattributes index e740a2f..12b533e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -15,10 +15,14 @@ # A CRLF shebang breaks execution, so scripts stay LF regardless of the default. *.sh text eol=lf -# The URL-parity and redirect-map generators are shebang-executable and run by path in CI. -# They are pinned individually rather than by a blanket `*.py` rule. -checks/build-redirects.py text eol=lf +# Shebang-executable Python, where a CRLF on line one is a broken interpreter line rather +# than a cosmetic difference. `capture/` is pinned whole, because everything there is a +# script; under `checks/` the two executables are named, because that directory also holds +# lists and fixtures. Neither is a blanket `*.py` rule, so a future non-executable module +# elsewhere is not swept in by accident, and a new executable needs a line here. +capture/*.py text eol=lf checks/check-url-parity.py text eol=lf +checks/check-env-docs.py text eol=lf # These formats are parsed line by line by a daemon rather than by a shell. # Caddy and OpenSSH both reject or silently mis-parse a CRLF file. diff --git a/.github/workflows/validate-task.yml b/.github/workflows/validate-task.yml index 20eb390..b4dab3a 100644 --- a/.github/workflows/validate-task.yml +++ b/.github/workflows/validate-task.yml @@ -59,7 +59,7 @@ jobs: - name: Lint shell scripts step run: | set -Eeuo pipefail - scripts=(checks/check-live-urls.sh deploy/make-release.sh ops/vps-backup-pull ops/install.sh) + scripts=(checks/check-live-urls.sh deploy/make-release.sh ops/vps-backup-pull ops/install.sh capture/run-wp2hugo.sh) docker run --rm --pull=always -v "$PWD":/mnt --workdir /mnt \ koalaman/shellcheck:stable "${scripts[@]}" docker run --rm --pull=always -v "$PWD":/mnt --workdir /mnt \ diff --git a/.gitignore b/.gitignore index 076afa5..0678a5b 100644 --- a/.gitignore +++ b/.gitignore @@ -19,7 +19,7 @@ hugo_stats.json *.user .claude -# Python byproducts from the check and redirect-map generators under `checks/`. +# Python byproducts from the gates under `checks/` and the provenance tools under `capture/`. __pycache__/ *.py[cod] .venv/ diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md index 6cc1584..c9bfdd9 100644 --- a/ENVIRONMENT.md +++ b/ENVIRONMENT.md @@ -27,7 +27,10 @@ Held in `secrets/..env`, one file per environment. Template | `EXPECT_SITE_ENV` | the environment that must answer, compared against the `X-Blog-Env` header the bundle stamps | A proxy rule aimed at the wrong container returns a healthy 200 under the right hostname, so the check refuses to start rather than proving nothing. | | `PANGOLIN_ACCESS_TOKEN_ID` | the resource access token's id, for an environment behind the auth gate | Set both or neither. Leave both unset for a site that is public. | | `PANGOLIN_ACCESS_TOKEN` | the token itself | Read by `check-live-urls.sh`. Staging keeps its gate on because it serves a byte-identical copy of the public site. | -| `CAPTURE_ROOT` | the provenance capture, holding the WordPress exports, the crawl of the old platform, and the inventories derived from it | `checks/build-redirects.py` takes it as its one argument. Environment-independent, so it belongs in the default file only. Nothing sources it. | +| `CAPTURE_ROOT` | the provenance capture, holding the WordPress exports, the crawl of the old platform, and the inventories derived from it | Every script under [`capture/`](./capture/) reads beneath it, and all but one write there too. The exception is [`capture/build-redirects.py`](./capture/build-redirects.py), which writes the committed maps under `deploy/maps/` in this repository, and which also accepts the capture as a first argument that wins over this value. Environment-independent, so it belongs in the default file only. | +| `CAPTURE_SOURCE_URL` | the old platform's base URL, the site the crawl and the URL verification ran against | **Not `HUGO_BASEURL`.** The two hold the same string after the cutover and mean different things, so merging them points a verification run at the new site while every check still passes. Environment-independent. | +| `CAPTURE_SOURCE_API` | the old platform's REST API for that site, carrying its numeric site id | Read for the post and page bodies in **rendered** form, which is what expands shortcodes so a media reference is seen the way a reader's browser sees it. Environment-independent. | +| `CAPTURE_AUTHOR_SLUG` | the old platform's author slug, used to backfill the author archive and its pagination | Optional, and an account name rather than a site value, which is why it is a variable at all. Unset, [`capture/classify.py`](./capture/classify.py) skips the backfill and says so, rather than emitting a list that is silently short by the author URLs. Environment-independent. | | `VPS_SSH_HOST` | the VPS administrative login | Not the deploy account. See "Two credentials" below. Environment-independent. | | `VPS_TRAEFIK_LOG` | today's live access log on the VPS, still being appended to | Never pulled, because rotation is what makes a file eligible. An analysis covering today reads it over SSH. Nothing sources it. | | `VPS_TRAEFIK_LOG_ARCHIVE` | the rotated access logs on the VPS, and the source of the off-host copy | Also read by the pull, below. | diff --git a/OPERATIONS.md b/OPERATIONS.md index ff56db6..22b83b8 100644 --- a/OPERATIONS.md +++ b/OPERATIONS.md @@ -48,26 +48,19 @@ This site has served the same domain across earlier platforms, so its whole oper ## The Migration Record -**The migration is documented once, as a post on the site, and that post is the artifact to reference.** [`content/posts/2026/08/01/moving-this-blog-from-wordpress-to-hugo.md`](./content/posts/2026/08/01/moving-this-blog-from-wordpress-to-hugo.md) holds how the URL surface was captured, why the contract splits into a render half and a redirect half, why the Blogger permalink map needs more entries than the posts it covers, why the media had to come from the export tar and be hash-verified, and which Hugo taxonomy default moves every archive to a new address without reporting anything. +**The procedure and the facts live in the directory READMEs.** [`capture/README.md`](./capture/README.md) is the authority on how the inputs were captured and what is derived from them, [`checks/README.md`](./checks/README.md) on the URL contract, and [`deploy/README.md`](./deploy/README.md) on how the redirects are expressed. Each sits beside the thing it describes, which is what keeps it true. -**Read it before changing anything under [`checks/`](./checks/) or [`deploy/maps/`](./deploy/maps/).** Both hold values that no code derives and no test explains, and the reasoning behind them is in the post rather than beside them. Cite the post rather than restating it. This file is the procedure and the post is the account of how the procedure came to be, so where the two disagree this file governs what to do while the post explains why the check exists. +**The migration also has an account of itself, as a post on the site.** It is the casual version, what was done and how it went, and it is worth reading before changing anything under [`checks/`](./checks/) or [`deploy/maps/`](./deploy/maps/), because those hold values that no code derives. + +**The direction between them is one-way.** A post may cite a README. A README never cites the post. A doc that sends a reader to published prose for an operational fact has put the fact where it cannot be kept current, and where correcting it means editing something people have already read. **The post is content, so it sits under the URL contract.** Editing it moves nothing. Renaming it or taking it down breaks an address the site serves. A fact in it that proves wrong is corrected in the post rather than footnoted here. ### Rebuilding from the Exports -Everything derived is in this repository. Everything it was derived *from* is in a capture directory outside it, which is where a rebuild starts. **The capture path is `CAPTURE_ROOT` in `secrets/local.production.env`**, recorded alongside the other values that name a machine rather than the project, so it is read from there rather than searched for. The capture is not a git repository, so it has no history to revert to, and it is read-only in normal use. - -| Under the capture | Holds | Recoverable | -| --- | --- | --- | -| `export/raw/` | the WordPress content export, WXR XML | yes, from the WordPress account while it exists | -| `export/media-tar/` | the media export, the only trustworthy copy of the images | yes, from the same place | -| `mirror/` | a crawl of the old platform as it served, including the media it linked from other hosts | no, once the old hosting ends | -| `inventory/` | the URL and media inventories derived from that crawl | no, for the same reason | - -The two exports are the only inputs a person has to fetch, and `EXPORT-INSTRUCTIONS.md` at the root of the capture records which two menu items produce them and the counts each has to reconcile against. The counts are the point, because a partial export is the common way a migration loses posts without reporting anything. +Everything derived is in this repository. Everything it was derived *from* is a capture directory outside it, at `CAPTURE_ROOT`, which is where a rebuild starts. The capture is not a git repository, so it has no history to revert to, and it is read-only in normal use. -[`checks/build-redirects.py`](./checks/build-redirects.py) takes the capture directory as its one argument and rebuilds everything under `deploy/maps/` from it. It selects the export **by content** rather than by filename and fails unless exactly one candidate holds published posts, because the capture also holds a media-only export whose zero posts produce empty maps that are indistinguishable from working ones until the redirects are live. +**[`capture/README.md`](./capture/README.md) holds the procedure**: what is under the capture and which parts of it can be fetched again, the two exports and the counts they must reconcile against, the ordered rebuild, and the results that look like success and are not. ## Local Verification Before a Pull Request @@ -420,7 +413,7 @@ Ordering is load-bearing, so every redirect lives in a single `route` block. Out | Blogger label archives | `labels.map`, defaulting to the archive index | | Term archives the generator does not build | `terms.map` | -The maps are generated by `checks/build-redirects.py` from the source export, which lives outside this repository. It is a provenance script rather than a CI step, and its outputs are committed. It selects the export by content and refuses to run unless exactly one contains published posts, because the capture holds a full export and a media-only one, and reading the wrong one yields empty maps that are indistinguishable from working ones until the redirects are live. +The maps are generated by [`capture/build-redirects.py`](./capture/build-redirects.py) and the generated files are committed, so a deploy never regenerates them. How it selects its input, and why that selection is the part to get right, is in [`capture/README.md`](./capture/README.md). ## Server Hardening diff --git a/README.md b/README.md index 9450866..b9f406a 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ Deployment is a release directory plus a symlink. A build is installed alongside The site has served the same domain since 2008, across three platforms: Blogger until 2012, WordPress until 2026, and Hugo from then on. Converting the posts took an afternoon. Preserving sixteen years of inbound links was the work, and it is why this repository carries a URL contract and gates it rather than trusting the build. -The account of that migration is a post on the site, [Moving This Blog From WordPress to Hugo][migration-post]. It covers what a WordPress export holds and what it leaves out, why the sitemap named barely a tenth of the addresses the site was actually serving, how the Blogger-era permalinks resolve through a lookup table rather than a pattern, why media fetched over HTTP is not the same bytes as the media in the export and only a content hash tells them apart, and which Hugo default moves every taxonomy archive to a new address without reporting anything. +How it was done is in [`capture/README.md`][capture-readme], and the account of it is a post on the site, [Moving This Blog From WordPress to Hugo][migration-post]. It covers what a WordPress export holds and what it leaves out, why the sitemap named barely a tenth of the addresses the site was actually serving, how the Blogger-era permalinks resolve through a lookup table rather than a pattern, why media fetched over HTTP is not the same bytes as the media in the export and only a content hash tells them apart, and which Hugo default moves every taxonomy archive to a new address without reporting anything. ## How a Change Reaches the Site @@ -152,6 +152,7 @@ flowchart LR | [`hugo.yaml`][hugo-config] | site configuration, taxonomy URLs, and the feed name | | [`checks/`][checks] | the URL contract and the gates that enforce it | | [`deploy/`][deploy] | the release script, the web-server config, and the redirect maps | +| [`capture/`][capture] | the migration's provenance tooling, and how the site was derived from the old platform's exports | | [`ops/`][ops] | the pull that copies the server's backups and access logs off it, and its schedule | | [`ENVIRONMENT.md`][environment] | every configuration value, described once | @@ -214,6 +215,8 @@ Licensed under the [MIT License][license]\ [checks]: ./checks/ [commits-link]: https://github.com/ptr727/Blog/commits [deploy]: ./deploy/ +[capture]: ./capture/ +[capture-readme]: ./capture/README.md [ops]: ./ops/ [environment]: ./ENVIRONMENT.md [deploy-readme]: ./deploy/README.md diff --git a/TODO.md b/TODO.md index ef0762e..729cc83 100644 --- a/TODO.md +++ b/TODO.md @@ -1,6 +1,6 @@ # TODO -Running backlog for this repo, kept in a committed file so the work survives across sessions. How the migration was done is a [post on the blog][migration-post] rather than a section here. +Running backlog for this repo, kept in a committed file so the work survives across sessions. How the migration was done is in [`capture/README.md`](./capture/README.md), with a casual account of it as a [post on the blog][migration-post]. ## State @@ -37,7 +37,7 @@ The site is built, gated in CI, and deployed to staging by pipeline. It is not y - **The first deploy did not fix the 404, and that is what turned this from a gap into a decision.** The VPS agent raised it in §22.10 and both halves were measured rather than assumed: the site emitted no `robots.txt` at all, because `hugo.yaml` set no `enableRobotsTXT`, so the 404 survived the deploy and `X-Robots-Tag` was the only control, while `sitemap.xml` **was** emitted and became fetchable on the interim name at that same deploy. A crawler got a full sitemap and no robots file. `enableRobotsTXT` is now set and a deploy has carried it, so this describes the state up to release `20260808-041050` rather than what is served today. - **At the cutover this stops being a gap and becomes a loss, which is the half neither side had checked.** The live `.com` blog **serves a `robots.txt` today, carrying a `Sitemap:` line**. Because this site emitted none, M7b would not have been a return to a previous state, it would have been a move from having crawl directives to having none on a site that has had them for years, and the sitemap pointer would have gone with them. The VPS agent measured this from the outside in §23.3, will not put a file in this repository's bundle, and has made it a decision that blocks step 1 of the M7b checklist rather than one discovered after it. The minimum that preserves today's behavior is `User-agent: *`, no `Disallow`, and the sitemap line, since every `Disallow` the old platform serves names a WordPress path this site does not have. **That is what was chosen**, out of three options: preserve today's behavior, write what this site actually wants, or keep emitting nothing and accept the loss. The sitemap URL is derived from the built `baseURL` rather than typed, which is what makes the choice survive the cutover without a second edit. - **The log reframes the decision, and it is the `Sitemap:` line that carries it rather than any rule.** Across the interim hostname's first full day, `/robots.txt` was requested nine times and answered 404 every time, five of those from real agents on a hostname with no inbound links. **No crawler fetched `sitemap.xml` or `feed.xml` once**: every request to either came from `curl`, the deploy gate's or the host side's. Crawlers do not guess a sitemap's location, they are told it, and the only thing telling them today is the `robots.txt` the old platform serves, which is the file the cutover deletes. So the question is not whether to have crawl directives, it is whether the sitemap stays advertised at all. Measured on the host side in its §26.4 and recorded here because the decision outlives that channel. - - **`/robots.txt/`, with a trailing slash, now redirects to the real file** rather than to the home page, in the same change, since the two are only correct together. The fix is in `build-redirects.py` rather than in the generated map, because the map is rewritten from the capture and a hand edit does not survive the next regeneration. `/osd.xml/` stays pointed at the home page: it was the old platform's OpenSearch description and this site emits no such file. + - **`/robots.txt/`, with a trailing slash, now redirects to the real file** rather than to the home page, in the same change, since the two are only correct together. The fix is in `capture/build-redirects.py` rather than in the generated map, because the map is rewritten from the capture and a hand edit does not survive the next regeneration. `/osd.xml/` stays pointed at the home page: it was the old platform's OpenSearch description and this site emits no such file. - **A wrong `HUGO_BASEURL` is still invisible to every gate here, and the `Sitemap:` line does not change that.** Worth stating because the opposite is easy to believe: the parity check compares the advertised origin against the one on the home page's canonical link, and both come from `baseURL`, so they agree whenever the build is coherent — including when `baseURL` was wrong for the environment. Nothing inside the artifact can see it, which is why the check belongs on the side that knows which host it is serving, and the VPS side does it by reading the origin out of the deployed `sitemap.xml`, `og:url` and `feed.xml`. What the comparison does catch is an origin **written rather than derived**, a committed `static/robots.txt` shadowing the template being the way that happens. - **Media is checked live now, which unblocks the item below.** [`checks/golden-media-live.txt`](./checks/golden-media-live.txt) is fetched by `check-live-urls.sh` against a running server, covering both media trees and the `@uploads` rule, and asserting status, a non-zero body and an image content type so that a 403 from a bad mode, a 404 from a lost transfer, a truncated file and a soft-404 error page are each caught. Verified against production, and each of the four failure shapes was reproduced rather than assumed. The record of why it was needed follows. - **~~Nothing checks that media survived the trip to the server.~~ Closed 2026-08-08, by the item above.** The VPS agent noticed in §24.3 that a 3,095-request gate run fetched no image at all, and asked whether `golden-media-legacy.txt` is wired in. It is, but only at build time, in `check-url-parity.py`, against files on disk. The live check requests pages and redirects and never an image, so a media tree lost **between the build and the server**, a partial upload, is caught by neither: the build passed before the loss and the live gate never asks. On a site whose value is eighteen years of posts with images in them, that is the gap worth closing rather than the one that was suspected. A handful of media URLs in the live check would close it, chosen to cover both trees rather than to be exhaustive, since the build gate already proves the set. The mechanism that makes this concrete rather than theoretical is the hard-link trap below: a link carries its inode's mode, so a media file that acquires a bad one rides the chain into every later release, present and correctly named and unreadable to the server, which `is_file()` on the runner cannot see and a check that never requests an image cannot either. @@ -83,8 +83,8 @@ The reference leaf the hub now ships carries one step this repo's deploy does no - **The pull itself is resolved and the reasoning is kept because it applies to everything still listed here.** What made it urgent was measured: the copy protected everywhere was the VPS's older one, while the copy that actually ran, carrying the log leg the review depends on, was in no snapshot and no repository. Committing it is what closed that, not the backup host's own off-site copy, which never reached the script. - **The directory holding it is named as though it were disposable.** `~/vps-backup-pull-patch` reads as a patch staged against a source, and there is no source: it is the most complete copy of the script in existence. A directory named for a temporary artifact is the one a cleanup deletes, and nothing here would notice until a restore produced the wrong script. - **The same reasoning points at the home-automation configuration repository for anything that is purely this host's**, since that is where the rest of the backup host's service configuration already lives. The pull is here instead because [`OPERATIONS.md`](./OPERATIONS.md) "Log Review" is what stops working without it. Revisit if a second unrelated host service ends up here. - - **The same question covers the migration toolchain in the capture directory**, which is fourteen scripts: the `wp2hugo` run, the content restructure and clean passes, external-media localization, the crawl and mirror, the golden-URL build, and the media inventory. Some are worth keeping only if generalized, and some are cheaper to rewrite than to maintain, so this is a per-script call rather than one decision. - - **One of them is already three copies with two of them stale**, which is the concrete version of this risk rather than a hypothetical one. `build-redirects.py` exists at the capture root, again under the capture's own `checks/`, and here at [`checks/build-redirects.py`](./checks/build-redirects.py). The two capture copies are identical to each other at 115 lines; the copy in this repository is the maintained one at 225. Nothing detects that, because the capture is not a git repository and is read-only in normal use. + - **Resolved for the migration toolchain: the durable scripts are in this repository at [`capture/`](./capture/).** The fourteen split by whether they can ever run again rather than by whether they look reusable. A re-export re-runs the conversion chain, so `run-wp2hugo.sh`, `clean-content.py`, `restructure-content.py`, `localize-external.py` and `enumerate-media.py` are carried. `build-golden.py` and `classify.py` are carried as the record behind an append-only contract, and say so, since they cannot run once the old hosting ends. The crawl pair and the three fetchers are named in [`capture/README.md`](./capture/README.md) rather than carried, because their outputs are the durable artifact and the scripts hit a site that will be gone. + - **The three copies of `build-redirects.py` are down to one.** The maintained copy moved from `checks/` to [`capture/`](./capture/build-redirects.py), which is where it belonged: it generates rather than gates, and `checks/` is defined as the contract and the gates that enforce it. Both stale copies in the capture are named by path in the capture README and marked stale, so finding one is not mistaken for finding a source. - **What `robots.txt` says, which is undecided and is the last non-mechanical item before M7b.** Recorded under "Next" above, where it blocks the cutover. - `/osd.xml/` sits in `slugs.map` pointing at `/`, and stays there unless this site ever emits an OpenSearch description. `/robots.txt/` was the other half and is resolved, above. - Content is capped at a fixed 720px on every screen, because PaperMod's width is four CSS variables with no responsive term and no Hugo parameter. The prose measure is right and should stay; images and galleries inheriting the same cap is the part that costs something on a wide display. The knobs, the override location, and the `--gap` trap are documented under "Customization points" in [`themes/README.md`](./themes/README.md). @@ -160,7 +160,7 @@ The URL contract lives in this repo and is the thing CI enforces. | [`checks/README.md`](./checks/README.md) | how the contract was derived | | [`deploy/README.md`](./deploy/README.md) | the release mechanics and the redirect design | -The provenance store holds the raw exports, the media tar, and the crawl. It lives outside this repo, is never published, and is passed to `checks/build-redirects.py` as an argument, which is why that script is a provenance tool rather than a CI step. +The capture holds the raw exports, the media tar, and the crawl. It lives outside this repo at `CAPTURE_ROOT` and is never published, because it carries commenter email addresses and IP addresses that the conversion drops rather than scrubs. [`capture/README.md`](./capture/README.md) is the procedure. Secrets and variables, per environment. The App-token pair is repository-scoped rather than per-environment. diff --git a/capture/README.md b/capture/README.md new file mode 100644 index 0000000..76e5e8a --- /dev/null +++ b/capture/README.md @@ -0,0 +1,122 @@ +# Provenance Capture + +Everything in this repository is derived. What it was derived *from* is a capture directory that lives outside it, and this directory holds the scripts that read that capture. + +The capture's path is `CAPTURE_ROOT`, recorded alongside the other values that name a machine rather than the project. It is environment-independent, so unlike a deploy root it belongs in `secrets/local.production.env` alone rather than in a copy per environment: there is one capture, and four copies of its path is four chances for three of them to be wrong. It is not a git repository, so it has no history to revert to, and it is read-only in normal use. Nothing here writes into it except the steps below that say they do. + +**None of this runs in CI, and none of it runs on a schedule.** These are provenance tools, run by hand, and their outputs are committed. That is the whole difference between this directory and [`checks/`](../checks/), which holds gates that run on every change. + +## What is under the capture + +| Under the capture | Holds | Recoverable | +| --- | --- | --- | +| `export/raw/` | the WordPress content export, WXR XML | yes, from the WordPress account while it exists | +| `export/media-tar/` | the media export, the only trustworthy copy of the images | yes, from the same place | +| `mirror/` | a crawl of the old platform as it served, including the media it linked from other hosts | no, once the old hosting ends | +| `inventory/` | the URL and media inventories derived from that crawl | no, for the same reason | + +**The mirror spans more hosts than the blog.** It was taken across the blog itself, the platform's image CDN, and the Google hosts that served the hotlinked images, which is why it holds media that was never in the media library. That matters beyond the migration: [`checks/README.md`](../checks/README.md) adjudicates orphaned media against this tree, and an adjudication is only as good as what the crawl reached. + +**The capture holds personal data and is never committed.** The WXR carries commenter email addresses and IP addresses, and the mirror carries the same data rendered into HTML. The conversion resolves this by dropping comments entirely rather than scrubbing them, so there is no partial to get wrong, and the site this repository builds has none. The capture itself keeps them, which is one more reason it stays outside git. + +## The two exports, and the counts they must reconcile + +Two downloads from the WordPress account, both from Tools then Export. + +1. **The content export.** Choose **All content** and do not filter by date or type. One WXR XML file. This carries the post and page bodies in raw form, the comments, the categories and tags, and pointers to the media. It is the primary input and the one thing that cannot be fetched from outside the account. +2. **The media library export.** A separate menu item on the same page, producing a `.tar` organized into year and month folders. Not strictly required, because the crawl captures what the posts reference, but worth taking for two reasons: it includes media that was uploaded and never embedded in a post, which the XML omits entirely, and it avoids rate-limiting during conversion. + +**Verify the export against what the live site reported before trusting it.** A partial export is the common way a migration loses posts without reporting anything, so a mismatch is a stop-and-investigate rather than a rounding error. These are a **measurement of the old platform taken 2026-07-29**, not values this repository can check, and they are recorded because nothing else will ever be able to state them again: + +| | Measured | +| --- | --- | +| Posts | 108 | +| Pages | 2 | +| Comments | 397 | +| Categories | 12 | +| Tags | 183 | +| Media assets | 941, being 675 in the library and 266 hotlinked | + +**Do not cancel the old plan, delete the site, or change DNS until the cutover is done and has held.** The conversion fetches media over HTTP from the live site, so cancelling early loses images, and deleting the site destroys the ability to re-export. The DNS change *is* the cutover and comes last. + +## Rebuilding from the exports + +In order. Each Python step is a dry run by default and takes `--apply` to write. + +Everything here is standard library except `clean-content.py`, which needs PyYAML to read front matter. It names the package if it is missing rather than raising an import error. + +```sh +set -a; . secrets/local.production.env; set +a + +capture/run-wp2hugo.sh # convert, into $CAPTURE_ROOT/converted/ +capture/clean-content.py --apply # drop comments, reduce the front matter +capture/restructure-content.py --apply # reshape the tree to match the URLs +capture/localize-external.py --apply # pull the hotlinked images local +capture/build-redirects.py # regenerate deploy/maps/ +``` + +`build-redirects.py` is the only one that writes into this repository, and what it writes is committed. The other four write into the capture. + +**The export is selected by content, never by filename.** An account holds several exports and a media-only one carries the attachments and no posts, so a glob would choose by filesystem order and converting the wrong one yields a site that builds and is empty. `build-redirects.py` makes the choice, and `run-wp2hugo.sh` asks it with `--print-export` rather than repeating the logic, so the conversion and the maps are provably built from the same file. + +## What the conversion does not carry + +**Hotlinked images are in no export.** Images embedded from other hosts during the Windows Live Writer and Blogger era were never in the media library, so they are absent from the WXR, and the converter skips them as non-relative links. Left alone they stay a permanent dependency on someone else serving fifteen-year-old URLs. `localize-external.py` downloads them, names each by a hash of its source URL, because the originals carry characters that do not survive a filesystem, then rewrites every reference and records the mapping in the capture's inventory. + +**Comments are dropped rather than scrubbed.** The blog is read-only going forward, so the data file is deleted outright. There is no partial scrub to get wrong and nothing to carry. + +**Front matter is reduced to what drives the site.** The converter carries every WordPress custom field through, most of them platform internals that no template reads. `clean-content.py` keeps a short list and drops the rest. The list is in the script rather than restated here, so a reader can diff it against a new export. + +## Three results that look like success and are not + +- **A Picasa or ggpht URL whose size segment ends in `-h` returns HTTP 200 with an HTML page**, not an image, and a naive fetch writes a few hundred bytes of markup with a successful status. `localize-external.py` parses the wrapper and follows the `` it names, which is the platform's own answer rather than a guess. +- **Any non-image body is a failure regardless of status.** The magic bytes are checked, and anything that is not an image is reported rather than written. +- **Selecting the export by filename yields empty maps that pass every check** until the redirects are live. See the note above on selection by content. + +## How the URL contract was captured + +The contract in [`checks/`](../checks/) was not derived from the content tree. It was measured against the live old platform, by union of three sources and then verified URL by URL: + +| Script | Did | +| --- | --- | +| `enumerate-media.py` | pulled every post and page from the platform's REST API in **rendered** form, so shortcodes were expanded and a media reference was seen as a browser sees it, and split the results by host to separate library media from hotlinks | +| `build-golden.py` | unioned the crawl, the sitemap and a derivation of the archive and pagination shapes, then requested every candidate against the live site and recorded what it answered | +| `classify.py` | split the verified set into what must render and what must redirect, using the sitemap as the discriminator for bare one-segment URLs, which are ambiguous between a real page and an attachment page | + +**These three cannot run again once the old hosting ends.** They are carried as the record behind an append-only contract, not as a step anyone re-runs. An append to `golden-urls.txt` is only reviewable against the derivation that produced the original, which is why the derivation is here rather than lost with the platform. + +**They write into the capture and never into `checks/`.** The committed lists are grown by hand from a log finding, per that directory's own maintenance rules. A script that could rewrite them would be able to replace a verified contract with an inferior re-derivation. + +## Two properties of the maps that are easy to break + +**The Blogger map holds more entries than there are Blogger-era posts.** That platform truncated an auto-generated slug at a fixed length on a whole-word boundary, so a long title was served at the truncated address and that is the address in search indexes. The importer registered the full slug, both answer, and both are mapped. The limit is a named constant in `build-redirects.py`, and changing it changes how many entries the map has. + +**A term archive the old platform served is not always one Hugo builds.** Where it does not, the URL still has to answer, which is why the maps carry terms that no longer exist as pages. + +## What lived in the capture and is not carried + +Seven scripts stayed behind, and each is named here so nobody goes looking for something that was deliberately left. + +| In the capture | Did | Why it is not here | +| --- | --- | --- | +| `crawl/spider.sh` | enumerated every URL the live site served, politely and with an identifying user agent | A short flag list against a site that will be gone. Its output, the crawl log, is the durable artifact and is in the capture. | +| `crawl/mirror.sh` | took the offline snapshot, spanning the blog and the image hosts | Same, and its span-host list is recorded above because the orphan adjudication depends on it. | +| `inventory/fetch-at-risk.sh` | downloaded every hotlinked image with its size and SHA-256 | The manifest it wrote is the durable artifact. Re-verification reads the manifest and never re-fetches. | +| `inventory/fetch-missing.sh` | fetched library media the crawl did not reach | Same shape, same reason. | +| `inventory/fetch-unattached.sh` | fetched media listed in the export but never embedded in a post | Same shape, same reason. | +| `build-redirects.py` at the capture root | an older copy of the generator | **Stale.** Superseded by the copy here. | +| a second copy under the capture's own `checks/` | byte-identical to the one above | **Stale.** Superseded by the copy here. That directory belongs to the capture and is not this repository's `checks/`. | + +**The two stale copies are named by path on purpose**, so that finding one is not mistaken for finding a source. Neither has the fixes this copy carries. + +## Variables + +Every path and address is a variable, so nothing here names a machine. [`example.env`](../example.env) lists them and [`ENVIRONMENT.md`](../ENVIRONMENT.md) describes them. + +A required value that is unset stops the script and names what is missing, rather than falling back to something plausible. A wrong-but-valid capture directory produces empty maps that are indistinguishable from working ones until the redirects are live, which is the failure this rule exists for. + +`CAPTURE_SOURCE_URL` is the **old** platform. It holds the same string as `HUGO_BASEURL` after the cutover and means something different, so merging the two would point a verification run at the new site while every check still passed. + +## This directory is the source + +Edit the copy here and run it from here. A copy found in the capture is an artifact of when it ran, not a place to make a change. diff --git a/capture/build-golden.py b/capture/build-golden.py new file mode 100755 index 0000000..8cd0045 --- /dev/null +++ b/capture/build-golden.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 +"""Build the golden URL list: every URL the live WordPress site actually serves. + +Three sources, unioned, then every candidate verified against the live site: + + 1. The recursive crawl - finds linked pages, but misses anything unlinked. + 2. The sitemap - only 111 URLs, misses taxonomy terms entirely. + 3. Derivation - date archives and pagination are served but linked from nowhere, + so no crawl can find them. Computed from post dates and taxonomy post counts. + +Verification is what makes the list authoritative: a candidate is kept only if the +live site answers for it. The output is split by how Hugo must satisfy each URL: + + golden-urls.txt - must render as a page (200) + redirect-urls.txt - must redirect (301/308), or is a WordPress-ism with no Hugo + equivalent (attachment pages, per-post comment feeds) that we + choose to redirect to the parent post rather than reproduce. +""" + +import json +import math +import os +import re +import sys +import threading +import urllib.error +import urllib.request +from collections import Counter +from pathlib import Path +from queue import Queue + +def env(name: str) -> str: + """A required capture value, refused rather than guessed when unset. + + Duplicated across the scripts here rather than shared, because these get copied out to + a scratch directory to run, and an import would break the moment one travelled alone. + """ + v = os.environ.get(name, "") + if not v: + sys.exit(f"{name} is not set -- see example.env and ENVIRONMENT.md") + return v + + +BASE = env("CAPTURE_SOURCE_URL") +API = env("CAPTURE_SOURCE_API") +PER_PAGE = 10 # measured against the old platform: the post count paginated to /page/11/ +# The capture, never this script's directory. Both outputs below are capture artifacts and +# must not be able to land in the repository's checks/, whose lists are append-only and are +# grown by hand from a log finding rather than regenerated. +ROOT = Path(env("CAPTURE_ROOT")) +UA = {"User-Agent": "Mozilla/5.0 (compatible; blog-migration-audit/1.0)"} + + +def api(path): + req = urllib.request.Request(f"{API}/{path}", headers=UA) + with urllib.request.urlopen(req, timeout=30) as r: + return json.load(r) + + +def norm(p): + p = re.sub(r"^https?://[^/]+", "", p) + p = p.split("#")[0] + if not p.startswith("/"): + p = "/" + p + return p if p.endswith("/") else p + "/" + + +def pages_for(count): + """Pagination URLs beyond page 1 for an archive holding `count` posts.""" + return range(2, math.ceil(count / PER_PAGE) + 1) if count > PER_PAGE else [] + + +def build_candidates(): + cand = {"/"} + + # 1. Crawl + log = (ROOT / "crawl" / "spider.log").read_text(encoding="utf-8", errors="replace") + # Built from CAPTURE_SOURCE_URL rather than written in, so the pattern and the site the + # crawl actually ran against cannot drift apart. + crawled = {norm(u) for u in re.findall(re.escape(BASE) + r"[^\s]*", log)} + cand |= {u for u in crawled if not u.startswith("/wp-content/")} + print(f" crawl: {len(crawled)} paths") + + # 2. Sitemap + try: + req = urllib.request.Request(f"{BASE}/sitemap.xml", headers=UA) + with urllib.request.urlopen(req, timeout=30) as r: + sm = {norm(u) for u in re.findall(r"([^<]+)", r.read().decode())} + cand |= sm + print(f" sitemap: {len(sm)} URLs") + except Exception as e: # noqa: BLE001 - the sitemap is a nice-to-have source + print(f" sitemap: FAILED ({e})", file=sys.stderr) + + # 3. Derivation - the part no crawl can reach. + posts = json.loads((ROOT / "inventory" / "posts.json").read_text(encoding="utf-8")) + derived = set() + + ym = Counter() + for p in posts: + d = p.get("date", "") + if len(d) >= 7: + ym[(d[:4], d[5:7])] += 1 + years = Counter() + for (y, m), n in ym.items(): + derived.add(f"/{y}/{m}/") + years[y] += n + for i in pages_for(n): + derived.add(f"/{y}/{m}/page/{i}/") + for y, n in years.items(): + derived.add(f"/{y}/") + for i in pages_for(n): + derived.add(f"/{y}/page/{i}/") + + for i in pages_for(len(posts)): + derived.add(f"/page/{i}/") + + for kind, key, field in (("category", "categories", "categories"), ("tag", "tags", "tags")): + data = api(f"{field}?number=500")[key] + for t in data: + derived.add(f"/{kind}/{t['slug']}/") + for i in pages_for(t["post_count"]): + derived.add(f"/{kind}/{t['slug']}/page/{i}/") + + derived.add("/feed/") + cand |= derived + print(f" derived: {len(derived)} URLs (date archives + pagination, unlinked)") + return sorted(cand) + + +def verify(urls, workers=6): + """HEAD every candidate. Redirects are recorded, not followed.""" + out, q, lock = {}, Queue(), threading.Lock() + for u in urls: + q.put(u) + + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): + return None + + opener = urllib.request.build_opener(NoRedirect) + + def worker(): + while True: + try: + u = q.get_nowait() + except Exception: # noqa: BLE001 - empty queue ends the worker + return + code, loc = 0, "" + for _ in range(3): + try: + req = urllib.request.Request(BASE + u, headers=UA, method="HEAD") + with opener.open(req, timeout=25) as r: + code, loc = r.status, r.headers.get("Location", "") + break + except urllib.error.HTTPError as e: + code, loc = e.code, e.headers.get("Location", "") + break + except Exception: # noqa: BLE001 - transient, retry + continue + with lock: + out[u] = (code, loc) + if len(out) % 200 == 0: + print(f" verified {len(out)}/{len(urls)}", flush=True) + q.task_done() + + threads = [threading.Thread(target=worker, daemon=True) for _ in range(workers)] + for t in threads: + t.start() + for t in threads: + t.join() + return out + + +def main(): + print("Building candidate set:") + cand = build_candidates() + print(f" UNION: {len(cand)} candidates\n") + + print("Verifying against the live site:") + res = verify(cand) + + # An attachment page is /YYYY/MM/DD/post/attachment/ - a WordPress-ism with no Hugo + # equivalent. The image itself stays at its wp-content path; the page redirects home + # to its parent post. Per-post /feed/ endpoints get the same treatment. + attach = re.compile(r"^/\d{4}/\d{2}/\d{2}/[^/]+/[^/]+/$") + feed = re.compile(r"/feed/$") + + golden, redirect, dropped = [], [], [] + for u, (code, loc) in sorted(res.items()): + if code in (301, 302, 307, 308): + redirect.append((u, code, loc)) + elif code == 200: + (redirect if (attach.match(u) or (feed.search(u) and u != "/feed/")) else golden).append( + (u, code, "") + ) + else: + dropped.append((u, code, loc)) + + (ROOT / "checks").mkdir(exist_ok=True) + (ROOT / "checks" / "golden-urls.txt").write_text("".join(f"{u}\n" for u, _, _ in golden), encoding="utf-8") + (ROOT / "checks" / "redirect-urls.txt").write_text("".join(f"{u}\n" for u, _, _ in redirect), encoding="utf-8") + with (ROOT / "checks" / "url-verification.tsv").open("w", encoding="utf-8") as fh: + fh.write("class\tstatus\turl\tlocation\n") + for name, rows in (("golden", golden), ("redirect", redirect), ("dropped", dropped)): + for u, c, loc in rows: + fh.write(f"{name}\t{c}\t{u}\t{loc}\n") + + print(f"\n GOLDEN (must render): {len(golden)}") + print(f" REDIRECT: {len(redirect)}") + print(f" dropped (4xx/5xx/0): {len(dropped)}") + print("\n golden by shape:") + shape = Counter() + for u, _, _ in golden: + if u == "/": + shape["home"] += 1 + elif re.match(r"^/\d{4}/\d{2}/\d{2}/[^/]+/$", u): + shape["post"] += 1 + elif "/page/" in u: + shape["pagination"] += 1 + elif u.startswith("/tag/"): + shape["tag archive"] += 1 + elif u.startswith("/category/"): + shape["category archive"] += 1 + elif re.match(r"^/\d{4}/(\d{2}/)?$", u): + shape["date archive"] += 1 + else: + shape["page/other"] += 1 + for k, v in shape.most_common(): + print(f" {k:20} {v}") + if dropped: + print(f"\n sample dropped: {[u for u, _, _ in dropped[:5]]}") + + +if __name__ == "__main__": + main() diff --git a/checks/build-redirects.py b/capture/build-redirects.py similarity index 78% rename from checks/build-redirects.py rename to capture/build-redirects.py index 3d94171..fa7eb25 100755 --- a/checks/build-redirects.py +++ b/capture/build-redirects.py @@ -2,9 +2,14 @@ """Generate the Caddy redirect maps from the WordPress export. Reads the export and the capture inventory, which live outside this repo, and writes the -committed maps under deploy/maps/. See OPERATIONS.md for when to run it. +committed maps under deploy/maps/. See capture/README.md for when to run it. + +The capture directory comes from CAPTURE_ROOT, and a first argument wins over it. This +generates rather than gates, which is why it sits in capture/ beside the other scripts +that read the capture rather than in checks/ beside the gates. """ +import os import pathlib import re import sys @@ -12,7 +17,11 @@ NS = {"wp": "http://wordpress.org/export/1.2/"} -CHECKS = pathlib.Path(__file__).resolve().parent +# Anchored on the repository rather than on this file's own directory, because the two +# lists below live in checks/ and the maps in deploy/maps/, and neither follows this +# script if it moves again. +REPO = pathlib.Path(__file__).resolve().parent.parent +CHECKS = REPO / "checks" # Blogger truncates an auto-generated slug at this many characters, on a whole-word boundary. # For a longer slug the truncated form is the URL Blogger served, and so the one in search indexes. @@ -52,17 +61,40 @@ def blogger_truncate(slug, limit=BLOGGER_SLUG_LIMIT): def write_map(path, pairs): path.parent.mkdir(parents=True, exist_ok=True) - path.write_text("".join(f"{k} {v}\n" for k, v in pairs)) + path.write_text("".join(f"{k} {v}\n" for k, v in pairs), encoding="utf-8") return len(pairs) def main(argv): - if len(argv) != 2: - print(__doc__.strip().splitlines()[0], file=sys.stderr) - print(f"usage: {argv[0]} ", file=sys.stderr) + # CAPTURE_ROOT is the default and an argument wins over it, the same shape DEPLOY_ROOT + # uses. Unset and unsupplied is refused rather than guessed: a wrong-but-plausible + # capture yields maps that are empty and indistinguishable from working ones. + # --print-export names the selected export and writes nothing. run-wp2hugo.sh calls it + # rather than reimplementing the choice, so the conversion and the maps are provably + # built from the same file. A shell reimplementation cannot match this anyway: the test + # is that ONE item carries both post_type=post and status=publish, and two greps over a + # whole file would accept a media-only export that happens to contain both words. + args = [a for a in argv[1:] if a != "--print-export"] + print_export = "--print-export" in argv[1:] + # An unknown option is refused rather than taken as a path. Without this, `--help` is + # read as a capture directory and the run fails with "no export XML found under --help", + # which sends the reader looking for a missing file rather than a mistyped flag. + unknown = [a for a in args if a.startswith("-")] + if unknown: + print(f"unknown option: {unknown[0]}", file=sys.stderr) + print(f"usage: {argv[0]} [--print-export] [capture-dir]", file=sys.stderr) + return 2 + if len(args) > 1: + print(f"usage: {argv[0]} [--print-export] [capture-dir]", file=sys.stderr) + return 2 + root = args[0] if args else os.environ.get("CAPTURE_ROOT", "") + if not root: + print(f"usage: {argv[0]} [--print-export] [capture-dir]", file=sys.stderr) + print("CAPTURE_ROOT is not set and no capture directory was given", file=sys.stderr) + print("see example.env and ENVIRONMENT.md", file=sys.stderr) return 2 - capture = pathlib.Path(argv[1]) - out = pathlib.Path(__file__).resolve().parent.parent / "deploy" / "maps" + capture = pathlib.Path(root) + out = REPO / "deploy" / "maps" # An account holds several exports, and a media-only one carries the attachments but no posts. # Filesystem order decides which a glob returns, and the wrong one yields empty maps that look valid. @@ -84,6 +116,9 @@ def main(argv): print(f" {path}", file=sys.stderr) return 1 src, root = with_posts[0] + if print_export: + print(src) + return 0 print(f"export: {src}") posts, attachments, blogger, terms = {}, [], [], [] @@ -129,7 +164,7 @@ def main(argv): # Reading the render list also resolves a slug that exists as both a tag and a category. # Map lookups are case-sensitive, so each slug is emitted alongside a capitalized variant. rendered = set() - for line in (CHECKS / "golden-urls.txt").read_text().splitlines(): + for line in (CHECKS / "golden-urls.txt").read_text(encoding="utf-8").splitlines(): if m := re.match(r"^/(tag|category)/([^/]+)/$", line.strip()): rendered.add((m.group(2), m.group(1))) destinations = {} @@ -166,7 +201,7 @@ def main(argv): r"|^/p/[^/]+\.html$" # Blogger static pages ) # The repo's list, not the capture's, which is a frozen snapshot from before the contract grew. - redirects = (CHECKS / "redirect-urls.txt").read_text().splitlines() + redirects = (CHECKS / "redirect-urls.txt").read_text(encoding="utf-8").splitlines() needed = [u for u in (line.strip() for line in redirects) if u and u.count("/") == 2 and not covered.match(u)] # Attachments with a real post_parent resolve directly. @@ -178,7 +213,7 @@ def main(argv): file_to_post = {} inv = capture / "inventory" / "media-urls.tsv" if inv.exists(): - for line in inv.read_text().splitlines()[1:]: + for line in inv.read_text(encoding="utf-8").splitlines()[1:]: parts = line.split("\t") if len(parts) >= 4: stem = pathlib.PurePosixPath(parts[1].split("?")[0]).stem.lower() diff --git a/capture/classify.py b/capture/classify.py new file mode 100755 index 0000000..0c52eba --- /dev/null +++ b/capture/classify.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Split the verified URL set into what Hugo must render and what must redirect. + +Reads the cached verification results so this can be re-run without re-hitting the +live site. The discriminator that matters: WordPress serves an attachment page for +every uploaded image, at BOTH /YYYY/MM/DD/post/attachment/ and a bare /attachment/. +A bare one-segment URL is therefore ambiguous with a real page, and the sitemap is +the authority - it lists exactly the posts and pages, so a one-segment URL absent +from it is an attachment page, not content. +""" + +import os +import re +import sys +import urllib.request +from collections import Counter +from pathlib import Path + + + +def env(name: str) -> str: + """A required capture value, refused rather than guessed when unset. + + Duplicated across the scripts here rather than shared, because these get copied out to + a scratch directory to run, and an import would break the moment one travelled alone. + """ + v = os.environ.get(name, "") + if not v: + sys.exit(f"{name} is not set -- see example.env and ENVIRONMENT.md") + return v + + +# The capture, never this script's directory. Both outputs below are capture artifacts and +# must not be able to land in the repository's checks/, whose lists are append-only. +ROOT = Path(env("CAPTURE_ROOT")) +BASE = env("CAPTURE_SOURCE_URL") +UA = {"User-Agent": "Mozilla/5.0 (compatible; blog-migration-audit/1.0)"} + +req = urllib.request.Request(f"{BASE}/sitemap.xml", headers=UA) +with urllib.request.urlopen(req, timeout=30) as r: + sitemap = { + re.sub(r"^https?://[^/]+", "", u).rstrip("/") + "/" + for u in re.findall(r"([^<]+)", r.read().decode()) + } + +rows = [ + line.rstrip("\n").split("\t") + for line in (ROOT / "checks" / "url-verification.tsv").read_text(encoding="utf-8").splitlines()[1:] +] +status = {r[2]: (int(r[1]), r[3] if len(r) > 3 else "") for r in rows} + +# The author archive and its pagination are served but linked from nowhere, and on a +# single-author blog they duplicate the home archive exactly. Verified live: /page/11/ +# is the last one. +# +# Optional, and skipped loudly rather than silently. An account slug is not this +# repository's to carry, and a run without it produces a list short by the author URLs +# rather than a wrong one. Silence would be indistinguishable from a site that never +# served them. +AUTHOR_SLUG = os.environ.get("CAPTURE_AUTHOR_SLUG", "") +if AUTHOR_SLUG: + for i in range(2, 12): + status.setdefault(f"/author/{AUTHOR_SLUG}/page/{i}/", (200, "")) + status.setdefault(f"/author/{AUTHOR_SLUG}/", (200, "")) +else: + print("CAPTURE_AUTHOR_SLUG is not set: skipping the author archive backfill", file=sys.stderr) + +POST = re.compile(r"^/\d{4}/\d{2}/\d{2}/[^/]+/$") +NESTED_ATTACH = re.compile(r"^/\d{4}/\d{2}/\d{2}/[^/]+/[^/]+/$") +DATE = re.compile(r"^/\d{4}/(\d{2}/)?$") +DATE_PAGED = re.compile(r"^/\d{4}/(\d{2}/)?page/\d+/$") +HOME_PAGED = re.compile(r"^/page/\d+/$") +TERM = re.compile(r"^/(tag|category)/[^/]+/(page/\d+/)?$") +AUTHOR = re.compile(r"^/author/[^/]+/(page/\d+/)?$") + +golden, redirect, dropped = [], [], [] +reason = Counter() + +for url, (code, _loc) in sorted(status.items()): + if code not in (200, 301, 302, 307, 308): + dropped.append(url) + continue + if code != 200: + redirect.append(url) + reason["already a redirect on WordPress"] += 1 + elif NESTED_ATTACH.match(url): + redirect.append(url) + reason["attachment page (nested)"] += 1 + elif url.endswith("/feed/") and url != "/feed/": + redirect.append(url) + reason["per-post or per-term feed"] += 1 + elif url == "/feed/": + redirect.append(url) + reason["site feed -> /index.xml"] += 1 + elif AUTHOR.match(url): + redirect.append(url) + reason["author archive (single author, duplicates home)"] += 1 + elif DATE.match(url) or DATE_PAGED.match(url): + # Decision (2026-07-29): Hugo has no built-in year/month archive, and these are + # absent from the sitemap and linked from nowhere on the live site. Building them + # would be the only custom templating in the migration, for URLs nothing points at. + # One Caddy pattern rule sends them home instead. + redirect.append(url) + reason["date archive -> / (no Hugo equivalent, unlinked)"] += 1 + elif POST.match(url) or HOME_PAGED.match(url) or TERM.match(url) or url == "/": + golden.append(url) + elif url.rstrip("/").count("/") == 1: + # One segment: a real page if the sitemap lists it, otherwise an attachment. + if url in sitemap: + golden.append(url) + else: + redirect.append(url) + reason["attachment page (root level)"] += 1 + else: + golden.append(url) + +(ROOT / "checks" / "golden-urls.txt").write_text("".join(f"{u}\n" for u in sorted(golden)), encoding="utf-8") +(ROOT / "checks" / "redirect-urls.txt").write_text("".join(f"{u}\n" for u in sorted(redirect)), encoding="utf-8") + +shape = Counter() +for u in golden: + if u == "/": + shape["home"] += 1 + elif POST.match(u): + shape["post"] += 1 + elif TERM.match(u) and "/page/" in u: + shape["taxonomy pagination"] += 1 + elif u.startswith("/tag/"): + shape["tag archive"] += 1 + elif u.startswith("/category/"): + shape["category archive"] += 1 + elif DATE.match(u): + shape["date archive"] += 1 + elif DATE_PAGED.match(u) or HOME_PAGED.match(u): + shape["date/home pagination"] += 1 + else: + shape["page"] += 1 + +print(f"GOLDEN (Hugo must render): {len(golden)}") +for k, v in shape.most_common(): + print(f" {k:24} {v}") +print(f"\nREDIRECT: {len(redirect)}") +for k, v in reason.most_common(): + print(f" {k:46} {v}") +print(f"\ndropped (4xx): {len(dropped)}") diff --git a/capture/clean-content.py b/capture/clean-content.py new file mode 100755 index 0000000..a20205d --- /dev/null +++ b/capture/clean-content.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Reduce the converted site to content only. + +Two jobs, both decided deliberately: + +1. **Drop comments entirely.** The blog is read-only going forward - no comments, no + interaction. Deleting the data file rather than scrubbing it means there is no PII + question at all, no partial to write, and nothing to carry. + +2. **Strip front matter to what actually drives the site.** wp2hugo carries every + WordPress custom field through, which is 156 distinct keys across 108 posts, 127 of + them WordPress internals (`_edit_last`, `_oembed_`, `_jetpack_*`, `_coblocks_*`, + `_publicize_*`). None of it is content. + +Kept, with the reason each earns its place: + + title required + date required, drives the permalink and ordering + url the exact WordPress permalink - keeping it guarantees URL preservation + independent of any hugo.yaml permalink config + categories taxonomy, 12 terms + tags taxonomy, 183 terms + post_id drives the ?p= shortlink redirect map - inbound-link surface + cover featured image, {alt, image}, on 33 posts + +Dropped on purpose: `author` (single-author blog, the site knows), `guid` (GUID +preservation was dropped, and wp2hugo rewrote the scheme to https anyway, which would +have broken RSS), `parent_post_id` (null on every post), `blogger_*` (provenance from an +earlier Blogger migration), `publicize_*` (dead social-share links), `geo_*` (no template +consumes it), and every `_`-prefixed WordPress internal. +""" + +import os +import re +import shutil +import sys +import pathlib +from pathlib import Path + +try: + import yaml +except ModuleNotFoundError: # the only third-party import in capture/ or checks/ + sys.exit("PyYAML is required by this script: pip install PyYAML (Debian: apt install python3-yaml)") + +KEEP = ["title", "date", "url", "categories", "tags", "post_id", "cover"] +FM = re.compile(r"^---\n(.*?)\n---\n(.*)$", re.S) + + +def capture_root() -> pathlib.Path: + """CAPTURE_ROOT, refused rather than guessed when unset. + + Duplicated in each script here rather than shared, because these get copied out to a + scratch directory to run against a copy of the capture, and an import would break the + moment one of them travelled alone. + """ + root = os.environ.get("CAPTURE_ROOT", "") + if not root: + sys.exit("CAPTURE_ROOT is not set -- see example.env and ENVIRONMENT.md") + return pathlib.Path(root) + + +def converted_site(argv) -> pathlib.Path: + """The converted site: a first argument, else the one generated-* under the capture. + + Ambiguity aborts rather than picking, the same rule build-redirects.py applies to the + export. wp2hugo stamps the directory with a run timestamp, so there is no fixed name + to default to and a glob that matched two would otherwise choose by filesystem order. + """ + if len(argv) > 1 and not argv[1].startswith("--"): + return pathlib.Path(argv[1]) + found = sorted((capture_root() / "converted").glob("generated-*")) + if len(found) != 1: + sys.exit( + f"expected exactly one converted site under {capture_root()}/converted, found {len(found)}" + + "".join(f"\n {p}" for p in found) + + "\npass one as the first argument" + ) + return found[0] + + +def main(root: Path, apply: bool): + stats = {"files": 0, "keys_before": 0, "keys_after": 0, "no_title": []} + + data = root / "data" + if data.exists(): + n = sorted(p.name for p in data.iterdir()) + print(f"data/ to delete: {n}") + if apply: + shutil.rmtree(data) + + for p in sorted(root.joinpath("content").rglob("*.md")): + raw = p.read_text(encoding="utf-8") + m = FM.match(raw) + if not m: + continue + fm = yaml.safe_load(m.group(1)) or {} + body = m.group(2) + stats["files"] += 1 + stats["keys_before"] += len(fm) + + out = {k: fm[k] for k in KEEP if k in fm and fm[k] not in (None, "", [])} + if not out.get("title"): + # Recover a title from the slug rather than shipping an untitled page. + slug = p.parent.name if p.name == "index.md" else p.stem + out["title"] = slug.replace("-", " ").title() + out = {"title": out["title"], **{k: v for k, v in out.items() if k != "title"}} + stats["no_title"].append(f"{p.relative_to(root)} -> {out['title']!r}") + stats["keys_after"] += len(out) + + # sort_keys=False preserves the KEEP order, which reads better than alphabetical. + new = "---\n" + yaml.dump(out, sort_keys=False, allow_unicode=True, width=10**6) + "---\n" + body + if apply: + p.write_text(new, encoding="utf-8") + + print(f"\nfiles processed : {stats['files']}") + print(f"front-matter keys: {stats['keys_before']} -> {stats['keys_after']}" + f" ({stats['keys_before'] - stats['keys_after']} removed)") + if stats["no_title"]: + print(f"\ntitle recovered from slug ({len(stats['no_title'])}):") + for t in stats["no_title"]: + print(" ", t) + print("\nAPPLIED" if apply else "\nDRY RUN - pass --apply to write") + + +if __name__ == "__main__": + main(converted_site(sys.argv), "--apply" in sys.argv) diff --git a/capture/enumerate-media.py b/capture/enumerate-media.py new file mode 100755 index 0000000..f62adbe --- /dev/null +++ b/capture/enumerate-media.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +"""Enumerate every media URL referenced by the live WordPress.com site. + +Pulls all posts and pages from the old platform's REST API, named by CAPTURE_SOURCE_API, +and extracts +every media reference from the rendered HTML. The rendered form is deliberate: +shortcodes are already expanded, so this sees what a reader's browser sees. + +The critical output is the by-host breakdown. Media on the wp.com subdomain is in +the media library and will appear in the WXR export; media on lh*.ggpht.com and +googleusercontent.com is hotlinked from the Windows Live Writer era, is NOT in the +library, and will NOT be in the export. That subset is the migration's biggest +silent-data-loss risk, so it gets enumerated explicitly. + +Writes: media-urls.tsv (host, url, post_id, post_url), posts.json (raw archive). +""" + +import json +import os +import re +import sys +import urllib.parse +import urllib.request +from collections import Counter, defaultdict +from pathlib import Path + +def env(name: str) -> str: + """A required capture value, refused rather than guessed when unset. + + Duplicated across the scripts here rather than shared, because these get copied out to + a scratch directory to run, and an import would break the moment one travelled alone. + """ + v = os.environ.get(name, "") + if not v: + sys.exit(f"{name} is not set -- see example.env and ENVIRONMENT.md") + return v + + +API = env("CAPTURE_SOURCE_API") +# Written into the capture, never beside this script. Anchoring on __file__ would put the +# inventory inside the repository the moment this file moved into it, which it now has. +OUT = Path(env("CAPTURE_ROOT")) / "inventory" + +# src/href targets that are media rather than navigation. +MEDIA_EXT = re.compile( + r"\.(?:jpe?g|png|gif|webp|avif|svg|ico|bmp|tiff?|mp4|m4v|mov|webm|mp3|m4a|wav|ogg|pdf|zip|7z|txt|csv|xlsx?|docx?)" + r"(?:[?#]|$)", + re.IGNORECASE, +) +# Attributes that can carry a media URL, including responsive-image sets. +ATTR = re.compile(r"""(?:src|href|data-orig-file|data-large-file|data-medium-file|poster)\s*=\s*["']([^"']+)["']""", re.I) +SRCSET = re.compile(r"""srcset\s*=\s*["']([^"']+)["']""", re.I) + + +def fetch(url): + req = urllib.request.Request(url, headers={"User-Agent": "blog-migration-audit/1.0"}) + with urllib.request.urlopen(req, timeout=30) as r: + return json.load(r) + + +def all_items(kind, extra=""): + """Page through a collection until exhausted. + + Pages go through here too, with type=page, rather than a single number=100 request. + That request was correct for this site and silently wrong for any site with more than + a hundred pages, which is the shape of loss this whole capture exists to catch. + """ + items, page = [], 1 + while True: + data = fetch(f"{API}/{kind}/?number=100&page={page}{extra}&fields=ID,URL,slug,title,date,content") + found = data.get("posts", []) + if not found: + break + items.extend(found) + if len(items) >= data.get("found", 0): + break + page += 1 + return items + + +def extract(html): + urls = set() + for m in ATTR.finditer(html or ""): + urls.add(m.group(1).strip()) + for m in SRCSET.finditer(html or ""): + for candidate in m.group(1).split(","): + part = candidate.strip().split() + if part: + urls.add(part[0]) + return {u for u in urls if MEDIA_EXT.search(u)} + + +def main(): + posts = all_items("posts") + pages = all_items("posts", extra="&type=page") + everything = posts + pages + print(f"fetched {len(posts)} posts + {len(pages)} pages", file=sys.stderr) + + OUT.mkdir(parents=True, exist_ok=True) + (OUT / "posts.json").write_text(json.dumps(everything, indent=1), encoding="utf-8") + + rows, by_host, per_post = [], Counter(), defaultdict(set) + for item in everything: + for u in extract(item.get("content", "")): + absolute = urllib.parse.urljoin(item["URL"], u) + host = urllib.parse.urlparse(absolute).netloc.lower() + by_host[host] += 1 + per_post[item["ID"]].add(absolute) + rows.append((host, absolute, str(item["ID"]), item["URL"])) + + with (OUT / "media-urls.tsv").open("w", encoding="utf-8") as fh: + fh.write("host\turl\tpost_id\tpost_url\n") + for row in sorted(set(rows)): + fh.write("\t".join(row) + "\n") + + unique = {r[1] for r in rows} + print(f"\n{len(rows)} media references, {len(unique)} unique URLs\n") + print(f"{'host':45} refs") + for host, n in by_host.most_common(): + print(f"{host:45} {n}") + + # The at-risk subset, called out explicitly. + risky = sorted(u for u in unique if re.search(r"(ggpht|googleusercontent)\.com", u)) + (OUT / "media-external-hotlinked.txt").write_text("\n".join(risky) + "\n", encoding="utf-8") + print(f"\nNOT in the media library (absent from any WXR export): {len(risky)} unique URLs") + print(" -> inventory/media-external-hotlinked.txt") + + +if __name__ == "__main__": + main() diff --git a/capture/localize-external.py b/capture/localize-external.py new file mode 100755 index 0000000..bfc8f12 --- /dev/null +++ b/capture/localize-external.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Download every externally-hosted image and rewrite the content to point at local copies. + +wp2hugo skips these entirely ("non-relative link (skipped for download)"), and they are +absent from the WordPress export too, because they were never in the media library - they +are hotlinks from the Windows Live Writer and Blogger era. If they are not localized they +remain a permanent dependency on Google serving 15-year-old URLs. + +Two traps this handles, both of which return HTTP 200 and look like success: + +1. **The `-h` wrapper.** A Picasa/ggpht URL whose size segment ends in `-h` (`/s1600-h/`) + serves an HTML *page* containing an `` tag, not the image. Fetching it naively + yields a 400-byte HTML file with a 200 status. The fix is to parse the wrapper and + follow the `` it names, which is Google's own answer rather than a guess. +2. **Non-image bodies generally.** Anything whose magic bytes are not an image is a + failure regardless of status code, and is reported rather than written. + +Writes images to static/external/ named by a hash of the source URL (these URLs carry +percent-encoded brackets and other characters that do not survive a filesystem), records +the mapping in external-media-map.tsv for auditability, and rewrites every reference. +""" + +import hashlib +import pathlib +import os +import re +import sys +import urllib.error +import urllib.request +from collections import Counter + +UA = {"User-Agent": "Mozilla/5.0 (compatible; blog-migration-audit/1.0)"} +EXT_HOST = re.compile(r"^https?://[a-z0-9.-]*\.(?:ggpht|googleusercontent)\.com/", re.I) +URL_IN_CONTENT = re.compile(r"https?://[a-z0-9.-]*\.(?:ggpht|googleusercontent)\.com/[^\s\"'\)\]<>]+", re.I) +IMG_IN_WRAPPER = re.compile(rb' pathlib.Path: + """CAPTURE_ROOT, refused rather than guessed when unset. + + Duplicated in each script here rather than shared, because these get copied out to a + scratch directory to run against a copy of the capture, and an import would break the + moment one of them travelled alone. + """ + root = os.environ.get("CAPTURE_ROOT", "") + if not root: + sys.exit("CAPTURE_ROOT is not set -- see example.env and ENVIRONMENT.md") + return pathlib.Path(root) + + +def converted_site(argv) -> pathlib.Path: + """The converted site: a first argument, else the one generated-* under the capture. + + Ambiguity aborts rather than picking, the same rule build-redirects.py applies to the + export. wp2hugo stamps the directory with a run timestamp, so there is no fixed name + to default to and a glob that matched two would otherwise choose by filesystem order. + """ + if len(argv) > 1 and not argv[1].startswith("--"): + return pathlib.Path(argv[1]) + found = sorted((capture_root() / "converted").glob("generated-*")) + if len(found) != 1: + sys.exit( + f"expected exactly one converted site under {capture_root()}/converted, found {len(found)}" + + "".join(f"\n {p}" for p in found) + + "\npass one as the first argument" + ) + return found[0] + + +def sniff(data: bytes): + for sig, ext in MAGIC: + if data.startswith(sig): + return ext + if data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return ".webp" + return None + + +def fetch(url: str, depth: int = 0): + """Return (bytes, ext) or (None, reason). Follows one level of `-h` HTML wrapper.""" + try: + req = urllib.request.Request(url, headers=UA) + with urllib.request.urlopen(req, timeout=45) as r: + body = r.read() + except urllib.error.HTTPError as e: + return None, f"HTTP {e.code}" + except Exception as e: # noqa: BLE001 - network is the expected failure here + return None, type(e).__name__ + + ext = sniff(body) + if ext: + return body, ext + + # Not an image. If it is Google's `-h` wrapper page, it names the real image. + # A wrapper page is HTML, and HTML does not reliably start with . A doctype, a + # comment or leading whitespace are all ordinary, and requiring the tag meant a wrapper + # that opened with was reported as "not an image" rather than followed. + head = body.lstrip()[:64].lower() + if depth == 0 and (head.startswith(b" /2024/05/29/slug/ + +The `url:` front matter is the authority, not the `date:` field - it is WordPress's own +permalink, and the two can legitimately disagree if a post was ever re-dated. + +Standalone pages move to the content root, which is Hugo's idiomatic place for them: + + content/pages/2012/07/about/index.md -> content/about.md -> /about/ + +They were nested under a date only because wp2hugo's date-folder option applies to pages +as well as posts, which is meaningless for a page. A `content/pages/` section would also +make Hugo publish a `/pages/` listing URL, the same unwanted extra as `/posts/`. +""" + +import collections +import os +import pathlib +import re +import shutil +import sys + +FM = re.compile(r"^---\n(.*?)\n---\n", re.S) +URL = re.compile(r"^url:\s*(\S+)\s*$", re.M) +DATED = re.compile(r"^/(\d{4})/(\d{2})/(\d{2})/([^/]+)/$") + + +def capture_root() -> pathlib.Path: + """CAPTURE_ROOT, refused rather than guessed when unset. + + Duplicated in each script here rather than shared, because these get copied out to a + scratch directory to run against a copy of the capture, and an import would break the + moment one of them travelled alone. + """ + root = os.environ.get("CAPTURE_ROOT", "") + if not root: + sys.exit("CAPTURE_ROOT is not set -- see example.env and ENVIRONMENT.md") + return pathlib.Path(root) + + +def converted_site(argv) -> pathlib.Path: + """The converted site: a first argument, else the one generated-* under the capture. + + Ambiguity aborts rather than picking, the same rule build-redirects.py applies to the + export. wp2hugo stamps the directory with a run timestamp, so there is no fixed name + to default to and a glob that matched two would otherwise choose by filesystem order. + """ + if len(argv) > 1 and not argv[1].startswith("--"): + return pathlib.Path(argv[1]) + found = sorted((capture_root() / "converted").glob("generated-*")) + if len(found) != 1: + sys.exit( + f"expected exactly one converted site under {capture_root()}/converted, found {len(found)}" + + "".join(f"\n {p}" for p in found) + + "\npass one as the first argument" + ) + return found[0] + + +def url_of(p: pathlib.Path): + m = FM.match(p.read_text(encoding="utf-8")) + if not m: + return None + u = URL.search(m.group(1)) + return u.group(1).strip().strip("\"'") if u else None + + +def main(site: pathlib.Path, apply: bool): + content = site / "content" + moves, problems = [], [] + + # --- posts: content/posts///.md -> content/posts////.md + for p in sorted((content / "posts").rglob("*.md")): + # A section index is Hugo structure rather than a post. It carries no url: because + # it is not served, and treating it as unplaceable would make a healthy tree fail. + if p.name.startswith("_index."): + continue + u = url_of(p) + if not u: + problems.append((p, "no url: front matter")) + continue + m = DATED.match(u) + if not m: + problems.append((p, f"url not /Y/M/D/slug/: {u}")) + continue + y, mo, d, slug = m.groups() + dest = content / "posts" / y / mo / d / f"{slug}.md" + if dest != p: + moves.append((p, dest)) + + # --- pages: anywhere under content/pages -> content/.md + for p in sorted((content / "pages").rglob("*.md")): + u = url_of(p) + if not u: + problems.append((p, "no url: front matter")) + continue + slug = u.strip("/").split("/")[-1] + moves.append((p, content / f"{slug}.md")) + + print(f"posts and pages to relocate: {len(moves)}") + for src, dst in moves[:4]: + print(f" {src.relative_to(content)}\n -> {dst.relative_to(content)}") + if problems: + print(f"\nPROBLEMS ({len(problems)}):") + for p, why in problems: + print(f" {p.relative_to(content)}: {why}") + + # shutil.move replaces an existing destination without a word, and this applies moves in + # bulk, so a collision would destroy a post and report success. Two ways it can happen: + # two sources resolving to one destination, which flattening pages to content/.md + # makes possible, and a destination that already exists from a half-finished earlier run. + # Both are refused before anything moves, rather than discovered half way through. + collisions = collections.Counter(dst for _, dst in moves) + clashes = sorted(d for d, n in collisions.items() if n > 1) + occupied = sorted(dst for src, dst in moves if dst.exists() and dst != src) + if clashes or occupied: + print(f"\nREFUSING TO MOVE ({len(clashes)} collisions, {len(occupied)} occupied destinations):") + for d in clashes: + print(f" {d.relative_to(content)} <- {sum(1 for _, x in moves if x == d)} sources") + for d in occupied: + print(f" {d.relative_to(content)} already exists") + return 1 + + if apply: + for src, dst in moves: + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(src), str(dst)) + # Remove directories left empty by the move. + for _ in range(6): + for d in sorted(content.rglob("*"), key=lambda x: -len(x.parts)): + if d.is_dir() and not any(d.iterdir()): + d.rmdir() + print("\nAPPLIED") + else: + print("\nDRY RUN - pass --apply") + + # A problem is a file this cannot place: no url: front matter, or a url that is not the + # dated shape. The valid moves still happen, because leaving them undone helps nobody, + # but the run is incomplete and must not report success. Contrast clean-content.py, + # whose recovered titles are a repair rather than a skip and correctly exit zero. + if problems: + print(f"{len(problems)} file(s) could not be placed, listed above") + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main(converted_site(sys.argv), "--apply" in sys.argv)) diff --git a/capture/run-wp2hugo.sh b/capture/run-wp2hugo.sh new file mode 100755 index 0000000..175c4b6 --- /dev/null +++ b/capture/run-wp2hugo.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Convert the WordPress export to Hugo. Media is downloaded here because that is what +# drives absolute->relative URL rewriting, but the bytes are replaced afterwards from the +# official media tar - WordPress.com serves optimized derivatives over HTTP for some +# images, one of them at a fraction of the original's dimensions. +# +# The export is chosen by build-redirects.py --print-export rather than by a glob here, so +# the conversion and the redirect maps are provably built from the same file. An account +# holds several exports and a media-only one carries the attachments and no posts, and +# converting that one yields a site that builds and is empty. The selection cannot be +# reimplemented in shell: the test is that ONE item carries both post_type=post and +# status=publish, where two greps over a whole file would accept the media-only export. +set -Eeuo pipefail + +# A `go install`ed wp2hugo lands here. $HOME rather than a literal path. +export PATH="$HOME/.local/bin:$PATH" + +: "${CAPTURE_ROOT:?CAPTURE_ROOT is not set -- see example.env and ENVIRONMENT.md}" +[ -d "$CAPTURE_ROOT" ] || { + echo "CAPTURE_ROOT is not a directory: $CAPTURE_ROOT" >&2 + exit 1 +} +# Resolved to absolute before anything else, because this script cd's into it and the +# export path is worked out beforehand. A relative CAPTURE_ROOT would yield a relative +# export path that stops resolving the moment the cd happens, which reads as a missing +# export rather than as a path problem. +CAPTURE_ROOT="$(cd "$CAPTURE_ROOT" && pwd)" +export CAPTURE_ROOT + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +export_xml="$("$here/build-redirects.py" --print-export)" +echo "==> export: $export_xml" + +cd "$CAPTURE_ROOT" +wp2hugo \ + --source "$export_xml" \ + --output converted \ + --download-media \ + --download-all \ + --continue-on-media-download-error \ + --content-date-folder-structure year-month \ + --color-log-output=false +echo "WP2HUGO-EXIT-OK" diff --git a/checks/README.md b/checks/README.md index c86ebb0..1b30119 100644 --- a/checks/README.md +++ b/checks/README.md @@ -54,17 +54,15 @@ An **attachment page** is the page the old platform generated per uploaded image ## Legacy URL shapes worth knowing -Two properties of the maps are non-obvious and easy to break when regenerating them. - -**`blogger.map` carries 59 entries for 48 posts.** Blogger truncated an auto-generated slug at 40 characters on a whole-word boundary, so for the 11 posts with a longer slug the URL actually served, and therefore the one in search indexes and in other people's links, is the truncated form. Both forms are live redirects. A map holding only the full slug keeps the URL that never existed and drops the one that did. - **`/search/label/