diff --git a/.github/actions/build-base/action.yml b/.github/actions/build-base/action.yml new file mode 100644 index 00000000..b344c463 --- /dev/null +++ b/.github/actions/build-base/action.yml @@ -0,0 +1,41 @@ +name: Build the website at another commit +description: > + Checks out and builds a specified version of this repository. Useful for build comparisons with + newer repo versions. If it doesn't build, or has no build-site, there's no site at the "site" output. + +inputs: + ref: + description: The commit to build, such as a pull request's base commit. + required: true + drafts: + description: Include scheduled posts (draft = true). + default: 'false' + +outputs: + site: + description: The built site, relative to the workspace. + value: base/public + +runs: + using: composite + steps: + - name: Check out the commit + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + ref: ${{ inputs.ref }} + path: base + + - name: Build + id: build + if: hashFiles('base/.github/actions/build-site/action.yml') != '' + continue-on-error: true + uses: ./base/.github/actions/build-site + with: + path: base + drafts: ${{ inputs.drafts }} + + # A failed build can leave part of a site behind. + - name: Discard a failed build + if: steps.build.outcome == 'failure' + shell: bash + run: sudo rm -rf base/public diff --git a/.github/actions/build-site/action.yml b/.github/actions/build-site/action.yml index 553ca5d5..e7fac495 100644 --- a/.github/actions/build-site/action.yml +++ b/.github/actions/build-site/action.yml @@ -1,50 +1,51 @@ name: Build the website description: > - Builds a checkout of this repository into /public, with its topics and + Builds a checkout of this repository and its search index into /public, with its topics and commands from valkey-doc and the command metadata from valkey and the modules, checked out - next to it in the workspace. + next to it in the workspace. Content repositories that are already checked out there, such as by + an earlier build in the job, are reused. inputs: path: description: The website checkout to build, relative to the workspace (e.g. website). required: true - checkout-content: - description: Check out the content repositories. Set to false if an earlier build in the job already did. - default: 'true' + drafts: + description: Include scheduled posts (draft = true). Only for checks, since deploying it would publish them early. + default: 'false' runs: using: composite steps: - name: Checkout valkey - if: inputs.checkout-content == 'true' + if: hashFiles('valkey/.git/HEAD') == '' uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: repository: valkey-io/valkey path: valkey - name: Checkout valkey-bloom - if: inputs.checkout-content == 'true' + if: hashFiles('valkey-bloom/.git/HEAD') == '' uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: repository: valkey-io/valkey-bloom path: valkey-bloom - name: Checkout valkey-doc - if: inputs.checkout-content == 'true' + if: hashFiles('valkey-doc/.git/HEAD') == '' uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: repository: valkey-io/valkey-doc path: valkey-doc - name: Checkout valkey-json - if: inputs.checkout-content == 'true' + if: hashFiles('valkey-json/.git/HEAD') == '' uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: repository: valkey-io/valkey-json path: valkey-json - name: Checkout valkey-search - if: inputs.checkout-content == 'true' + if: hashFiles('valkey-search/.git/HEAD') == '' uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: repository: valkey-io/valkey-search @@ -65,3 +66,23 @@ runs: BUILD_DIR: ${{ inputs.path }} BUILD_ONLY: true BUILD_THEMES: false + BUILD_FLAGS: ${{ inputs.drafts == 'true' && '--drafts' || '' }} + + - name: Install Pagefind + shell: bash + env: + PAGEFIND_VERSION: v1.5.2 + PAGEFIND_SHA256: afb824a9e7f64905a934900481cea5be679c03975e527329e0e5e6cc70f5feda + run: | + curl -sSfL --retry 3 "https://github.com/Pagefind/pagefind/releases/download/${PAGEFIND_VERSION}/pagefind-${PAGEFIND_VERSION}-x86_64-unknown-linux-musl.tar.gz" \ + -o "$RUNNER_TEMP/pagefind.tar.gz" + echo "${PAGEFIND_SHA256} $RUNNER_TEMP/pagefind.tar.gz" | sha256sum -c - + tar -xzf "$RUNNER_TEMP/pagefind.tar.gz" -C "$RUNNER_TEMP" pagefind + + - name: Build search index + shell: bash + working-directory: ${{ inputs.path }} + # The Zola action runs as root in Docker, so public/ is owned by root. + run: | + sudo chown -R "$(id -u):$(id -g)" public + "$RUNNER_TEMP/pagefind" diff --git a/.github/actions/check-links/action.yml b/.github/actions/check-links/action.yml index 159d22b0..49d95a1f 100644 --- a/.github/actions/check-links/action.yml +++ b/.github/actions/check-links/action.yml @@ -1,14 +1,15 @@ name: Check the website's links description: > - Checks a built site (/public) for links to missing pages or #anchors. If base-path is - provided, only surfaces issues that don't appear in both. + Checks a built site for links to missing pages or #anchors, and for doc links that weren't + converted to site URLs. Given a build from before the change, fails only on problems the change + causes. Without, fails on every problem. inputs: - path: - description: The website to check the build for, relative to the workspace (e.g. website). + after: + description: The built site to check, relative to the workspace (e.g. website/public). required: true - base-path: - description: A checkout of the base commit to compare with. If it has no public directory, every broken link is listed. + before: + description: A built site from before the change to compare with, relative to the workspace. Leave empty if there is none. default: '' runs: @@ -26,21 +27,20 @@ runs: tar -xzf "$RUNNER_TEMP/lychee.tar.gz" -C "$RUNNER_TEMP" --strip-components=1 lychee-x86_64-unknown-linux-gnu/lychee echo "$RUNNER_TEMP" >> "$GITHUB_PATH" + # Uses the scripts from the same commit as this action, so a change to a check is used on both + # builds. Runs both even if the first fails. - name: Check links shell: bash env: - CHECKOUT: ${{ inputs.path }} - BASE_CHECKOUT: ${{ inputs.base-path }} + BEFORE: ${{ inputs.before }} + AFTER: ${{ inputs.after }} run: | + build=$(git -C "$GITHUB_ACTION_PATH" rev-parse --show-toplevel)/build + before=- + if [ -n "$BEFORE" ]; then before=$BEFORE; fi status=0 - for check in broken-links unconverted-doc-links; do - echo "build/$check.sh:" - before=- - if [ -n "$BASE_CHECKOUT" ]; then - before=$RUNNER_TEMP/$check-before.txt - if [ -d "$BASE_CHECKOUT/public" ]; then "$CHECKOUT/build/$check.sh" "$BASE_CHECKOUT/public" > "$before"; fi - fi - "$CHECKOUT/build/$check.sh" "$CHECKOUT/public" > "$RUNNER_TEMP/$check.txt" - "$CHECKOUT/build/compare-link-failures.sh" "$before" "$RUNNER_TEMP/$check.txt" || status=1 + for check in broken-links.sh unconverted-doc-links.sh; do + echo "$check:" + "$build/compare-problems.sh" "$before" "$AFTER" "$build/$check" || status=1 done exit "$status" diff --git a/.github/actions/check-search-index/action.yml b/.github/actions/check-search-index/action.yml new file mode 100644 index 00000000..ebd997e2 --- /dev/null +++ b/.github/actions/check-search-index/action.yml @@ -0,0 +1,29 @@ +name: Check the website's search index +description: > + Checks a built site's search index for missing or unexpected pages and wrong or duplicate titles. + Given a build from before the change, fails only on problems the change causes. Without, fails + on every problem. + +inputs: + after: + description: The built site to check, relative to the workspace (e.g. website/public). + required: true + before: + description: A built site from before the change to compare with, relative to the workspace. Leave empty if there is none. + default: '' + +runs: + using: composite + steps: + # Uses the script from the same commit as this action, so a change to the check is used on + # both builds. Runs it with python3, since the runner doesn't have uv. + - name: Check search index + shell: bash + env: + BEFORE: ${{ inputs.before }} + AFTER: ${{ inputs.after }} + run: | + build=$(git -C "$GITHUB_ACTION_PATH" rev-parse --show-toplevel)/build + before=- + if [ -n "$BEFORE" ]; then before=$BEFORE; fi + "$build/compare-problems.sh" "$before" "$AFTER" python3 "$build/check-search-index.py" diff --git a/.github/workflows/link-check.yml b/.github/workflows/link-check.yml index 5f02e126..d6df3d44 100644 --- a/.github/workflows/link-check.yml +++ b/.github/workflows/link-check.yml @@ -22,38 +22,20 @@ jobs: uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: path: website - fetch-depth: 0 # for the base commit - - name: Check out the base commit - env: - BASE_SHA: ${{ github.event.pull_request.base.sha }} - run: git -C website worktree add --detach ../base "$BASE_SHA" - - # Each side uses its own build-site, so changes to the build itself are checked too. - # If the base doesn't build or has no build-site, the checks list every broken link - # instead. - name: Build this PR - id: head uses: ./website/.github/actions/build-site with: path: website - name: Build the base id: base - if: hashFiles('base/.github/actions/build-site/action.yml') != '' - continue-on-error: true - uses: ./base/.github/actions/build-site + uses: ./website/.github/actions/build-base with: - path: base - checkout-content: false - - # A failed build can leave part of a site, which could hide links the PR breaks. - - name: Discard a failed base build - if: steps.base.outcome == 'failure' - run: rm -rf base/public + ref: ${{ github.event.pull_request.base.sha }} - name: Check links uses: ./website/.github/actions/check-links with: - path: website - base-path: base + before: ${{ steps.base.outputs.site }} + after: website/public diff --git a/.github/workflows/search-check.yml b/.github/workflows/search-check.yml new file mode 100644 index 00000000..e7ac3695 --- /dev/null +++ b/.github/workflows/search-check.yml @@ -0,0 +1,59 @@ +# Builds the site before and after the PR and checks its search index. Fails if the PR causes a +# problem. Problems already there before the PR, such as ones from other repos, are listed but don't +# fail the check. Includes scheduled posts (drafts) so they are checked before being merged. + +name: Search check + +on: + pull_request: + branches: ["main"] + +permissions: + contents: read + +concurrency: + group: search-check-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + search-index: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + path: website + + - name: Build this PR + uses: ./website/.github/actions/build-site + with: + path: website + drafts: true + + - name: Build the base + id: base + uses: ./website/.github/actions/build-base + with: + ref: ${{ github.event.pull_request.base.sha }} + drafts: true + + - name: Check search index + uses: ./website/.github/actions/check-search-index + with: + before: ${{ steps.base.outputs.site }} + after: website/public + + # Only checks when this PR changes the Pagefind version or the list of sites. Those are the + # only changes in this repo that can stop search from merging the other sites. + - name: Check the other Valkey sites have a copy of their search index for this Pagefind version + if: ${{ !cancelled() }} + env: + BASE: ${{ steps.base.outputs.site }} + run: | + version() { jq -r .version "$1/pagefind/pagefind-entry.json" 2>/dev/null || echo none; } + if [ "$(version "$BASE")" = "$(version website/public)" ] \ + && cmp -s base/static/cross-site-search.json website/static/cross-site-search.json; then + echo "This PR doesn't change the Pagefind version or the list of sites, so there's nothing to check." + exit 0 + fi + ./website/build/index-copies.sh check diff --git a/.github/workflows/zola-deploy.yml b/.github/workflows/zola-deploy.yml index 0fb8da39..c18587ca 100644 --- a/.github/workflows/zola-deploy.yml +++ b/.github/workflows/zola-deploy.yml @@ -32,6 +32,11 @@ jobs: with: path: website + - name: Build copies of the search index for the other Valkey sites + if: github.event_name != 'pull_request' + working-directory: website + run: ./build/index-copies.sh build + - name: Upload artifact if: github.event_name != 'pull_request' uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3 @@ -81,9 +86,16 @@ jobs: name: github-pages - name: Unpack the built site + id: unpack run: mkdir public && tar -xf artifact.tar -C public - name: Check links uses: ./.github/actions/check-links with: - path: . + after: public + + - name: Check search index + if: ${{ !cancelled() && steps.unpack.outcome == 'success' }} + uses: ./.github/actions/check-search-index + with: + after: public diff --git a/README.md b/README.md index f4e83bfc..cba4bb83 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,20 @@ Open your browser to `http://127.0.0.1:1111/` Zola will automatically rebuild on changes to the template or any content stored in this repo. Changes to external content (command reference, documentation topics) require a restart of the Zola server process (`ctrl-c` then `zola serve` again, a browser refresh may also be needed). +### Site search (optional) + +The search index is built in CI after `zola build`. `zola serve` doesn't build or update it, so search doesn't work there. To try search locally, download `pagefind` for your platform from the [Pagefind releases](https://github.com/Pagefind/pagefind/releases) (the version in `.github/actions/build-site/action.yml`) and run, from the root of this repo: + +```shell +zola build && pagefind --serve +``` + +Open the URL Pagefind prints after `Serving "public" at`. The server doesn't rebuild on changes, so run the command again after editing. + +Every page needs a unique ``. CI checks this when it checks the search index, so if it reports a `duplicate title`, change the `title` in the front matter of one of the listed pages. + +Search also shows results from the other Valkey sites listed in `static/cross-site-search.json`. + ### Checking catalog entries The clients and integrations entries in `_data/libraries/` are checked by `build/validate-libraries.py`, against the rules in `_data/libraries/schema.json` and the SPDX license list. diff --git a/build/broken-links.sh b/build/broken-links.sh index 73e5750d..3d132955 100755 --- a/build/broken-links.sh +++ b/build/broken-links.sh @@ -1,10 +1,16 @@ #!/usr/bin/env bash -# Lists links in a built site to missing pages or #anchors. +# Lists links in a built site to missing pages or #anchors, one "key<TAB>message" line each. +# Keyed by the link alone, so a new page that inherits a link that was already dead (such as one +# in the footer) isn't a new problem. # # build/broken-links.sh public +# +# Exits 0 if there are no problems, 1 if there are, and 2 if it couldn't check. set -euo pipefail -site=$(cd "${1:?usage: broken-links.sh <built site>}" && pwd -P) +if [ $# -ne 1 ]; then echo "usage: $(basename "$0") <built site>" >&2; exit 2; fi +site=$(cd "$1" && pwd -P) || exit 2 report=$(mktemp) +trap 'rm -f "$report"' EXIT status=0 # --offline skips links written as https://valkey.io/..., so point them at the build. @@ -13,14 +19,18 @@ lychee --offline --no-progress --format json --output "$report" --config "$(dirn "$site" > /dev/null || status=$? case $status in 0 | 2) ;; # 2 means lychee found broken links - *) echo "lychee itself failed (exit code $status)" >&2; exit 1 ;; + *) echo "lychee itself failed (exit code $status)" >&2; exit 2 ;; esac -jq -r --arg root "$site" '.error_map | to_entries[] | .key as $page | .value[] +problems=$(jq -r --arg root "$site" '.error_map | to_entries[] | .key as $page | .value[] | (.url | ltrimstr("file://" + $root)) as $link | ($page | ltrimstr($root) | rtrimstr("index.html")) as $on | (if (.status.text | startswith("Cannot find fragment")) then "but that page has no #\($link | split("#") | last) anchor" elif (.status.text | startswith("File not found")) then "but no such page exists" else .status.text end) as $problem | [$link, "\($on) links to \($link), \($problem)"] | @tsv' "$report" \ - | sort -u + | sort -u) || exit 2 + +if [ -z "$problems" ]; then exit 0; fi +echo "$problems" +exit 1 diff --git a/build/check-search-index.py b/build/check-search-index.py new file mode 100755 index 00000000..a125a5c0 --- /dev/null +++ b/build/check-search-index.py @@ -0,0 +1,102 @@ +#!/usr/bin/env -S uv run --script +# /// script +# requires-python = ">=3.9" +# /// +"""Lists problems with a built site's Pagefind search index, one "key<TAB>message" line each. + + build/check-search-index.py public + +Exits 0 if there are no problems, 1 if there are, and 2 if it couldn't check (such as a site +with no search index). + +Problems: +- missing: a rendered page is not in the index. +- unexpected: the index has a page that isn't rendered, such as the 404 page. +- title mismatch: a page's search title isn't the name in its <title>. +- duplicate title: two indexed pages have the same <title>. +""" + +import collections +import gzip +import html +import json +import pathlib +import re +import sys + +FRAGMENT_PREFIX = b"pagefind_dcd" + + +def expected_pages(public): + """Return {URL: <title> text}, skipping redirect stubs, the 404 page and HTML + fragments that aren't full pages.""" + pages = {} + for path in public.rglob("*.html"): + source = path.read_text(encoding="utf-8", errors="replace") + is_redirect = '<meta http-equiv="refresh"' in source + is_fragment = "<html" not in source + if is_redirect or is_fragment or path.name == "404.html": + continue + url = "/" + path.relative_to(public).as_posix() + title = re.search(r"<title>(.*?)", source, re.DOTALL) + pages[url.removesuffix("index.html")] = normalise(html.unescape(title.group(1))) if title else "" + return pages + + +def normalise(text): + return " ".join(text.split()) + + +def indexed_records(public): + """Return every page record in the index. + + The fragment format is undocumented, so a Pagefind upgrade that changes it + should fail here rather than check nothing. + """ + records = [] + for path in (public / "pagefind" / "fragment").glob("*.pf_fragment"): + data = gzip.decompress(path.read_bytes()) + records.append(json.loads(data.removeprefix(FRAGMENT_PREFIX))) + return records + + +def matches_page_title(record, page_title): + # is the search title on its own or after a prefix. + title = normalise(record["meta"].get("title", "")) + return page_title == title or page_title.endswith(" · " + title) + + +def main(): + if len(sys.argv) != 2: + print(f"usage: {pathlib.Path(sys.argv[0]).name} <built site>", file=sys.stderr) + return 2 + public = pathlib.Path(sys.argv[1]) + expected = expected_pages(public) + records = indexed_records(public) + if not records: + print(f"error: no search index records under {public / 'pagefind'}", file=sys.stderr) + return 2 + + indexed = {record["url"] for record in records} + indexed_titles = {url: title for url, title in expected.items() if url in indexed} + title_counts = collections.Counter(indexed_titles.values()) + problems = { + "missing": expected.keys() - indexed, + "unexpected": indexed - expected.keys(), + "title mismatch": {r["url"] for r in records if not matches_page_title(r, expected.get(r["url"], ""))}, + "duplicate title": {f'{url} ("{title}")' for url, title in indexed_titles.items() if title_counts[title] > 1}, + } + + counts = ", ".join(f"{len(urls)} {name}" for name, urls in problems.items()) + print(f"{len(records)} pages indexed, {len(expected)} expected: {counts}", file=sys.stderr) + for name, urls in problems.items(): + for url in sorted(urls): + message = f"{name}: {url}" + if name == "duplicate title": + message += ". Every page needs a unique title, so change `title` in the front matter of one of them." + print(f"{name}: {url}\t{message}") + return 1 if any(problems.values()) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/build/compare-link-failures.sh b/build/compare-link-failures.sh deleted file mode 100755 index 2f587bcf..00000000 --- a/build/compare-link-failures.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env bash -# Prints failures from broken-links.sh or unconverted-doc-links.sh. -# -# build/compare-link-failures.sh <before> <after> -# Fails if a link in <after> isn't in <before>. If <before> doesn't exist (the base -# didn't build), lists everything as below. -# build/compare-link-failures.sh - <failures> -# Fails if there are any failures. -# -# Compares the first field of each failure. broken-links.sh puts only the link there, so a new -# page that inherits a dead footer link doesn't fail. -set -euo pipefail -before=${1:?usage: compare-link-failures.sh <before|-> <after>} after=${2:?} - -if [ "$before" != - ] && [ ! -e "$before" ]; then - echo "The base commit didn't build, so every broken link is listed." - before=- -fi - -if [ "$before" = - ]; then - if [ ! -s "$after" ]; then - echo "No broken links." - exit 0 - fi - echo "Broken links ($(wc -l < "$after" | tr -d ' ')):" - cut -f2 "$after" | sed 's/^/::error::/' - exit 1 -fi - -new_links=$(comm -13 <(cut -f1 "$before" | sort -u) <(cut -f1 "$after" | sort -u)) - -# Each failure is "link<TAB>message". Group the messages by whether their link is new. -new=() already=() -while IFS=$'\t' read -r link message; do - if grep -qxF -- "$link" <<< "$new_links"; then - new+=("$message") - else - already+=("$message") - fi -done < "$after" - -if [ ${#new[@]} -gt 0 ]; then - echo "Broken by this change (${#new[@]}):" - printf '::error::%s\n' "${new[@]}" -else - echo "This change doesn't break any links." -fi -if [ ${#already[@]} -gt 0 ]; then - echo "Already broken before this change (${#already[@]}):" - printf ' %s\n' "${already[@]}" -fi -if [ ${#new[@]} -gt 0 ]; then - exit 1 -fi diff --git a/build/compare-problems.sh b/build/compare-problems.sh new file mode 100755 index 00000000..d5ada1be --- /dev/null +++ b/build/compare-problems.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# Runs a check on a site before and after a change. Fails only on problems the change causes. +# Problems that were already there before are listed but don't fail. +# +# build/compare-problems.sh <before|-> <after> <check command...> +# +# <before> and <after> are built sites. With - for <before> there's nothing to compare with, so +# every problem fails. The same goes if <before> doesn't exist or the check couldn't check it, +# such as a site from before the check was added. +# +# A check is a command that takes a built site and lists its problems on stdout, one +# "key<TAB>message" line each and nothing else, where the key says which problems are the same +# one before and after. It exits 0 if there are no problems, 1 if there are, and anything else if +# it couldn't check. +# +# Exits 0 if the change causes no problems, 1 if it does, and 2 if the check couldn't check +# <after>. +set -euo pipefail +export LC_ALL=C +if [ $# -lt 3 ]; then echo "usage: $(basename "$0") <before|-> <after> <check command...>" >&2; exit 2; fi +before=$1 after=$2 +shift 2 +check=("$@") + +results=$(mktemp -d) +trap 'rm -rf "$results"' EXIT + +# Runs the check on site $1, writing its problems to $2. Fails if the check couldn't check, or if +# its exit code doesn't match what it listed (such as a crash that lists nothing). +run_check() { + local status=0 + "${check[@]}" "$1" > "$2" || status=$? + case $status in + 0) [ ! -s "$2" ] ;; + 1) [ -s "$2" ] ;; + *) false ;; + esac +} + +before_problems=$results/before.txt after_problems=$results/after.txt + +if ! run_check "$after" "$after_problems"; then + echo "::error::${check[*]} couldn't check $after" + exit 2 +fi + +compare=false +if [ "$before" != - ]; then + if [ ! -d "$before" ]; then + echo "There's no build from before this change, so every problem fails." + elif ! run_check "$before" "$before_problems" 2> "$results/before-errors.txt"; then + echo "The check couldn't check the build from before this change, so every problem fails. It said:" + sed 's/^/ /' "$results/before-errors.txt" + else + compare=true + fi +fi + +if [ "$compare" = false ]; then + if [ ! -s "$after_problems" ]; then + echo "No problems." + exit 0 + fi + echo "Problems ($(wc -l < "$after_problems" | tr -d ' ')):" + cut -f2 "$after_problems" | sed 's/^/::error::/' + exit 1 +fi + +new_keys=$(comm -13 <(cut -f1 "$before_problems" | sort -u) <(cut -f1 "$after_problems" | sort -u)) + +# Group the messages by whether their key is new. +new=() already=() +while IFS=$'\t' read -r key message || [ -n "$key" ]; do + if grep -qxF -- "$key" <<< "$new_keys"; then + new+=("$message") + else + already+=("$message") + fi +done < "$after_problems" + +if [ ${#new[@]} -gt 0 ]; then + echo "Caused by this change (${#new[@]}):" + printf '::error::%s\n' "${new[@]}" +else + echo "This change doesn't cause any problems." +fi +if [ ${#already[@]} -gt 0 ]; then + echo "Already there before this change (${#already[@]}):" + printf ' %s\n' "${already[@]}" +fi +if [ ${#new[@]} -gt 0 ]; then + exit 1 +fi diff --git a/build/index-copies.sh b/build/index-copies.sh new file mode 100755 index 00000000..053016d4 --- /dev/null +++ b/build/index-copies.sh @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +# Builds copies of this site's search index at /pagefind/v<major.minor>/, one for every Pagefind minor version from the +# oldest a Valkey site runs up to the newest release. Pagefind only merges indexes built with its own minor version, so +# this site must provide any version other sites may need. +# +# build/index-copies.sh build [site] produces the necessary indexes for other sites to consume +# build/index-copies.sh check [site] checks current Pagefind is compatible with indexes hosted by other sites +# +# Both fail if a site that has set up cross-site search has no copy for this build's Pagefind minor version yet. +# Redeploying that site usually adds the copy. +# +# Each Valkey site with cross-site search has a copy of this script. Keep the copies in sync. + +set -euo pipefail +case ${1:-} in build | check) ;; *) echo "usage: $0 build|check [site]" >&2; exit 2 ;; esac + +cd "$(dirname "$0")/.." +SITE=${2:-public} +OTHER_SITES=$(jq -r '.otherSites[]' static/cross-site-search.json) +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +minor_version() { cut -d. -f1-2 <<< "$1"; } # 1.5.2 -> 1.5 + +# Prints the Pagefind version of the index at $1, "none" if it has no usable index (a 404, or an entry file without a +# release number), or "down" for anything else, such as a 503 or no answer. +index_state() { + local status version + rm -f "$TMP/entry.json" # clean any prior state + status=$(curl -sS --retry 3 --retry-connrefused --max-time 20 -o "$TMP/entry.json" -w '%{http_code}' \ + "${1}pagefind-entry.json" 2>/dev/null) || status=failed + case $status in + 404) echo none; return ;; + 200) ;; + *) echo down; return ;; + esac + version=$(jq -r .version "$TMP/entry.json" 2>/dev/null) || version= + if [[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then + echo "$version" + else + echo none + fi +} + +check_other_sites() { + local this_minor index version copy_version missing=() + this_minor=$(minor_version "$1") + for index in $OTHER_SITES; do + # Check whether the site has any Pagefind index at all. + version=$(index_state "$index") + case $version in + none) continue ;; + down) missing+=("$index"); continue ;; + esac + # Check whether the site publishes its own version-specific index version. + case $(index_state "${index}v$(minor_version "$version")/") in + none) continue ;; # hasn't set up cross-site search + down) missing+=("$index"); continue ;; + esac + # Check whether the needed version is available. + copy_version=$(index_state "${index}v${this_minor}/") + [ "$(minor_version "$copy_version")" = "$this_minor" ] || missing+=("$index") + done + [ "${#missing[@]}" -gt 0 ] || return 0 + + cat >&2 << EOF +::error::These sites have no copy of their search index for Pagefind ${this_minor} yet, or can't be reached: ${missing[*]} +Deployed now, this site's search would leave them out. Either: + - redeploy them first, which adds a ${this_minor} copy if ${this_minor} is within the versions they publish. + - keep this site on the Pagefind version it uses now. +EOF + return 1 +} + +# Index versions to publish from this site. Finds the oldest version a Valkey site uses, and gathers each minor version +# of Pagefind published since up to the newest release. +versions_to_copy() { + local in_use=("$1") index state oldest + for index in $OTHER_SITES; do + state=$(index_state "$index") + case $state in + none) echo "::warning::${index} has no index; its version isn't counted" >&2 ;; + # Without its version, this deploy could stop publishing the copy that site's search uses. + down) echo "::error::${index} can't be reached; re-run this deploy once it can" >&2; return 1 ;; + *) echo "${index} runs Pagefind ${state}" >&2; in_use+=("$state") ;; + esac + done + oldest=$(printf '%s\n' "${in_use[@]}" | sort -V | head -1) + curl -fsS --retry 3 --retry-connrefused --max-time 20 https://registry.npmjs.org/pagefind | jq -r --arg oldest "$(minor_version "$oldest")" ' + def minor: split(".")[:2] | map(tonumber); + .versions | keys + | map(select(test("^[0-9]+\\.[0-9]+\\.[0-9]+$"))) # releases, not pre-releases + | map(select(minor >= ($oldest | minor))) # from the oldest minor version in use + | group_by(minor) | map(max_by(split(".") | map(tonumber))) | .[] # the newest patch of each + ' +} + +# Downloads Pagefind $1 to $TMP/$1/pagefind. +download_pagefind() { + local dir asset url + dir=$TMP/$1 + case $(uname -s)-$(uname -m) in + Linux-x86_64 | Linux-aarch64) asset="pagefind-v$1-$(uname -m)-unknown-linux-musl.tar.gz" ;; + Darwin-arm64) asset="pagefind-v$1-aarch64-apple-darwin.tar.gz" ;; + Darwin-x86_64) asset="pagefind-v$1-x86_64-apple-darwin.tar.gz" ;; + *) echo "no Pagefind release for $(uname -s) $(uname -m)" >&2; return 1 ;; + esac + url="https://github.com/Pagefind/pagefind/releases/download/v$1/${asset}" + mkdir -p "$dir" + curl -fsSL --retry 3 --max-time 300 "$url" -o "$dir/$asset" + curl -fsSL --retry 3 --max-time 60 "$url.sha256" -o "$dir/$asset.sha256" + if command -v sha256sum > /dev/null; then + (cd "$dir" && sha256sum -c --quiet "$asset.sha256") + else + (cd "$dir" && shasum -a 256 -c --quiet "$asset.sha256") # macOS has shasum instead + fi + tar -xzf "$dir/$asset" -C "$dir" +} + +this_version=$(jq -er .version "$SITE/pagefind/pagefind-entry.json") +check_other_sites "$this_version" +[ "$1" = build ] || exit 0 + +# Through a file, since a failure inside $(...) wouldn't stop the script. +versions_to_copy "$this_version" > "$TMP/versions" +for version in $(< "$TMP/versions"); do + echo "Building a Pagefind ${version} copy at pagefind/v$(minor_version "$version")/" + download_pagefind "$version" + "$TMP/$version/pagefind" --site "$SITE" --output-path "$SITE/pagefind/v$(minor_version "$version")" +done diff --git a/build/unconverted-doc-links.sh b/build/unconverted-doc-links.sh index f1517506..9d123825 100755 --- a/build/unconverted-doc-links.sh +++ b/build/unconverted-doc-links.sh @@ -1,24 +1,31 @@ #!/usr/bin/env bash -# Lists valkey-doc links that fix_links (templates/macros/) didn't convert to site URLs. -# The browser resolves these against the page URL, so they can open the wrong page. +# Lists links on topic and command pages that weren't converted to site URLs, one "key<TAB>message" +# line each. The browser resolves these against the page URL, so they can open the wrong page. # For example, ../clients/ on /topics/installation/ opens /topics/clients/. +# Keyed by page too, since the same link opens a different page under topics and commands. # # build/unconverted-doc-links.sh public +# +# Exits 0 if there are no problems, 1 if there are, and 2 if it couldn't check. set -euo pipefail -cd "${1:?usage: unconverted-doc-links.sh <built site>}" +if [ $# -ne 1 ]; then echo "usage: $(basename "$0") <built site>" >&2; exit 2; fi +cd "$1" || exit 2 -# hrefs on topic and command pages that still start with ../ or point at a .md file, as -# valkey-doc writes them. [^":] skips links with a scheme, such as https://…/README.md. +# hrefs on topic and command pages that still start with ../ or point at a .md file, as the source +# docs write them. [^":] skips links with a scheme, such as https://…/README.md. unconverted='href="(\.\./[^"]*|[^":]*\.md(#[^"]*)?)"' # grep prints one "topics/x/index.html:href=\"../y.md\"" per match. It exits 1 when nothing # matches, which means the site is clean. -# Keyed by page too, since the same link opens a different page under topics and commands. -{ grep -roE "$unconverted" topics commands --include=index.html || [ $? -eq 1 ]; } | +problems=$({ grep -roE "$unconverted" topics commands --include=index.html || [ $? -eq 1 ]; } | while IFS= read -r match; do page=/${match%%index.html:*} # topics/x/index.html:… → /topics/x/ link=${match#*:href=\"} # …:href="../y.md" → ../y.md" link=${link%\"} # → ../y.md - printf '%s\t%s links to %s, a valkey-doc link that was not converted to a site URL\n' \ + printf '%s\t%s links to %s, a doc link that was not converted to a site URL\n' \ "$page $link" "$page" "$link" - done | sort -u + done | sort -u) || exit 2 + +if [ -z "$problems" ]; then exit 0; fi +echo "$problems" +exit 1 diff --git a/config.toml b/config.toml index 68709386..57bea7fa 100644 --- a/config.toml +++ b/config.toml @@ -3,8 +3,6 @@ title = "Valkey" compile_sass = true -build_search_index = true - generate_feeds = true taxonomies = [ diff --git a/content/download/releases/_index.md b/content/download/releases/_index.md index 482881c0..fa7457a1 100644 --- a/content/download/releases/_index.md +++ b/content/download/releases/_index.md @@ -1,4 +1,5 @@ +++ +title = "Releases" page_template= "release-page.html" template= "release-section.html" sort_by= "title" diff --git a/pagefind.yml b/pagefind.yml new file mode 100644 index 00000000..d24f8764 --- /dev/null +++ b/pagefind.yml @@ -0,0 +1,8 @@ +site: public + +# Only the page content, not the header and footer +root_selector: ".body" + +exclude_selectors: + # Sidebars repeat on many pages. + - "aside" diff --git a/sass/_valkey.scss b/sass/_valkey.scss index 64955d77..be94a12f 100644 --- a/sass/_valkey.scss +++ b/sass/_valkey.scss @@ -156,6 +156,11 @@ p { font-size: 1.6rem; font-weight: 600; + // Tighter spacing so the nav still fits with the search button + @media (max-width: 1200px) { + gap: 1rem; + } + a { white-space: nowrap; color: inherit; @@ -256,6 +261,35 @@ p { text-align: center; } } + + // Match the search button to the GitHub button + #site-search { + display: flex; + --pf-background: #f8f9fa; + --pf-border: #dfe1e4; + --pf-input-height: 100%; + + pagefind-modal-trigger { + flex-grow: 1; + } + + // Pagefind hides its other keyboard hints on touch devices, but not this one + @media (hover: none) { + .pf-trigger-shortcut { + display: none !important; + } + } + + // The mobile menu is a column, where 100% would shrink the button + @media (max-width: 1024px) { + --pf-input-height: 3.9rem; + + // Pagefind resets its elements with a high-specificity selector + .pf-trigger-btn { + justify-content: center !important; + } + } + } } .btn-menu { display: none; @@ -2806,3 +2840,62 @@ blockquote { .calendar-day { min-height: 40px; font-size: 1.1rem; } .calendar-nav .calendar-nav-title { font-size: 1.8rem; min-width: auto; } } + +// The site shown on each search result +pagefind-modal .search-result-site { + // Otherwise it stretches across the result + width: fit-content; + margin: 6px 0 0; + padding: 2px 8px; + border-radius: 4px; + background: var(--pf-hover); + color: var(--pf-text-secondary); + font-size: 13px; +} + +// The site filter's pills, above the results +pagefind-modal .search-site-filter { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin: 4px 0 12px; + + &[hidden] { + display: none; + } + + button { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 7px 12px; + border: 1px solid var(--pf-border); + border-radius: 999px; + background: var(--pf-background); + color: var(--pf-text); + font: inherit; + font-size: 14px; + line-height: 1; + cursor: pointer; + + &:hover { + border-color: var(--pf-border-focus); + } + + &:focus-visible { + outline: 2px solid var(--pf-outline-focus); + outline-offset: 2px; + } + + &[aria-pressed="true"] { + border-color: var(--pf-text); + background: var(--pf-text); + color: var(--pf-background); + } + } + + .search-site-filter-count { + font-size: 12px; + opacity: 0.7; + } +} diff --git a/static/assets/js/search.js b/static/assets/js/search.js new file mode 100644 index 00000000..3f8d63f5 --- /dev/null +++ b/static/assets/js/search.js @@ -0,0 +1,178 @@ +// Site search, including results from the other Valkey sites. + +// Favour exact word matches and longer pages over short pages with similar words. +// Values based on git-scm.com's Pagefind setup. +const RANKING = { pageLength: 0.1, termFrequency: 0.1, termSaturation: 2, termSimilarity: 9 }; + +// Other sites that don't answer within this are left out. +const LOAD_TIMEOUT_MS = 3000; + +// Listed first in the site filter. Set once the list of sites loads. +let thisSiteLabel = null; + +document.addEventListener('DOMContentLoaded', function() { + const slot = document.getElementById('site-search'); + // Without a search index, such as under zola serve, there is no search button. + if (!window.PagefindComponents || !slot) return; + + // Configure before creating the elements: the first element to connect creates the + // instance with default settings, and configuration after that is ignored. + window.PagefindComponents.configureInstance('default', { + ranking: RANKING, + }); + + const trigger = document.createElement('pagefind-modal-trigger'); + trigger.setAttribute('compact', ''); + slot.append(trigger); + createModal(); + + // Only fetch the other sites' indexes once the visitor uses search. + let isMergeStarted = false; + document.addEventListener('focusin', function(event) { + if (isMergeStarted || !event.target.closest('pagefind-modal')) return; + isMergeStarted = true; + mergeOtherSites().catch(function(error) { + console.warn('Search: merging the other sites failed', error); + }); + }); +}); + +// Pagefind's default modal, plus the site filter and each result's site. +function createModal() { + const modal = document.createElement('pagefind-modal'); + // The modal goes on <body>, inside the nav it would be hidden while the mobile menu is closed. + document.body.append(modal); + + modal.querySelector('pagefind-summary').before(createSiteFilter()); + + labelResultsWithTheirSite(modal.querySelector('pagefind-results')); +} + +// A pill per site, plus "All sites", with one picked at a time. +function createSiteFilter() { + const instance = window.PagefindComponents.getInstanceManager().getInstance('default'); + const bar = document.createElement('div'); + bar.className = 'search-site-filter'; + bar.setAttribute('role', 'group'); + bar.setAttribute('aria-label', 'Filter by site'); + bar.hidden = true; + + const ALL_SITES = ''; + const pills = {}; + let pickedSite = ALL_SITES; + let counts = {}; + + function createPill(site, name) { + const count = document.createElement('span'); + count.className = 'search-site-filter-count'; + const pill = document.createElement('button'); + pill.type = 'button'; + pill.append(name, count); + pill.addEventListener('click', function() { + pickedSite = site; + instance.triggerFilter('site', site === ALL_SITES ? [] : [site]); + draw(); + }); + return pill; + } + + // Updated in place, so a focused pill keeps focus when the counts change. + function draw() { + const sites = Object.keys(counts).sort(function(a, b) { + const thisSiteFirst = (b === thisSiteLabel) - (a === thisSiteLabel); + return thisSiteFirst || a.localeCompare(b); + }); + bar.hidden = sites.length < 2 || !instance.searchTerm.trim(); + + const shown = [ALL_SITES].concat(sites); + for (const site of shown) { + pills[site] = pills[site] || createPill(site, site === ALL_SITES ? 'All sites' : site); + } + const isOrderChanged = shown.some(function(site, i) { return bar.children[i] !== pills[site]; }); + if (isOrderChanged) bar.replaceChildren(...shown.map(function(site) { return pills[site]; })); + + const total = sites.reduce(function(sum, site) { return sum + counts[site]; }, 0); + for (const site of shown) { + pills[site].setAttribute('aria-pressed', String(site === pickedSite)); + pills[site].lastChild.textContent = String(site === ALL_SITES ? total : counts[site]); + } + } + + // `total` ignores the picked site, so the other sites keep their counts. + instance.on('filters', function(filters) { + counts = (filters.total && filters.total.site) || {}; + draw(); + }); + instance.on('search', draw); + return bar; +} + +// Adds the site's name to each result as Pagefind renders it, which happens as results scroll into +// view. +function labelResultsWithTheirSite(results) { + const instance = window.PagefindComponents.getInstanceManager().getInstance('default'); + new MutationObserver(function() { + // Placeholders carry the index too, before Pagefind replaces them with the result. + const rendered = results.querySelectorAll('[data-pf-result-index]:not([aria-hidden="true"]):not([data-site-labelled])'); + for (const result of rendered) { + result.setAttribute('data-site-labelled', ''); + const rawResult = instance.searchResult.results[result.getAttribute('data-pf-result-index')]; + if (!rawResult) continue; + rawResult.data().then(function(data) { + if (!data.meta.site || !result.isConnected) return; + const label = document.createElement('p'); + label.className = 'search-result-site'; + label.textContent = 'Site: ' + data.meta.site; + result.querySelector('.pf-result-content').append(label); + }).catch(function(error) { + console.warn('Search: labelling a result failed', error); + }); + } + }).observe(results, { childList: true, subtree: true }); +} + +// Merging an index that doesn't load breaks every search (Pagefind issue #887), so each is checked +// first. Returns its Pagefind minor version, or null. +async function probeIndexVersion(bundlePath) { + try { + const signal = AbortSignal.timeout(LOAD_TIMEOUT_MS); + // Skips caches, as Pagefind does, so this checks the same deploy Pagefind will load. + const entry = await (await fetch(bundlePath + 'pagefind-entry.json?ts=' + Date.now(), { signal })).json(); + const language = Object.values(entry.languages)[0]; + const meta = await fetch(bundlePath + 'pagefind.' + language.hash + '.pf_meta', { signal }); + return meta.ok ? entry.version.split('.').slice(0, 2).join('.') : null; + } catch { + return null; + } +} + +async function mergeOtherSites() { + const instance = window.PagefindComponents.getInstanceManager().getInstance('default'); + await instance.triggerLoad(); + const [ownVersion, sites] = await Promise.all([ + probeIndexVersion('/pagefind/'), + fetch('/cross-site-search.json').then(function(response) { return response.json(); }), + ]); + if (!ownVersion) { + console.warn("Search: this site's index didn't load, so not merging the other sites"); + return; + } + thisSiteLabel = sites.label; + + await Promise.all(sites.otherSites.map(async function(index) { + // Pagefind only merges indexes built with its own minor version, so each site publishes a + // copy of its index for each version. + const bundle = index + 'v' + ownVersion + '/'; + if ((await probeIndexVersion(bundle)) !== ownVersion) { + console.warn('Search: leaving out ' + index + ', which has no copy for Pagefind ' + ownVersion + " or didn't load in time"); + return; + } + // The Component UI has no public way to merge an index after it loads, so this uses its + // private Pagefind instance. Merged indexes don't inherit the instance's ranking. + await instance.__pagefind__.mergeIndex(bundle, { ranking: RANKING, indexWeight: sites.otherSitesIndexWeight }); + // Without this, the site filter leaves this site out until the search box is cleared. + await instance.__pagefind__.filters(); + // Pagefind doesn't redo a search that finished before this merge. + instance.triggerSearch(instance.searchTerm); + })); +} diff --git a/static/cross-site-search.json b/static/cross-site-search.json new file mode 100644 index 00000000..54e78264 --- /dev/null +++ b/static/cross-site-search.json @@ -0,0 +1,9 @@ +{ + "label": "valkey.io", + "otherSites": [ + "https://glide.valkey.io/pagefind/", + "https://valkey-admin.valkey.io/pagefind/", + "https://spring.valkey.io/pagefind/" + ], + "otherSitesIndexWeight": 1 +} diff --git a/templates/404.html b/templates/404.html index b889bf51..af956651 100644 --- a/templates/404.html +++ b/templates/404.html @@ -1,10 +1,12 @@ {% extends "default.html" %} {% block content %} +<div data-pagefind-ignore="all"> <h1 class="page-title">File Not Found (404)</h1> <div class="width-limiter"> <main class="container"> Perhaps you mistyped the URL or something moved around. Sorry about that. </main> </div> +</div> {% endblock content %} \ No newline at end of file diff --git a/templates/default.html b/templates/default.html index a886903d..f4fa0375 100644 --- a/templates/default.html +++ b/templates/default.html @@ -1,4 +1,14 @@ -{%- block head -%}{%- endblock -%}<!DOCTYPE html> +{%- block head -%}{%- endblock -%} +{#- The page's name, for the page title and og:title. Templates set the variables below in their head + block, which must stay above this. #} +{%- set name_prefix = "Valkey" %} +{%- if command_title is defined and command_title %}{% set page_name = command_title %}{% set name_prefix = "Valkey Command" %} +{%- elif frontmatter_title is defined and frontmatter_title %}{% set page_name = frontmatter_title %}{% set name_prefix = "Valkey Documentation" %} +{%- elif release_title is defined and release_title %}{% set page_name = release_title %} +{%- elif page is defined and page.title %}{% set page_name = page.title %} +{%- elif section is defined and section.title %}{% set page_name = section.title %} +{%- else %}{% set page_name = "" %}{% endif -%} +<!DOCTYPE html> <html lang="{{ page?.lang | default(value=config.default_language) }}"> {% include "includes/head.html" %} <script> @@ -69,11 +79,15 @@ GitHub <!-- Star count will be injected here by JS --> </a> + <div id="site-search"></div> </nav> </div> </div> - <div class="body"> + {#- Search results use the page's name, since a page's first heading isn't always its title. #} + <div class="body" data-pagefind-meta="title:{% if page_name %}{{ page_name }}{% else %}{{ name_prefix }}{% endif %}"> + {#- Names this site so the other Valkey sites can label its results. #} + <span hidden data-pagefind-filter="site:valkey.io" data-pagefind-meta="site:valkey.io"></span> {% block content %}{% endblock %} </div> <div class="footer"> diff --git a/templates/includes/head.html b/templates/includes/head.html index 2bf49492..3d263f6e 100644 --- a/templates/includes/head.html +++ b/templates/includes/head.html @@ -29,34 +29,17 @@ <meta name="msapplication-config" content="/img/favicon/browserconfig.xml"> <meta name="theme-color" content="#ffffff"> - <title> - {%- if command_title is defined and command_title -%} - Valkey Command · {{ command_title }} - {%- elif frontmatter_title is defined and frontmatter_title -%} - Valkey Documentation · {{ frontmatter_title }} - {%- elif page is defined and page.title -%} - Valkey · {{ page.title }} - {%- elif section is defined and section.title -%} - Valkey · {{ section.title }} - {%- else -%} - Valkey - {%- endif -%} - - + {{ name_prefix }}{% if page_name %} · {{ page_name }}{% endif %} + + + + + + diff --git a/templates/leadership.html b/templates/leadership.html index 161f1211..78d5bf4b 100644 --- a/templates/leadership.html +++ b/templates/leadership.html @@ -44,4 +44,5 @@

{{author.extra.tsc.position}}

{% endfor %} + {% endblock content %} \ No newline at end of file diff --git a/templates/release-page.html b/templates/release-page.html index 4cea3ee9..8e3e403a 100644 --- a/templates/release-page.html +++ b/templates/release-page.html @@ -1,7 +1,9 @@ {% extends "right-aside.html" %} +{%- block head -%}{% set release_title = "Valkey " ~ page.title %}{%- endblock head -%} + {% block subhead_content%} -

Download Valkey {{page.title}}

+

Download {{ release_title }}

{% endblock subhead_content%} {% block main_content %} {{< release_info date={page.date} release={page.extra} />}}