Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,12 @@ Temporary Items
*~
# yarn things
.config

# Disposable validation reports
tmp/checks/

# Persistent build cache must not enter image layers.
.hugo_cache/

# Exported CI Docker layers
.buildx-cache*/
25 changes: 25 additions & 0 deletions .github/actions/prepare-build/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Prepare cached Hugo build
description: Restore Docker layers and Hugo modules, then build the Compose image once.
runs:
using: composite
steps:
- name: Cache Docker layers
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: .buildx-cache
key: docker-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('Dockerfile', '.env', 'package.json', 'package-lock.json', 'packages/**') }}-${{ github.sha }}
restore-keys: |
docker-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('Dockerfile', '.env', 'package.json', 'package-lock.json', 'packages/**') }}-
docker-v1-${{ runner.os }}-${{ runner.arch }}-

- name: Cache Hugo modules and downloads
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: .hugo_cache
key: hugo-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.env', 'go.mod', 'go.sum') }}-${{ github.sha }}
restore-keys: |
hugo-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('.env', 'go.mod', 'go.sum') }}-

- name: Build Compose image
shell: bash
run: make build-ci
13 changes: 8 additions & 5 deletions .github/scripts/build-site.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ fi
export HOME
export npm_config_cache="${npm_config_cache:-/tmp/.npm}"
export HUGO_ENV="${HUGO_ENV:-production}"
export NODE_PATH="${NODE_PATH:-/tmp/node_modules}"
export NODE_PATH="${NODE_PATH:-/src/node_modules}"

HUGO_CACHEDIR="${HUGO_CACHEDIR:-/src/.hugo_cache}"
OUTPUT_DIR="${OUTPUT_DIR:-/src/public}"
Expand All @@ -31,17 +31,20 @@ require_absolute_path() {
require_absolute_path "$HUGO_CACHEDIR" HUGO_CACHEDIR
require_absolute_path "$OUTPUT_DIR" OUTPUT_DIR

# Preserve edition integrity before publishing any generated pages.
python3 .github/scripts/check_standard_archives.py

mkdir -p "$HUGO_CACHEDIR" "$OUTPUT_DIR" "$npm_config_cache"

git config --global --add safe.directory /src
git config --global core.quotepath false

# Docsy 0.17.0 theme module mounts expect node_modules/ at the project root
# (e.g. node_modules/bootstrap -> assets/vendor/bootstrap). PostCSS tooling
# and theme dependencies are installed at /tmp/node_modules by the Dockerfile;
# symlink so Hugo module mounts resolve them at the project root.
# and theme dependencies live in the image-populated /src/node_modules volume.
# Isolated builds need a link from their disposable project root.
if [ ! -e node_modules ]; then
ln -s /tmp/node_modules node_modules
ln -s /src/node_modules node_modules
fi

set -- build \
Expand All @@ -56,4 +59,4 @@ if [ -n "$BASE_URL" ]; then
fi

echo "Running: hugo $*" >&2
exec hugo "$@"
exec hugo "$@"
113 changes: 113 additions & 0 deletions .github/scripts/check_site.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
"""Check navigation and every archived download in a /preview/ render."""
from collections import Counter
from html.parser import HTMLParser
from pathlib import Path
import hashlib
import json
import sys


class Page(HTMLParser):
def __init__(self, text):
super().__init__()
self.sidebar_classes = set()
self.mobile_toc = False
self.ids = []
self.links = []
self.feedback_links = []
self.feed(text)

def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
classes = set(attrs.get('class', '').split())
if 'td-sidebar-toc' in classes:
self.sidebar_classes = classes
if 'omf-standard__mobile-toc' in classes:
self.mobile_toc = True
if 'id' in attrs:
self.ids.append(attrs['id'])
if tag == 'a':
self.links.append(attrs.get('href', ''))
if 'btn-primary' in classes:
self.feedback_links.append(attrs.get('href', ''))


def check(output, source=Path('content/en')):
errors = []
pages = {}

def require(condition, location, message):
if not condition:
errors.append(f'{location}: {message}')

def page(name, standard, feedback=None):
try:
parsed = Page((output / name / 'index.html').read_text())
except OSError as error:
errors.append(f'{name}: cannot read rendered page: {error}')
return None
pages[name] = parsed
expected = {'d-none', 'd-xl-flex'} if standard else {'d-flex'}
require(expected <= parsed.sidebar_classes, name,
f'sidebar missing expected classes {sorted(expected)}')
require(('d-none' in parsed.sidebar_classes) == standard, name,
'sidebar visibility does not match the page layout')
require(parsed.mobile_toc == standard, name, 'incorrect mobile TOC presence')
duplicates = [key for key, count in Counter(parsed.ids).items() if count > 1]
require(not duplicates, name, f'duplicate HTML IDs: {duplicates}')
if feedback:
require(feedback in parsed.feedback_links, name,
f'primary feedback action must point to {feedback}')
return parsed

current = page('standards/documentation', True,
'https://github.com/openmodelingfoundation/rfcs/discussions/2')
for name in ('standards/documentation/versions', 'standards/reusability',
'working-groups/standards', 'working-groups/standards/drafts/documentation'):
page(name, False)

manifests = sorted((source / 'standards').glob('**/versions/*/manifest.json'))
require(bool(manifests), source, 'no edition manifests found')
definition_links = []
download_count = 0
for manifest_path in manifests:
name = manifest_path.parent.relative_to(source).as_posix()
try:
manifest = json.loads(manifest_path.read_text())
entries = manifest['files']
except (OSError, ValueError, KeyError) as error:
errors.append(f'{manifest_path}: cannot read manifest: {error}')
continue
archived = page(name, True, manifest.get('discussion_url'))
history = '/preview/' + manifest_path.parent.parent.relative_to(source).as_posix() + '/'
if archived:
require(history in archived.links, name, f'missing history link {history}')
for entry in entries:
if entry['path'] == 'index.md':
continue
served = output / name / entry['path']
href = '/preview/' + name + '/' + entry['path']
if archived:
require(href in archived.links, name, f'missing download link {href}')
try:
digest = hashlib.sha256(served.read_bytes()).hexdigest()
require(digest == entry['sha256'], served, 'download checksum mismatch')
download_count += 1
except OSError as error:
errors.append(f'{served}: cannot read download: {error}')
if entry['path'] == 'definition.pdf':
definition_links.append(href)
if current:
require(any(link in current.links for link in definition_links),
'standards/documentation', 'missing link to an archived definition PDF')
require('/preview/standards/documentation/versions/' in current.links,
'standards/documentation', 'missing version history link')
return errors, len(pages), download_count


if __name__ == '__main__':
errors, page_count, download_count = check(Path(sys.argv[1]))
for error in errors:
print(f'ERROR: {error}', file=sys.stderr)
print(f'Checked {page_count} pages and {download_count} downloads; {len(errors)} failure(s).')
sys.exit(bool(errors))
48 changes: 48 additions & 0 deletions .github/scripts/check_standard_archives.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""Verify that preserved standard editions still match their manifests."""

import argparse
import hashlib
import json
from pathlib import Path
import sys


def verify(root: Path) -> int:
editions = {path for path in root.glob("**/versions/*") if path.is_dir()}
if not editions:
raise ValueError("No standard editions found")
for edition in sorted(editions):
manifest = json.loads((edition / "manifest.json").read_text())
if manifest["schema_version"] != 1 or manifest["edition_id"] != edition.name:
raise ValueError(f"{edition}: invalid manifest schema or edition identifier")
listed = set()
for entry in manifest["files"]:
name = entry["path"]
path = edition / name
if (not path.resolve().is_relative_to(edition.resolve())
or name in listed or name == "manifest.json"):
raise ValueError(f"{edition}: invalid or duplicate file {name!r}")
listed.add(name)
data = path.read_bytes()
if len(data) != entry["bytes"] or hashlib.sha256(data).hexdigest() != entry["sha256"]:
raise ValueError(f"{path}: archived bytes differ from the manifest")
actual = {str(path.relative_to(edition)) for path in edition.rglob("*")
if path.is_file() and path != edition / "manifest.json"}
if "index.md" not in listed or actual != listed:
raise ValueError(f"{edition}: manifest does not cover every archived file")
print(f"Verified {edition.name}: {len(listed)} files")
return len(editions)


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path,
default=Path(__file__).resolve().parents[2] / "content/en/standards")
args = parser.parse_args()
try:
count = verify(args.root)
except (OSError, ValueError, KeyError, TypeError) as error:
print(f"Archive verification failed: {error}", file=sys.stderr)
sys.exit(1)
print(f"Verified {count} standard edition(s).")
57 changes: 57 additions & 0 deletions .github/scripts/render-isolated.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/bin/sh
set -eu

# Logs live outside the disposable workspace so failures remain inspectable.
check_name=render
if [ "${CHECK_SITE:-0}" = 1 ]; then check_name=site; fi
if [ "${CHECK_HTML:-0}" = 1 ]; then check_name=html; fi
if [ "${CHECK_HTML:-0}" = external ]; then check_name=external; fi
report_dir="/src/tmp/checks/$check_name"
mkdir -p "$report_dir"
# Clear only this check's previous report, not other checks or live build output.
rm -rf "$report_dir/rendered"
rm -f "$report_dir/"*.log "$report_dir/exit-status.txt"
workspace=$(mktemp -d)
export OUTPUT_DIR="$workspace/public"
cleanup() {
result=$?
trap - EXIT
printf '%s\n' "$result" > "$report_dir/exit-status.txt"
if [ "$result" -ne 0 ] && [ -d "$OUTPUT_DIR" ]; then
cp -a "$OUTPUT_DIR" "$report_dir/rendered"
fi
rm -rf "$workspace"
exit "$result"
}
trap cleanup EXIT
run_logged() {
log=$1
shift
result=0
"$@" > "$report_dir/$log" 2>&1 || result=$?
cat "$report_dir/$log"
return "$result"
}

# Keep host dependencies, caches, reports and server locks out of the build.
mkdir "$workspace/src"
tar --exclude='./.buildx-cache*' --exclude=./node_modules --exclude=./.hugo_cache --exclude=./tmp \
--exclude=./public --exclude=./resources --exclude=./.hugo_build.lock \
-cf "$workspace/source.tar" .
tar -xf "$workspace/source.tar" -C "$workspace/src"
cd "$workspace/src"
git config --global --add safe.directory "$workspace/src"
export HUGO_CACHEDIR=/src/.hugo_cache
run_logged build.log sh .github/scripts/build-site.sh
if [ "${CHECK_SITE:-0}" = 1 ]; then
run_logged site.log python3 .github/scripts/check_site.py "$OUTPUT_DIR"
fi
if [ "${CHECK_HTML:-0}" != 0 ]; then
config=.htmltest.yml
if [ "$CHECK_HTML" = external ]; then config=.htmltest-external.yml; fi
# Use the checked-in policy with this disposable render and persistent reports.
sed -e "s|^DirectoryPath:.*|DirectoryPath: \"$OUTPUT_DIR\"|" \
-e '/^OutputDir:/d' "$config" > "$workspace/htmltest.yml"
printf 'OutputDir: "%s"\n' "$report_dir" >> "$workspace/htmltest.yml"
run_logged console.log htmltest -c "$workspace/htmltest.yml"
fi
77 changes: 77 additions & 0 deletions .github/scripts/test_check_site.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""Verify multiple editions and actionable, aggregated failure diagnostics."""
import hashlib
import json
from pathlib import Path
import tempfile
import unittest

from check_site import check


class SiteChecks(unittest.TestCase):
def setUp(self):
temporary = tempfile.TemporaryDirectory()
self.addCleanup(temporary.cleanup)
self.root = Path(temporary.name)
self.output = self.root / 'public'
self.source = self.root / 'content'
self.feedback = 'https://github.com/openmodelingfoundation/rfcs/discussions/2'
self.history = '/preview/standards/documentation/versions/'
self.downloads = []
for edition in ('draft-1', 'draft-2'):
name = f'standards/documentation/versions/{edition}'
source = self.source / name
source.mkdir(parents=True)
files = [dict(path='index.md'), dict(path='definition.pdf', sha256=hashlib.sha256(b'original').hexdigest())]
(source / 'manifest.json').write_text(json.dumps(dict(files=files, discussion_url=self.feedback)))
href = '/preview/' + name + '/definition.pdf'
self.write_page(name, True, [self.history, href])
download = self.output / name / 'definition.pdf'
download.write_bytes(b'original')
self.downloads.append(download)
self.write_page('standards/documentation', True, [self.history, self.history + 'draft-2/definition.pdf'])
for name in ('standards/documentation/versions', 'standards/reusability', 'working-groups/standards',
'working-groups/standards/drafts/documentation'):
self.write_page(name, False, [])

def write_page(self, name, standard, links):
path = self.output / name / 'index.html'
path.parent.mkdir(parents=True, exist_ok=True)
classes = 'd-none d-xl-flex' if standard else 'd-flex'
html = f'<aside class="td-sidebar-toc {classes}"></aside>'
if standard:
html += '<details class="omf-standard__mobile-toc"></details>'
html += f'<a class="btn-primary" href="{self.feedback}">Feedback</a>'
html += ''.join(f'<a href="{link}">Link</a>' for link in links)
path.write_text(html)
return path

def test_two_editions(self):
errors, pages, downloads = check(self.output, self.source)
self.assertEqual(errors, [])
self.assertEqual((pages, downloads), (7, 2))

def test_collects_missing_and_changed_downloads(self):
self.downloads[0].unlink()
self.downloads[1].write_bytes(b'changed')
errors, _, _ = check(self.output, self.source)
self.assertTrue(any('cannot read download' in error for error in errors))
self.assertTrue(any('checksum mismatch' in error for error in errors))

def test_footer_link_does_not_replace_primary_feedback(self):
path = self.output / 'standards/documentation/index.html'
path.write_text(path.read_text().replace('class="btn-primary"', 'class="footer-link"') + '<p id="duplicate"></p><p id="duplicate"></p>')
errors, _, _ = check(self.output, self.source)
self.assertTrue(any('primary feedback action' in error for error in errors))
self.assertTrue(any('duplicate HTML IDs' in error for error in errors))

def test_missing_page_does_not_abort_other_checks(self):
(self.output / 'working-groups/standards/index.html').unlink()
self.downloads[1].unlink()
errors, _, _ = check(self.output, self.source)
self.assertTrue(any('cannot read rendered page' in error for error in errors))
self.assertTrue(any('cannot read download' in error for error in errors))


if __name__ == '__main__':
unittest.main()
Loading
Loading