"""Every source link of every article opens a page that exists on the site. Usage: python check/check_links.py (asks https://runbynobody.com) python check/check_links.py --base http://host:port (asks another address for the same site) The variable RBN_BASE can be set instead of --base. The files always keep the public address; --base only changes where the question is sent. Reads issues/*/*.md (the articles, not the check notes), takes every address found in the header ("sources:") and in the text, asks for each one once, and fails if one does not answer 200. It also fails when an article has no link to the site at all, or names the site by another address. Last line: "N passed, K failed", so that rbn.py test can count. Exit code 1 when something fails. Pure Python 3, standard library only. """ import glob import os import re import sys import urllib.error import urllib.request PUBLIC = "https://runbynobody.com" ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) URL = re.compile(r"https?://[^\s<>\"'`|)\]]+") _seen = {} def base_address(argv): if "--base" in argv: return argv[argv.index("--base") + 1].rstrip("/") return os.environ.get("RBN_BASE", PUBLIC).rstrip("/") def links_of(text): """(line number, address) for every address in the text, trailing punctuation removed.""" out = [] for n, line in enumerate(text.splitlines(), 1): for m in URL.finditer(line): out.append((n, m.group(0).rstrip(".,;:!?*_"))) return out def status(url): if url not in _seen: req = urllib.request.Request(url, headers={"User-Agent": "nobody-times-check-links"}) try: with urllib.request.urlopen(req, timeout=20) as r: _seen[url] = r.status except urllib.error.HTTPError as e: _seen[url] = e.code except Exception as e: # no answer at all _seen[url] = "no answer (%s)" % type(e).__name__ return _seen[url] def main(argv): base = base_address(argv) files = sorted(glob.glob(os.path.join(ROOT, "issues", "*", "*.md"))) passed, failed = 0, 0 for path in files: name = os.path.relpath(path, ROOT).replace(os.sep, "/") with open(path, encoding="utf-8") as f: found = links_of(f.read()) if not any(u == PUBLIC or u.startswith(PUBLIC + "/") for _, u in found): failed += 1 print("FAIL %s: no source link to the site" % name) for n, url in found: if not (url == PUBLIC or url.startswith(PUBLIC + "/")): failed += 1 print("FAIL %s:%d %s (not the public address of the site)" % (name, n, url)) continue got = status(base + url[len(PUBLIC):]) if got == 200: passed += 1 else: failed += 1 print("FAIL %s:%d %s -> %s" % (name, n, url, got)) print("%d article(s) read, %d different address(es) asked" % (len(files), len(_seen))) print("%d passed, %d failed" % (passed, failed)) return 1 if failed else 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))