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
5 changes: 5 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ jobs:
if: github.event_name == 'pull_request'
run: zola build --drafts

- name: Check social images
run: |
python3 -B scripts/test-social-images.py
python3 scripts/check-social-images.py public

- name: Validate HTML
run: >-
npx --yes --package vnu-jar@26.8.21 vnu
Expand Down
71 changes: 71 additions & 0 deletions scripts/check-social-images.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#!/usr/bin/env python3
"""Check that rendered posts reference nonempty local social images."""

import argparse
from html.parser import HTMLParser
from pathlib import Path
import sys
from urllib.parse import unquote, urlsplit


class Metadata(HTMLParser):
def __init__(self):
super().__init__()
self.properties = {}

def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "meta" and "property" in attrs:
self.properties[attrs["property"]] = attrs.get("content", "")


def check(root):
root = root.resolve()
errors = []
count = 0
for page in sorted(root.rglob("*.html")):
metadata = Metadata()
metadata.feed(page.read_text(encoding="utf-8"))
props = metadata.properties
if props.get("og:type") != "article":
continue
count += 1
label = page.relative_to(root)
image = props.get("og:image", "").strip()
if not image:
errors.append(f"{label}: missing og:image")
continue
url = urlsplit(image)
site = urlsplit(props.get("og:url", ""))
if url.netloc and url.netloc != site.netloc:
errors.append(f"{label}: social image must be local: {image}")
continue
path = unquote(url.path)
target = ((root / path.lstrip("/")) if path.startswith("/")
else (page.parent / path)).resolve()
if not target.is_relative_to(root):
errors.append(f"{label}: image path escapes build directory: {image}")
elif not target.is_file() or target.stat().st_size == 0:
errors.append(f"{label}: missing or empty social image: {image}")
if count == 0:
errors.append(f"{root}: no rendered articles found; run zola build --drafts first")
return count, errors


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("directory", nargs="?", type=Path, default=Path("public"))
args = parser.parse_args()
count, errors = check(args.directory)
if errors:
for error in errors:
print(error, file=sys.stderr)
print("Add the missing social.png files (make social can generate them), then rebuild.",
file=sys.stderr)
return 1
print(f"Social images present for all {count} rendered posts.")
return 0


if __name__ == "__main__":
sys.exit(main())
67 changes: 67 additions & 0 deletions scripts/test-social-images.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""Regression tests for the rendered social-image check (standard library only)."""

import importlib.util
from pathlib import Path
import tempfile
import unittest

spec = importlib.util.spec_from_file_location(
"check_social_images", Path(__file__).with_name("check-social-images.py"))
checker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(checker)


class SocialImageTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.page = self.root / "blog/example/index.html"
self.page.parent.mkdir(parents=True)

def post(self, image):
self.page.write_text(
'<meta property="og:type" content="article">'
'<meta property="og:url" content="https://corrode.dev/blog/example/">'
f'<meta property="og:image" content="{image}">', encoding="utf-8")

def test_colocated_image(self):
self.post("https://corrode.dev/blog/example/social.png")
self.page.with_name("social.png").write_bytes(b"image")
self.assertEqual(checker.check(self.root), (1, []))

def test_fallback_image(self):
self.post("/social/default.png")
image = self.root / "social/default.png"
image.parent.mkdir()
image.write_bytes(b"image")
self.assertEqual(checker.check(self.root), (1, []))

def test_missing_and_empty_image(self):
self.post("social.png")
self.assertIn("missing or empty", checker.check(self.root)[1][0])
self.page.with_name("social.png").touch()
self.assertIn("missing or empty", checker.check(self.root)[1][0])

def test_missing_metadata(self):
self.post("")
self.assertIn("missing og:image", checker.check(self.root)[1][0])

def test_external_image(self):
self.post("https://example.org/social.png")
self.assertIn("must be local", checker.check(self.root)[1][0])

def test_path_escape(self):
self.post("/../outside.png")
self.assertIn("escapes build", checker.check(self.root)[1][0])

def test_redirects_and_sections_are_not_posts(self):
self.page.write_text('<meta http-equiv="refresh" content="0;url=/blog/new/">')
count, errors = checker.check(self.root)
self.assertEqual(count, 0)
self.assertIn("no rendered articles", errors[0])


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