diff --git a/.github/workflows/check-links.yml b/.github/workflows/check-links.yml new file mode 100644 index 0000000..b1c44f1 --- /dev/null +++ b/.github/workflows/check-links.yml @@ -0,0 +1,73 @@ +# Checks every web link of the courses (tools/check_links.py): pages that +# answer, YouTube videos that can still be played. +# - On each pull request that changes a course: report only, nothing blocked. +# - Every Monday morning (and on demand): dead pages are replaced by their +# archive.org copy in a pull request « Liens morts remplacés par leur +# archive », and the issue « Liens morts » lists what was found (choice of +# Timmy, 2026-12-06: A + C). Nothing is merged without Timmy. +name: Check the links + +on: + pull_request: + paths: ['**.md', 'tools/check_links.py', '.github/workflows/check-links.yml'] + schedule: + - cron: '17 6 * * 1' + workflow_dispatch: + +permissions: + contents: read + +jobs: + report: + name: Check the links (report) + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Check every link + run: python3 tools/check_links.py . + + weekly: + name: Replace dead links and update the issue + if: github.event_name != 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write + pull-requests: write + issues: write + env: + GH_TOKEN: ${{ github.token }} + BRANCH: liens-morts-archive + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Check every link and repair what archive.org keeps + run: python3 tools/check_links.py . --repair + - name: Open a pull request with the replaced links + run: | + if git diff --quiet -- '*.md'; then echo "Aucun lien remplacé."; exit 0; fi + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git switch -C "$BRANCH" + git add -- '*.md' + git commit -m "Liens morts remplacés par leur copie sur archive.org" + git push --force "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" "$BRANCH" + gh pr view "$BRANCH" >/dev/null 2>&1 || gh pr create --head "$BRANCH" --title "Liens morts remplacés par leur archive" --body-file verif-liens.md + - name: Update the issue « Liens morts » + run: | + numero=$(gh issue list --state open --search 'in:title "Liens morts"' --json number --jq '.[0].number') + if [ -n "$numero" ]; then gh issue edit "$numero" --body-file verif-liens.md + else gh issue create --title "Liens morts" --body-file verif-liens.md; fi + - name: Keep the report + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: verif-liens + path: | + verif-liens.json + verif-liens.md diff --git a/.gitignore b/.gitignore index 7a60b85..ba0511a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ __pycache__/ *.pyc +verif-liens.json +verif-liens.md diff --git a/tests/test_check_links.py b/tests/test_check_links.py new file mode 100644 index 0000000..b7b6df1 --- /dev/null +++ b/tests/test_check_links.py @@ -0,0 +1,169 @@ +"""Tests of the external link checker (tools/check_links.py). + +No network access: the answers of the sites, of YouTube and of archive.org +are mocked (unittest.mock) and the courses are written in a temporary fake +repository. Each test's docstring says in French what it checks. + +Run: python3 -m unittest discover -s tests -v +""" + +from __future__ import annotations + +import contextlib +import io +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'tools')) + +import check_links as cl # noqa: E402 + +COURSE = """--- +titre: Un cours +--- + +Voir [la norme](https://exemple.fr/norme), [la vidéo](https://www.youtube.com/watch?v=abc123), +[une recherche](https://www.youtube.com/results?search_query=derivee) et [le site mort](https://mort.fr/page). +""" + +# Mocked answers: HTTP status by address. +RESPONSES = { + 'https://exemple.fr/norme': 200, + 'https://mort.fr/page': 404, +} +ARCHIVE = 'https://web.archive.org/web/20250101000000/https://mort.fr/page' + + +def fake_status(url: str) -> int: + if url.startswith('https://www.youtube.com/oembed'): + return 404 if 'abc123' in url and FakeNetwork.video_morte else 200 + return RESPONSES.get(url, 200) + + +class FakeNetwork: + dead_video = False + + +class BaseTest(unittest.TestCase): + def setUp(self) -> None: + self._folder = tempfile.TemporaryDirectory() + self.addCleanup(self._folder.cleanup) + self.root = Path(self._folder.name) + (self.root / 'maths').mkdir() + self.course = self.root / 'maths' / 'cours.md' + self.course.write_text(COURSE, encoding='utf-8') + self._cwd = os.getcwd() + os.chdir(self.root) # the reports are written in the current folder + self.addCleanup(os.chdir, self._cwd) + FakeNetwork.video_morte = False + + def run_checker(self, *options: str, archive: str | None = ARCHIVE) -> tuple[int, dict]: + with mock.patch.object(cl, 'status', side_effect=fake_status), \ + mock.patch.object(cl, 'archived', return_value=archive) as fake_archive, \ + mock.patch.object(sys, 'argv', ['check_links.py', str(self.root), *options]), \ + contextlib.redirect_stdout(io.StringIO()): + code = cl.main() + self.fake_archive = fake_archive + return code, json.loads((self.root / 'verif-liens.json').read_text(encoding='utf-8')) + + +class TestVerdicts(BaseTest): + def test_classifies_links(self): + """Classe les liens (bons, morts, recherches).""" + _, report = self.run_checker() + self.assertEqual(report['broken'], ['https://mort.fr/page']) + self.assertIn('https://exemple.fr/norme', report['ok']) + self.assertIn('https://www.youtube.com/watch?v=abc123', report['ok']) + self.assertEqual(report['search'], ['https://www.youtube.com/results?search_query=derivee']) + + def test_deleted_video_is_dead(self): + """Vidéo supprimée est morte.""" + FakeNetwork.video_morte = True + _, report = self.run_checker() + self.assertIn('https://www.youtube.com/watch?v=abc123', report['broken']) + + def test_site_refusing_robots_needs_manual_check(self): + """Site qui refuse les robots est à vérifier.""" + RESPONSES['https://exemple.fr/norme'] = 403 + self.addCleanup(RESPONSES.__setitem__, 'https://exemple.fr/norme', 200) + _, report = self.run_checker() + self.assertEqual(report['robots'], ['https://exemple.fr/norme']) + + +class TestHandling(BaseTest): + def test_nothing_blocked_by_default(self): + """Rien n'est bloqué par défaut.""" + code, _ = self.run_checker() + self.assertEqual(code, 0) + + def test_strict_fails_on_dead_link(self): + """Avec --strict, un lien mort fait échouer.""" + code, _ = self.run_checker('--strict') + self.assertEqual(code, 1) + + def test_without_repair_course_unchanged(self): + """Sans réparer le cours ne change pas.""" + self.run_checker() + self.assertEqual(self.course.read_text(encoding='utf-8'), COURSE) + self.fake_archive.assert_not_called() + + def test_repair_replaces_with_archived_copy(self): + """Réparer remplace par la copie archivée.""" + _, report = self.run_checker('--repair') + text = self.course.read_text(encoding='utf-8') + self.assertIn(f'[le site mort]({ARCHIVE})', text) + self.assertNotIn('](https://mort.fr/page)', text) + self.assertEqual(report['archive'], [{'before': 'https://mort.fr/page', 'after': ARCHIVE}]) + self.assertEqual(report['broken'], []) + + def test_repair_without_archive_keeps_dead_link(self): + """Réparer sans copie archivée laisse le lien mort.""" + _, report = self.run_checker('--repair', archive=None) + self.assertIn('](https://mort.fr/page)', self.course.read_text(encoding='utf-8')) + self.assertEqual(report['broken'], ['https://mort.fr/page']) + + def test_video_never_replaced_by_archive(self): + """Une vidéo n'est jamais remplacée par une archive.""" + FakeNetwork.video_morte = True + _, report = self.run_checker('--repair') + self.assertIn('https://www.youtube.com/watch?v=abc123', report['broken']) + self.assertIn('](https://www.youtube.com/watch?v=abc123)', self.course.read_text(encoding='utf-8')) + + def test_report_for_issue(self): + """Rapport pour le ticket.""" + self.run_checker('--repair') + issue = (self.root / 'verif-liens.md').read_text(encoding='utf-8') + self.assertIn('Remplacés par leur copie sur archive.org (1)', issue) + self.assertIn('Liens cassés (0)', issue) + + +class TestArchive(unittest.TestCase): + def response(self, data: dict): + fake = mock.MagicMock() + fake.__enter__.return_value = io.BytesIO(json.dumps(data).encode()) + return fake + + def test_reads_closest_copy(self): + """Lit la copie la plus proche.""" + data = {'archived_snapshots': {'closest': {'available': True, 'status': '200', 'url': 'http://web.archive.org/web/1/https://mort.fr/page'}}} + with mock.patch.object(cl.urllib.request, 'urlopen', return_value=self.response(data)): + self.assertEqual(cl.archived('https://mort.fr/page'), 'https://web.archive.org/web/1/https://mort.fr/page') + + def test_no_copy(self): + """Aucune copie.""" + with mock.patch.object(cl.urllib.request, 'urlopen', return_value=self.response({'archived_snapshots': {}})): + self.assertIsNone(cl.archived('https://mort.fr/page')) + + def test_archive_unreachable(self): + """Archive injoignable.""" + with mock.patch.object(cl.urllib.request, 'urlopen', side_effect=OSError('réseau')): + self.assertIsNone(cl.archived('https://mort.fr/page')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/check_links.py b/tools/check_links.py new file mode 100644 index 0000000..61777d7 --- /dev/null +++ b/tools/check_links.py @@ -0,0 +1,179 @@ +"""Checks every web link of the courses (asked by Timmy on 2026-12-05). + +For each link written as [text](https://...) in a .md file: +- a web page must answer (codes 2xx or 3xx after redirects); +- a YouTube video must still exist and be playable: YouTube's oEmbed answers + 200 for a public video, 401 when its owner forbids playing it elsewhere, + 404 when it is private or deleted; +- a YouTube search (youtube.com/results) is listed apart: it is to be + replaced by a chosen video. + +Some sites refuse robots (403, 429): they are listed as « à vérifier à la +main », not as broken. The report goes to the summary of the GitHub run +($GITHUB_STEP_SUMMARY), to the standard output and to verif-liens.md, which +the Monday workflow posts as the GitHub issue « Liens morts ». + +What to do with a dead link (Timmy's choice, 2026-12-06: A and C): +- nothing is blocked: the exit code is 0 unless --strict is given; +- with --repair, a dead web page is replaced in the courses by its latest + copy on archive.org (Wayback Machine), when one exists; the report lists + what was replaced and what is still dead. +Only the standard library is used. +""" +import json +import os +import re +import sys +import urllib.error +import urllib.parse +import urllib.request +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +LINK = re.compile(r"\]\((https?://[^)\s]+)\)") +AGENT = "Mozilla/5.0 (compatible; verif-liens-cours/1.0; +https://github.com/TimmyWeatherhead/Cours)" +ROBOTS_REFUSED = {401, 403, 405, 406, 429, 451, 999} + + +def links(root: Path) -> dict[str, list[str]]: + found: dict[str, list[str]] = {} + for path in sorted(root.rglob("*.md")): + if ".git" in path.parts or "node_modules" in path.parts: + continue + for url in LINK.findall(path.read_text(encoding="utf-8")): + found.setdefault(url, []).append(str(path.relative_to(root))) + return found + + +def video_id(url: str) -> str | None: + parts = urllib.parse.urlparse(url) + if parts.netloc.endswith("youtu.be"): + return parts.path.strip("/") or None + if "youtube.com" in parts.netloc and parts.path in ("/watch", "/embed") or parts.path.startswith("/embed/"): + query = urllib.parse.parse_qs(parts.query) + return (query.get("v") or [parts.path.rsplit("/", 1)[-1]])[0] + return None + + +def status(url: str) -> int: + for method in ("HEAD", "GET"): + request = urllib.request.Request(url, method=method, headers={"User-Agent": AGENT, "Accept-Language": "fr,en"}) + try: + with urllib.request.urlopen(request, timeout=25) as answer: + return answer.status + except urllib.error.HTTPError as error: + if method == "HEAD" and error.code in (403, 404, 405, 501): + continue + return error.code + except Exception: + if method == "HEAD": + continue + return 0 + return 0 + + +def check(url: str) -> tuple[str, str, str]: + """(url, kind, verdict) with verdict ok, robots, broken or search.""" + parts = urllib.parse.urlparse(url) + if "youtube.com" in parts.netloc and parts.path.startswith("/results"): + return url, "recherche YouTube", "search" + vid = video_id(url) + if vid: + oembed = "https://www.youtube.com/oembed?format=json&url=" + urllib.parse.quote(f"https://www.youtube.com/watch?v={vid}") + code = status(oembed) + if code == 200: + return url, "vidéo", "ok" + if code == 401: + return url, "vidéo (lecture seulement sur YouTube)", "ok" + return url, f"vidéo indisponible ({code})", "broken" + code = status(url) + if 200 <= code < 400: + return url, str(code), "ok" + if code in ROBOTS_REFUSED: + return url, f"{code}, refusé aux robots", "robots" + return url, str(code) if code else "pas de réponse", "broken" + + +ARCHIVE_API = "https://archive.org/wayback/available?url=" + + +def archived(url: str) -> str | None: + """Latest archive.org copy of a page, or None.""" + request = urllib.request.Request(ARCHIVE_API + urllib.parse.quote(url, safe=""), headers={"User-Agent": AGENT}) + try: + with urllib.request.urlopen(request, timeout=25) as answer: + data = json.load(answer) + except Exception: + return None + snapshot = (data.get("archived_snapshots") or {}).get("closest") or {} + if snapshot.get("available") and str(snapshot.get("status", "200")).startswith("2") and snapshot.get("url"): + return snapshot["url"].replace("http://", "https://", 1) + return None + + +def replace_in_courses(root: Path, files: list[str], old: str, new: str) -> None: + for name in sorted(set(files)): + path = root / name + text = path.read_text(encoding="utf-8") + path.write_text(text.replace(f"]({old})", f"]({new})"), encoding="utf-8") + + +def repair(root: Path, found: dict[str, list[str]], broken: list[tuple[str, str]]) -> list[tuple[str, str]]: + """Replaces each dead web page by its archive.org copy. Returns (old, new).""" + done = [] + for url, kind in broken: + if kind.startswith("vidéo"): + continue # an archived page cannot play a video + copy = archived(url) + if copy: + replace_in_courses(root, found[url], url, copy) + done.append((url, copy)) + return done + + +def main() -> int: + args = [a for a in sys.argv[1:] if not a.startswith("--")] + root = Path(args[0] if args else ".") + found = links(root) + with ThreadPoolExecutor(max_workers=8) as pool: + results = list(pool.map(check, sorted(found))) + groups = {"broken": [], "robots": [], "search": [], "ok": []} + for url, kind, verdict in results: + groups[verdict].append((url, kind)) + titles = { + "broken": "Liens cassés", + "robots": "À vérifier à la main (le site refuse les robots)", + "search": "Recherches YouTube à remplacer par une vidéo choisie", + "ok": "Liens qui répondent", + } + repaired = repair(root, found, groups["broken"]) if "--repair" in sys.argv else [] + fixed = {old for old, _ in repaired} + groups["broken"] = [(u, k) for u, k in groups["broken"] if u not in fixed] + lines = [f"# Vérification des liens : {len(found)} liens\n"] + if repaired: + lines.append(f"\n## Remplacés par leur copie sur archive.org ({len(repaired)})\n") + for old, new in repaired: + lines.append(f"- {old} → {new} — {', '.join(sorted(set(found[old])))}") + for key in ("broken", "robots", "search", "ok"): + lines.append(f"\n## {titles[key]} ({len(groups[key])})\n") + if key in ("search", "ok"): + files = sorted({f for url, _ in groups[key] for f in found[url]}) + lines.append(f"Dans {len(files)} fichiers.\n") + if key == "ok": + continue + for url, kind in groups[key]: + lines.append(f"- {kind} : {url} — {', '.join(sorted(set(found[url])))}") + report = "\n".join(lines) + "\n" + print(report) + summary = os.environ.get("GITHUB_STEP_SUMMARY") + if summary: + Path(summary).write_text(report, encoding="utf-8") + Path("verif-liens.md").write_text(report, encoding="utf-8") + result = {k: [u for u, _ in v] for k, v in groups.items()} + result["archive"] = [{"before": old, "after": new} for old, new in repaired] + Path("verif-liens.json").write_text(json.dumps(result, ensure_ascii=False, indent=1), encoding="utf-8") + return 1 if groups["broken"] and "--strict" in sys.argv else 0 + + +if __name__ == "__main__": + sys.exit(main())