interplane-forge
INTERPLANE Forge
Brought by drakestapleton
interplane-forge / store / tests / radcrawl.py
| 1 | #!/usr/bin/env python3 |
| 2 | # ORACLE: host test driver, not product code. |
| 3 | # store/tests/radcrawl.py BASE LIMIT OUT.json: crawl a running forge from BASE (seeds below, then the |
| 4 | # links it finds on the same host, up to LIMIT addresses) and count the Radicle patterns of |
| 5 | # RadFreeForgeAndSI's crawl (~/work/hive/rad-free-si/crawl.py, the same regular expression) in what the |
| 6 | # forge itself writes. Repository content is left out of the count: every page of a repository below |
| 7 | # its home (blob, raw, blame, tree, commit, commits, compare, releases, archive, search), the result |
| 8 | # lines of the forge-wide code search (/search?q=: lines of repository files), and, on a |
| 9 | # project home, the README, the description and the last commit subject (HTML: the readme box, the |
| 10 | # desc paragraph and the Last commit line; JSON: the readme, description and last_commit values; |
| 11 | # text form: from the README.md heading on, and the description and last commit lines). |
| 12 | # Prints one FORGE line per address with forge-written hits, then |
| 13 | # RADCRAWL urls=N forge_hits=H content_hits=C codes={...} |
| 14 | # and exits 1 when H > 0, 0 otherwise. OUT.json gets every row. |
| 15 | import json, re, sys, urllib.error, urllib.parse, urllib.request |
| 16 | from collections import deque |
| 17 | |
| 18 | P = re.compile(r'radicle|\brad:z[1-9A-HJ-NP-Za-km-z]{10,}|\brad (clone|init|sync|id|patch|auth)|/rad/|heartwood|radicle\.(xyz|network|garden|dev)', re.I) |
| 19 | BASE, LIMIT, OUT = sys.argv[1], int(sys.argv[2]), sys.argv[3] |
| 20 | SEEDS = ['/', '/explore', '/explore.json', '/explore?format=text', '/agents.json', '/agents.json?format=text', |
| 21 | '/events.json', '/events.json?limit=200', '/feed', '/feed?format=text', '/drakestapleton', |
| 22 | '/drakestapleton?format=text', '/drakestapleton.json', '/login', '/stars', '/search?q=forge', |
| 23 | '/drakestapleton/hop', '/drakestapleton/hop.json', '/drakestapleton/hop?format=text', |
| 24 | '/drakestapleton/omega-mv', '/drakestapleton/omega-mv.json', '/drakestapleton/omega-mv?format=text', |
| 25 | '/drakestapleton/cuda-crack', '/drakestapleton/cuda-crack.json', '/drakestapleton/interplane.io', |
| 26 | '/status', '/status.json', '/open/', '/drakestapleton/hop/patches', '/no-such-page-x'] |
| 27 | CONTENT = re.compile(r'^(/[^/?]+/[^/?]+/(blob|raw|blame|tree|commit|commits|compare|releases|archive|search)(/|\?|$)|/search\?)') |
| 28 | HOME = re.compile(r'^/[^/?]+/([^/?]+?)(\.json)?(\?format=text)?$') |
| 29 | host = urllib.parse.urlparse(BASE).netloc |
| 30 | |
| 31 | def fetch(u): |
| 32 | class NR(urllib.request.HTTPRedirectHandler): |
| 33 | def redirect_request(self, *a, **k): return None |
| 34 | try: |
| 35 | r = urllib.request.build_opener(NR).open(urllib.request.Request(BASE + u, headers={'User-Agent': 'radcrawl'}), timeout=60) |
| 36 | return r.status, r.headers.get('Content-Type', ''), r.read() |
| 37 | except urllib.error.HTTPError as e: |
| 38 | return e.code, e.headers.get('Content-Type', ''), e.read() |
| 39 | |
| 40 | def forge_part(u, ct, t): |
| 41 | """the text the forge itself wrote on page u (repository content cut out)""" |
| 42 | if CONTENT.match(u.split('#')[0]): |
| 43 | return '' |
| 44 | m = HOME.match(u) |
| 45 | if not m or u.startswith(('/drakestapleton?', '/drakestapleton.json')) or m.group(1) in ('followers', 'following'): |
| 46 | return t |
| 47 | if 'json' in ct: |
| 48 | try: |
| 49 | d = json.loads(t) |
| 50 | except ValueError: |
| 51 | return t |
| 52 | if isinstance(d, dict) and d.get('schema') == 'forge/repo/1': |
| 53 | for k in ('readme', 'description', 'last_commit', 'files'): |
| 54 | d.pop(k, None) |
| 55 | return json.dumps(d) |
| 56 | return t |
| 57 | if 'text/plain' in ct: |
| 58 | t = t.split('\nREADME.md', 1)[0] |
| 59 | return '\n'.join(l for l in t.split('\n') if not l.startswith(('Last commit', 'Description'))) |
| 60 | # HTML: the readme box up to the developer section, the description, the last commit line |
| 61 | t = re.sub(r'<div class="box readme".*?(?=<section class="pj-dev")', '', t, flags=re.S) |
| 62 | t = re.sub(r'<p class="desc">.*?</p>', '', t, flags=re.S) |
| 63 | t = re.sub(r'<p class="meta">Last commit:.*?</p>', '', t, flags=re.S) |
| 64 | return t |
| 65 | |
| 66 | seen, q, rows = set(), deque(SEEDS), [] |
| 67 | while q and len(seen) < LIMIT: |
| 68 | u = q.popleft() |
| 69 | if u in seen: |
| 70 | continue |
| 71 | seen.add(u) |
| 72 | try: |
| 73 | c, ct, b = fetch(u) |
| 74 | except Exception as e: |
| 75 | rows.append(dict(url=u, code='ERR', forge=0, content=0, ex=str(e)[:80])) |
| 76 | continue |
| 77 | t = b.decode('utf-8', 'replace') |
| 78 | allh = len(P.findall(t)) |
| 79 | f = forge_part(u, ct, t) |
| 80 | fm = list(P.finditer(f)) |
| 81 | rows.append(dict(url=u, code=c, forge=len(fm), content=allh - len(fm), |
| 82 | ex=f[max(0, fm[0].start() - 70):fm[0].end() + 30].replace('\n', ' ') if fm else '')) |
| 83 | if any(x in ct for x in ('html', 'json', 'text')): |
| 84 | for h in re.findall(r'''(?:href|src)=["']([^"'#]+)''', t) + re.findall(r'"(/[A-Za-z0-9_./?=&%-]+)"', t): |
| 85 | h = h.replace('&', '&') |
| 86 | pu = urllib.parse.urlparse(urllib.parse.urljoin(BASE + u, h)) |
| 87 | if pu.netloc != host: |
| 88 | continue |
| 89 | p = pu.path + ('?' + pu.query if pu.query else '') |
| 90 | if p.startswith('/assets/') or p.endswith(('.css', '.svg', '.png', '.ico', '.tar', '.woff2', '.zip', '.gz')): |
| 91 | continue |
| 92 | if p not in seen: |
| 93 | q.append(p) |
| 94 | codes = {} |
| 95 | for r in rows: |
| 96 | codes[str(r['code'])] = codes.get(str(r['code']), 0) + 1 |
| 97 | if r['forge']: |
| 98 | print('FORGE', r['code'], r['forge'], r['url'], '|', r['ex']) |
| 99 | for s in SEEDS: |
| 100 | r = next((r for r in rows if r['url'] == s), None) |
| 101 | if r: |
| 102 | print('SEED', r['code'], r['forge'], r['content'], s) |
| 103 | fh, ch = sum(r['forge'] for r in rows), sum(r['content'] for r in rows) |
| 104 | print('RADCRAWL urls=%d forge_hits=%d content_hits=%d codes=%s' % (len(rows), fh, ch, json.dumps(codes, sort_keys=True))) |
| 105 | json.dump(rows, open(OUT, 'w'), indent=1) |
| 106 | sys.exit(1 if fh else 0) |