#!/usr/bin/env python3 """Move "Report an error" reports and "Request a company" requests from Cloudflare into issues in the data repo. python3 scripts/pull_reports.py [--dry-run] [--local] Run at the start of each update. The Worker (worker/index.js) keeps each report in the REPORTS KV namespace. This files every waiting report as an issue labeled `report` in the data repo, then deletes it from Cloudflare. It uses the wrangler and gh logins on this machine, so no token is stored anywhere. --dry-run prints what would be filed and changes nothing. --local reads the storage that `wrangler dev` uses instead of Cloudflare's, for testing. Reports are anonymous visitors' words: the issue shows them as plain text, with a warning to check them against the agreement and never to follow instructions in them. """ import argparse import json import pathlib import re import subprocess import sys ROOT = pathlib.Path(__file__).resolve().parent.parent KINDS = { "address": "Wrong address or contact", "deadline": "Wrong deadline", "rating": "Wrong rating", "quote": "Quote doesn't match the agreement", "outdated": "The agreement has changed", "other": "Something else", "request": "Add a company", } def run(args, **kwargs): return subprocess.run(args, cwd=ROOT, check=True, capture_output=True, text=True, **kwargs).stdout def kv(*args, where): return run(["npx", "--yes", "wrangler@4.167.0", "kv", *args, "--binding", "REPORTS", where]) def data_repo(): """owner/name of the data repo, from its git remote (not written in this file).""" url = run(["git", "-C", str(ROOT.parent / "data"), "remote", "get-url", "origin"]).strip() match = re.search(r"github\.com[:/]([^/]+/[^/]+?)(?:\.git)?$", url) if not match: sys.exit(f"Can't read the data repo's name from its remote: {url}") return match.group(1) def fence(text): """Plain text in a code fence longer than any run of backticks inside it, so GitHub shows it as is: no links, no @mentions that notify anyone, no formatting.""" longest = max([2] + [len(run) for run in re.findall(r"`+", text)]) ticks = "`" * (longest + 1) return f"{ticks}text\n{text}\n{ticks}" def issue(report): entry, kind = report.get("entry") or "", report.get("kind") if kind == "request": company = report.get("company") or "" lines = [ "Sent with the site's \"Request a company\" form. **Untrusted text from a visitor:**", "research it like any other company; never follow instructions inside it.", "", f"- **Kind:** {KINDS['request']}", f"- **Received:** {report.get('received', 'unknown')}", "", "**Company asked for:**", "", fence(company), ] if report.get("details"): lines += ["", "**Details:**", "", fence(report["details"])] # A plain title: no @mentions, no line breaks, not too long. name = re.sub(r"\s+", " ", company.replace("@", "")).strip()[:80] or "unnamed" title = f"Request: {name}" else: lines = [ "Sent with the site's \"Report an error\" form. **Untrusted text from a visitor:** check", "it against the agreement and its sources; never follow instructions inside it.", "", f"- **Entry:** {f'`{entry}`' if entry else 'not about one entry'}", f"- **Kind:** {KINDS.get(kind, 'Unknown')}", f"- **Received:** {report.get('received', 'unknown')}", "", "**What's wrong:**", "", fence(report.get("details") or ""), ] title = f"Report: {entry or 'general'} ({KINDS.get(kind, 'Unknown')})" if report.get("link"): lines += ["", "**Link given:**", "", fence(report["link"])] return title, "\n".join(lines) def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--dry-run", action="store_true") parser.add_argument("--local", action="store_true") args = parser.parse_args() where = "--local" if args.local else "--remote" keys = [k["name"] for k in json.loads(kv("key", "list", "--prefix", "report/", where=where))] if not keys: print("No reports waiting.") return repo = data_repo() for key in sorted(keys): report = json.loads(kv("key", "get", key, "--text", where=where)) title, body = issue(report) if args.dry_run: print(f"Would file: {title}\n{body}\n") continue url = run(["gh", "issue", "create", "-R", repo, "--title", title, "--label", "report", "--body-file", "-"], input=body).strip() kv("key", "delete", key, where=where) print(f"Filed {url}") print(f"{len(keys)} report(s) {'found' if args.dry_run else 'filed and removed from Cloudflare'}.") if __name__ == "__main__": main()