interplane-forge
INTERPLANE Forge
Brought by drakestapleton
interplane-forge / store / tests / compare.py
| 1 | #!/usr/bin/env python3 |
| 2 | # ORACLE: host test helper for store/tests/compare.sh (outside tool, not product code). |
| 3 | # sample CATALOG PROJECTS FIXTURE the sampled project names, one per line (rule in compare.sh) |
| 4 | # fetch PORT DIR LISTFILE every page of LISTFILE; HTML-like pages also with the JSON Accept |
| 5 | # key PATH KIND the file name fetch gives PATH (KIND html or json) |
| 6 | # same A B every page of fetch dir A equals B (status, type, bytes) |
| 7 | # radicle A B B equals A apart from the rules listed in RULES: the Radicle id |
| 8 | # replaced by the store id, the forge-nav row without "Open builds" |
| 9 | # (server/noopen.om ohnav), the footer, the developer rows, the |
| 10 | # clone panel and the JSON clone object. A STORE line must be |
| 11 | # exactly what its rule makes of the MAIN line; any other difference |
| 12 | # is printed as BAD with its page and line, and the exit is 1 |
| 13 | # replay LISTING the same rules over a kept `radicle` listing, offline (no pages) |
| 14 | # manylines CATALOG N N well-formed public lines (names many-NNN) |
| 15 | # signin PORT KEY / star PORT SESSION REPO / stars PORT REPO social helpers (forge sign-in) |
| 16 | # env (radicle, replay): COMPARE_FIXTURES, the names of the fixture projects compare.sh signs with its |
| 17 | # KEY (space-separated), and COMPARE_FIXTURE_KEY, the SHA256 fingerprint of that key. The owner key of a |
| 18 | # fixture page must be exactly COMPARE_FIXTURE_KEY, and fixtures keep their own one-to-one table |
| 19 | # ("owner key of fixtures"): KEY need not be the store's owner key (the store's own projects keep the |
| 20 | # "owner key" table, one key for the owner name over all of them). |
| 21 | import base64, difflib, hashlib, http.client, json, os, re, subprocess, sys, urllib.parse |
| 22 | |
| 23 | OWNER = "drakestapleton" |
| 24 | JSON = "application/json" |
| 25 | SEAM = '<a href="/open/">Open builds</a>' |
| 26 | PLAIN = re.compile(r"/(raw|archive)/|\.(patch|diff|json)$|\.json\?") |
| 27 | FIXTURES = set(os.environ.get("COMPARE_FIXTURES", "").split()) |
| 28 | FIXKEY = os.environ.get("COMPARE_FIXTURE_KEY", "") |
| 29 | |
| 30 | |
| 31 | def owner_pair(name, delegate, fp): |
| 32 | # the owner-key pair of a page: fixtures are signed with compare.sh's KEY, which must be exactly |
| 33 | # COMPARE_FIXTURE_KEY; the store's own projects pair the owner name with one key over the run |
| 34 | if name in FIXTURES: |
| 35 | return ("owner key of fixtures", delegate, fp) if fp == FIXKEY else None |
| 36 | return ("owner key", delegate, fp) |
| 37 | |
| 38 | |
| 39 | def key(path, kind): |
| 40 | return hashlib.sha256((kind + " " + path).encode()).hexdigest()[:32] |
| 41 | |
| 42 | |
| 43 | def get(port, path, headers=None): |
| 44 | c = http.client.HTTPConnection("127.0.0.1", port, timeout=900) |
| 45 | c.request("GET", path, headers=headers or {}) |
| 46 | r = c.getresponse() |
| 47 | body = r.read() |
| 48 | out = (r.status, r.getheader("Content-Type", ""), r.getheader("Location", ""), body, r.getheaders()) |
| 49 | c.close() |
| 50 | return out |
| 51 | |
| 52 | |
| 53 | def fetch(port, d, listfile): |
| 54 | paths = [l.rstrip("\n") for l in open(listfile, encoding="utf-8") if l.strip()] |
| 55 | idx = [] |
| 56 | for p in paths: |
| 57 | kinds = ["html"] if PLAIN.search(p) else ["html", "json"] |
| 58 | for k in kinds: |
| 59 | st, ct, loc, body, _ = get(port, p, {"Accept": JSON} if k == "json" else {}) |
| 60 | name = key(p, k) |
| 61 | open(os.path.join(d, name), "wb").write(body) |
| 62 | idx.append("\t".join([name, k, p, str(st), ct, loc.replace(str(port), "PORT"), str(len(body)), |
| 63 | hashlib.sha256(body).hexdigest()])) |
| 64 | open(os.path.join(d, "index.tsv"), "w", encoding="utf-8").write("\n".join(idx) + "\n") |
| 65 | |
| 66 | |
| 67 | def index(d): |
| 68 | rows = {} |
| 69 | for l in open(os.path.join(d, "index.tsv"), encoding="utf-8"): |
| 70 | f = l.rstrip("\n").split("\t") |
| 71 | rows[f[0]] = f |
| 72 | return rows |
| 73 | |
| 74 | |
| 75 | def same(a, b): |
| 76 | A, B = index(a), index(b) |
| 77 | bad = 0 |
| 78 | for k, ra in A.items(): |
| 79 | rb = B.get(k) |
| 80 | if rb is None or ra[3:] != rb[3:]: |
| 81 | bad += 1 |
| 82 | print("DIFFER %s %s: %s / %s" % (ra[1], ra[2], ra[3:7], rb[3:7] if rb else None)) |
| 83 | print("pages=%d identical=%d differ=%d" % (len(A), len(A) - bad, bad)) |
| 84 | return 1 if bad or len(A) != len(B) else 0 |
| 85 | |
| 86 | |
| 87 | # radicle A B: the only differences STORE may show against MAIN. Every rule is a form that the kept |
| 88 | # listing of the run at babf1706 shows (differing-lines-babf1706080e75dff2f8dd412e0d62ecbc538d44.txt), |
| 89 | # and a STORE line is accepted only when it is exactly what the rule makes of the MAIN line or lines |
| 90 | # it replaces. No line passes for merely naming an id. A rule gets the MAIN lines, the STORE lines and |
| 91 | # the project name of the page; it returns None, or the (table, MAIN value, STORE value) pairs that |
| 92 | # must stay one to one over the whole run (a Radicle id and its store id, an owner and its key). |
| 93 | # ids: rad:z... (the Radicle build before the Radicle-text removal), a bare z... in a "rid" value (after it, |
| 94 | # c1f107df: the old id without its prefix), git:<64 hex> (the store build) |
| 95 | IDS = re.compile(r'rad:z[0-9A-Za-z]+|git:[0-9a-f]{64}|(?<="rid":")z[0-9A-Za-z]+') |
| 96 | RIDF = r'((?:<span translate="no">)?z[0-9A-Za-z]+(?:</span>)?)' # a Radicle id as an HTML page prints it |
| 97 | CODE = '<code translate="no">' |
| 98 | FOOT = ('<p class="foot-fine">INTERPLANE Forge: agents express intent; the forge retains authority. %s' |
| 99 | " served by forged, a seeded-Omega web server, with no JavaScript.</p>") |
| 100 | FOOT_A = FOOT % "Built on Radicle (Heartwood): repositories are Radicle projects" |
| 101 | FOOT_A2 = FOOT % "Repositories are" # the footer after the Radicle-text removal (c1f107df) |
| 102 | FOOT_B = FOOT % "Repositories are plain Git kept in Interplane's own signed store," |
| 103 | PATCH = "<dt>Patch</dt><dd>A proposed change, %s The list is under " |
| 104 | PATCH_A = PATCH % "sent over Radicle and reviewed before it is merged." |
| 105 | PATCH_B = PATCH % "reviewed before it is merged. This forge does not show proposed changes from its own store yet." |
| 106 | PANEL = '<div class="clone"><h3>Get this repository</h3><dl>' |
| 107 | PANEL_A = re.compile(PANEL + "<dt>Radicle</dt><dd>" + CODE + "rad clone rad:" + RIDF + "</code></dd>" |
| 108 | "(<dt>Git over HTTPS</dt><dd>" + CODE + r"git clone )https://www\.aienos\.com/rad/\1\.git" |
| 109 | "(</code></dd><dt>Source archive of .*)", re.S) |
| 110 | OBJECT_A = re.compile(r'"clone":\{"rad":"rad:(z[0-9A-Za-z]+)","rad_clone":"rad clone rad:\1",' |
| 111 | r'"git_https":"https://www\.aienos\.com/rad/\1\.git"(.*)', re.S) |
| 112 | STORE_GIT = "https://interplane.io/projects/%s/repo.git" |
| 113 | DEV_RID = re.compile(r"<dt>RID</dt><dd>The Radicle ID: the project's permanent name on Radicle, the open network" |
| 114 | r" that stores and signs it\. This one is " + CODE + "rad:" + RIDF + r"</code>\.</dd>") |
| 115 | DEV_DELEGATE = re.compile(r"<dt>Delegate</dt><dd>A key that may sign the project's official versions\. This forge" |
| 116 | r" lists the project under ([^;<]+); " + CODE + "rad inspect rad:" + RIDF + |
| 117 | r" --delegates</code> prints the project's own list\.</dd>") |
| 118 | DEV_SEED = ("<dt>Seed</dt><dd>A Radicle node that keeps a copy of the project and serves it to others. The count" |
| 119 | " below is read from this node's routing table.</dd>") |
| 120 | DEV_ID = (r"<dt>ID</dt><dd>The project's permanent id on Interplane: the SHA-256 of its first signed record\." |
| 121 | " This one is " + CODE + r'git:<span translate="no">([0-9a-f]{64})</span></code>\. Its old Radicle ID,' |
| 122 | " kept only so that old links still work: " + CODE + r"rad:%s</code>\.</dd>") |
| 123 | DEV_OWNER = (r"<dt>Owner</dt><dd>The key that signs every record of the project\. This forge lists the project" |
| 124 | " under %s; its key is " + CODE + r"(SHA256:[A-Za-z0-9+/]{43})</code>\.</dd>") |
| 125 | |
| 126 | |
| 127 | def project(path): |
| 128 | f = path.split("?")[0].split("/") |
| 129 | n = f[2] if len(f) > 2 else "" |
| 130 | return n[:-5] if len(f) == 3 and n.endswith(".json") else n |
| 131 | |
| 132 | |
| 133 | def r_ids(a, b, name): |
| 134 | # the same line with a Radicle id where STORE has the store id; ids equal on both sides stay as they are |
| 135 | if IDS.split(a[0]) != IDS.split(b[0]): |
| 136 | return None |
| 137 | d = [(x, y) for x, y in zip(IDS.findall(a[0]), IDS.findall(b[0])) if x != y] |
| 138 | if not d or not all(x.startswith(("rad:", "z")) and y.startswith("git:") for x, y in d): |
| 139 | return None |
| 140 | # a bare old id (MAIN after c1f107df) is the same id as rad:<it>: one name for the one-to-one check |
| 141 | return [("id", x if x.startswith("rad:") else "rad:" + x, y) for x, y in d] |
| 142 | |
| 143 | |
| 144 | def r_nav(a, b, name): |
| 145 | return [] if SEAM in a[0] and '<nav class="forge-nav"' in a[0] and a[0].replace(SEAM, "") == b[0] else None |
| 146 | |
| 147 | |
| 148 | def r_footer(a, b, name): |
| 149 | return [] if a[0] in (FOOT_A, FOOT_A2) and b[0] == FOOT_B else None |
| 150 | |
| 151 | |
| 152 | def r_patch(a, b, name): |
| 153 | return [] if a[0].startswith(PATCH_A) and b[0] == PATCH_B + a[0][len(PATCH_A):] else None |
| 154 | |
| 155 | |
| 156 | def r_panel(a, b, name): |
| 157 | m = PANEL_A.fullmatch(a[0]) |
| 158 | return [] if m and name and b[0] == PANEL + m.group(2) + STORE_GIT % name + m.group(3) else None |
| 159 | |
| 160 | |
| 161 | def r_object(a, b, name): |
| 162 | m = OBJECT_A.fullmatch(a[0]) |
| 163 | want = '"clone":{"rad":null,"rad_clone":null,"git_https":"' + STORE_GIT % name + '"' |
| 164 | return [] if m and name and b[0] == want + m.group(2) else None |
| 165 | |
| 166 | |
| 167 | def r_dev(a, b, name): |
| 168 | # RID, Delegate and Seed rows of MAIN; ID and Owner rows of STORE, naming the same Radicle id and owner |
| 169 | r, d = DEV_RID.fullmatch(a[0]), DEV_DELEGATE.fullmatch(a[1]) |
| 170 | if not r or not d or d.group(2) != r.group(1) or a[2] != DEV_SEED: |
| 171 | return None |
| 172 | i = re.fullmatch(DEV_ID % re.escape(r.group(1)), b[0]) |
| 173 | o = re.fullmatch(DEV_OWNER % re.escape(d.group(1)), b[1]) |
| 174 | p = owner_pair(name, d.group(1), o.group(1)) if i and o else None |
| 175 | if not p: |
| 176 | return None |
| 177 | return [("id", "rad:" + re.sub(r"</?span[^>]*>", "", r.group(1)), "git:" + i.group(1)), p] |
| 178 | |
| 179 | |
| 180 | # ---- the forms of MAIN after the Radicle-text removal (c1f107df, merged as restore-rad-free 9a4420ab): |
| 181 | # MAIN no longer names Radicle, so its lines that the store build replaces are these instead. |
| 182 | DEV_DELEGATE2 = re.compile(r"<dt>Delegate</dt><dd>A key that may sign the project's official versions\. This forge" |
| 183 | r" lists the project under ([^;<.]+)\.</dd>") |
| 184 | DEV_ID2 = re.compile(r"<dt>ID</dt><dd>The project's permanent id on Interplane: the SHA-256 of its first signed record\." |
| 185 | " This one is " + CODE + r'git:<span translate="no">([0-9a-f]{64})</span></code>\. Its old id, kept' |
| 186 | " only so that old links still work: " + CODE + r'(?:<span translate="no">)?(z[0-9A-Za-z]+)(?:</span>)?</code>\.</dd>') |
| 187 | PATCH_A2 = PATCH % "stored in the repository and reviewed before it is merged." |
| 188 | SEED_A2 = '<p class="meta">Seeding: <b>not measured</b> (the source of this count is retired)</p>' |
| 189 | PANEL_A2 = re.compile(re.escape(PANEL[:-4]) + r'<p class="meta">No public Git URL yet: Interplane does not serve Git' |
| 190 | r' clones yet\.</p><dl>(<dt>Source archive of .*)', re.S) |
| 191 | AGENT_A2 = '<p class="meta">For agents: ' + CODE + "forge-contribute " |
| 192 | OBJECT_A2 = re.compile(r'"clone":\{"rad":"(z[0-9A-Za-z]+)","rad_clone":null,"git_https":null\}(.*)', re.S) |
| 193 | |
| 194 | |
| 195 | def r_dev2(a, b, name): |
| 196 | # the Delegate row of MAIN; the ID and Owner rows of STORE, naming the same owner |
| 197 | d = DEV_DELEGATE2.fullmatch(a[0]) |
| 198 | i = DEV_ID2.fullmatch(b[0]) |
| 199 | if not d or not i: |
| 200 | return None |
| 201 | o = re.fullmatch(DEV_OWNER % re.escape(d.group(1)), b[1]) |
| 202 | p = owner_pair(name, d.group(1), o.group(1)) if o else None |
| 203 | if not p: |
| 204 | return None |
| 205 | return [("id", "rad:" + i.group(2), "git:" + i.group(1)), p] |
| 206 | |
| 207 | |
| 208 | def r_patch2(a, b, name): |
| 209 | return [] if a[0].startswith(PATCH_A2) and b[0] == PATCH_B + a[0][len(PATCH_A2):] else None |
| 210 | |
| 211 | |
| 212 | def r_seed2(a, b, name): |
| 213 | # the seeding line of MAIN (its source, the node's routing table, is retired); the store build has none |
| 214 | return [] if a[0] == SEED_A2 else None |
| 215 | |
| 216 | |
| 217 | def r_panel2(a, b, name): |
| 218 | # MAIN's panel without a Git URL and its closed agent line; STORE's panel with the store's HTTPS URL |
| 219 | m = PANEL_A2.fullmatch(a[0]) |
| 220 | if not m or not name or not a[1].startswith(AGENT_A2): |
| 221 | return None |
| 222 | want = PANEL + "<dt>Git over HTTPS</dt><dd>" + CODE + "git clone " + STORE_GIT % name + "</code></dd>" + m.group(1) |
| 223 | return [] if b[0] == want else None |
| 224 | |
| 225 | |
| 226 | def r_object2(a, b, name): |
| 227 | m = OBJECT_A2.fullmatch(a[0]) |
| 228 | want = '"clone":{"rad":null,"rad_clone":null,"git_https":"' + STORE_GIT % name + '"}' |
| 229 | return [] if m and name and b[0] == want + m.group(2) else None |
| 230 | |
| 231 | |
| 232 | RULES = (("dev-rows", 3, 2, r_dev), ("nav", 1, 1, r_nav), ("footer", 1, 1, r_footer), ("dev-patch-row", 1, 1, r_patch), |
| 233 | ("clone-panel", 1, 1, r_panel), ("clone-object", 1, 1, r_object), |
| 234 | ("dev-rows-2", 1, 2, r_dev2), ("dev-patch-row-2", 1, 1, r_patch2), ("seeding-2", 1, 0, r_seed2), |
| 235 | ("clone-panel-2", 2, 1, r_panel2), ("clone-object-2", 1, 1, r_object2), ("id", 1, 1, r_ids)) |
| 236 | |
| 237 | |
| 238 | def state(): |
| 239 | return {"n": dict.fromkeys([r[0] for r in RULES], 0), "pairs": {}} |
| 240 | |
| 241 | |
| 242 | def clash(st, pairs, where): |
| 243 | # a value paired with one value here and another elsewhere is a difference, not a form |
| 244 | for t, x, y in pairs: |
| 245 | for side, p, q in ((t + " of MAIN", x, y), (t + " of STORE", y, x)): |
| 246 | seen = st["pairs"].get((side, p)) |
| 247 | if seen and seen[0] != q: |
| 248 | return "%s %s goes with %s here and with %s at %s" % (side, p, q, seen[0], seen[1]) |
| 249 | for t, x, y in pairs: |
| 250 | st["pairs"].setdefault((t + " of MAIN", x), (y, where)) |
| 251 | st["pairs"].setdefault((t + " of STORE", y), (x, where)) |
| 252 | return None |
| 253 | |
| 254 | |
| 255 | def block(where, path, rem, add, st): |
| 256 | # rem, add: the (number, line) lists of one differing block of MAIN and of STORE. One |
| 257 | # (sign, number, rule, line, reason) comes back per line; rule None is a line that nothing accepts. |
| 258 | out, i, j, name = [], 0, 0, project(path) |
| 259 | while i < len(rem) or j < len(add): |
| 260 | hit = why = None |
| 261 | for cls, n, m, rule in RULES: |
| 262 | if len(rem) - i < n or len(add) - j < m: |
| 263 | continue |
| 264 | pairs = rule([l for _, l in rem[i:i + n]], [l for _, l in add[j:j + m]], name) |
| 265 | if pairs is None: |
| 266 | continue |
| 267 | why = clash(st, pairs, "%s line %d" % (where, rem[i][0])) |
| 268 | hit = None if why else (cls, n, m) |
| 269 | break |
| 270 | if hit: |
| 271 | cls, n, m = hit |
| 272 | st["n"][cls] += 1 |
| 273 | out += [("-", k, cls, l, None) for k, l in rem[i:i + n]] |
| 274 | out += [("+", k, cls, l, None) for k, l in add[j:j + m]] |
| 275 | i, j = i + n, j + m |
| 276 | elif i < len(rem): |
| 277 | out.append(("-", rem[i][0], None, rem[i][1], why or "no listed rule gives this MAIN line a STORE line")) |
| 278 | i += 1 |
| 279 | else: |
| 280 | out.append(("+", add[j][0], None, add[j][1], why or "no listed rule produces this STORE line")) |
| 281 | j += 1 |
| 282 | return out |
| 283 | |
| 284 | |
| 285 | def tally(st): |
| 286 | return " ".join("%s=%d" % (r[0], st["n"][r[0]]) for r in RULES) |
| 287 | |
| 288 | |
| 289 | def radicle(a, b): |
| 290 | A, B = index(a), index(b) |
| 291 | st = state() |
| 292 | bad = ok = fine = 0 |
| 293 | for k, ra in A.items(): |
| 294 | rb = B.get(k) |
| 295 | where = "%s %s" % (ra[1], ra[2]) |
| 296 | if rb is None: |
| 297 | bad += 1 |
| 298 | print("BAD page missing from STORE %s" % where) |
| 299 | continue |
| 300 | if ra[3:6] != rb[3:6]: |
| 301 | bad += 1 |
| 302 | print("BAD status/type/location %s: %s / %s" % (where, ra[3:6], rb[3:6])) |
| 303 | continue |
| 304 | if ra[7] == rb[7]: |
| 305 | ok += 1 |
| 306 | continue |
| 307 | ba = open(os.path.join(a, k), "rb").read() |
| 308 | bb = open(os.path.join(b, k), "rb").read() |
| 309 | if not (ra[4].startswith("text/html") or ra[4].startswith(JSON)): |
| 310 | bad += 1 |
| 311 | print("BAD bytes differ in a non-text page %s (%s)" % (where, ra[4])) |
| 312 | continue |
| 313 | la = ba.decode("utf-8", "replace").split("\n") |
| 314 | lb = bb.decode("utf-8", "replace").split("\n") |
| 315 | print("DIFF %s" % where) |
| 316 | refused = 0 |
| 317 | for op, i1, i2, j1, j2 in difflib.SequenceMatcher(None, la, lb, autojunk=False).get_opcodes(): |
| 318 | if op == "equal": |
| 319 | continue |
| 320 | rem, add = list(enumerate(la[i1:i2], i1 + 1)), list(enumerate(lb[j1:j2], j1 + 1)) |
| 321 | for sign, num, cls, l, why in block(where, ra[2], rem, add, st): |
| 322 | print(" %s [%s] %s" % (sign, cls or "NOT ACCEPTED", l)) |
| 323 | if not cls: |
| 324 | refused += 1 |
| 325 | print("BAD %s line %d of %s: %s" % (where, num, "MAIN" if sign == "-" else "STORE", why)) |
| 326 | if refused: |
| 327 | bad += 1 |
| 328 | else: |
| 329 | fine += 1 |
| 330 | for k, rb in B.items(): |
| 331 | if k not in A: |
| 332 | bad += 1 |
| 333 | print("BAD page only in STORE %s %s" % (rb[1], rb[2])) |
| 334 | print("pages=%d identical=%d differing-by-listed-rules-only=%d bad=%d %s" % (len(A), ok, fine, bad, tally(st))) |
| 335 | return 1 if bad or len(A) != len(B) else 0 |
| 336 | |
| 337 | |
| 338 | def replay(listing): |
| 339 | # The rules over a kept `radicle` listing in the format of the run at babf1706: a "DIFF kind path" |
| 340 | # line per page, then " - " MAIN lines and " + " STORE lines, with "[SEAM open] " before a nav |
| 341 | # pair. A MAIN line after STORE lines starts the next block. Line numbers are the listing's. Status, |
| 342 | # type, location, non-text bytes and the identical pages are not in a listing, so they are not replayed. |
| 343 | st = state() |
| 344 | blocks, other, nmain, nstore = [], [], 0, 0 |
| 345 | for n, l in enumerate(open(listing, encoding="utf-8", newline="").read().split("\n"), 1): |
| 346 | if l.startswith("DIFF "): |
| 347 | blocks.append((l[5:], True, [], [])) |
| 348 | elif l[:4] in (" - ", " + ") and blocks: |
| 349 | t = l[4:] |
| 350 | t = t[12:] if t.startswith("[SEAM open] ") else t |
| 351 | if l[2] == "-" and blocks[-1][3]: |
| 352 | blocks.append((blocks[-1][0], False, [], [])) |
| 353 | blocks[-1][2 if l[2] == "-" else 3].append((n, t)) |
| 354 | nmain, nstore = nmain + (l[2] == "-"), nstore + (l[2] == "+") |
| 355 | elif l and not l.startswith("pages="): |
| 356 | other.append(n) |
| 357 | pages, badpages, refused = 0, set(), 0 |
| 358 | for where, first, rem, add in blocks: |
| 359 | pages += first |
| 360 | for sign, num, cls, l, why in block(where, where.split(" ", 1)[1], rem, add, st): |
| 361 | if not cls: |
| 362 | refused += 1 |
| 363 | badpages.add(pages) |
| 364 | print("REFUSED listing line %d (%s of %s): %s: %s" % (num, "MAIN" if sign == "-" else "STORE", where, |
| 365 | why, l[:160])) |
| 366 | badpages = len(badpages) |
| 367 | for n in other: |
| 368 | print("UNREAD listing line %d" % n) |
| 369 | print("replay: differing-pages=%d accepted=%d refused=%d lines-main=%d lines-store=%d lines-refused=%d " |
| 370 | "unread-lines=%d %s" % (pages, pages - badpages, badpages, nmain, nstore, refused, len(other), tally(st))) |
| 371 | return 1 if refused or other else 0 |
| 372 | |
| 373 | |
| 374 | def sample(catalog, projects, fixture): |
| 375 | names = [l.split("\t")[0] for l in open(catalog, encoding="utf-8") if l.strip()] |
| 376 | others = [n for n in names if n != fixture] |
| 377 | |
| 378 | def size(n): |
| 379 | t = 0 |
| 380 | for r, _, fs in os.walk(os.path.join(projects, n, "repo.git")): |
| 381 | for f in fs: |
| 382 | t += os.lstat(os.path.join(r, f)).st_size |
| 383 | return t |
| 384 | largest = max(others, key=size) |
| 385 | rest = sorted([n for n in others if n != largest], key=lambda n: hashlib.sha256(n.encode()).hexdigest()) |
| 386 | for n in [largest, fixture] + rest[:9]: |
| 387 | print(n) |
| 388 | |
| 389 | |
| 390 | def manylines(catalog, n): |
| 391 | first = open(catalog, encoding="utf-8").readline() |
| 392 | for i in range(int(n)): |
| 393 | nm = "many-%03d" % i |
| 394 | print("\t".join([nm, hashlib.sha256(nm.encode()).hexdigest(), "main", "none", "public"])) |
| 395 | |
| 396 | |
| 397 | def did(pub): |
| 398 | blob = base64.b64decode(open(pub).read().split()[1]) |
| 399 | raw = b"\xed\x01" + blob[-32:] |
| 400 | alpha = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" |
| 401 | v = int.from_bytes(raw, "big") |
| 402 | s = "" |
| 403 | while v: |
| 404 | v, r = divmod(v, 58) |
| 405 | s = alpha[r] + s |
| 406 | return "did:key:z" + s |
| 407 | |
| 408 | |
| 409 | def field(body, name): |
| 410 | m = re.search(r'name="%s" value="([^"]*)"' % name, body) |
| 411 | return m.group(1) if m else "" |
| 412 | |
| 413 | |
| 414 | def cookie(headers, suffix): |
| 415 | for h, v in headers: |
| 416 | if h.lower() == "set-cookie": |
| 417 | m = re.match(r"([A-Za-z_-]*%s)=([0-9a-f]*);" % suffix, v) |
| 418 | if m: |
| 419 | return m.group(1), m.group(2) |
| 420 | return None, None |
| 421 | |
| 422 | |
| 423 | def post(port, path, form, hdr): |
| 424 | c = http.client.HTTPConnection("127.0.0.1", port, timeout=60) |
| 425 | h = {"Content-Type": "application/x-www-form-urlencoded"} |
| 426 | h.update(hdr) |
| 427 | c.request("POST", path, urllib.parse.urlencode(form), h) |
| 428 | r = c.getresponse() |
| 429 | r.read() |
| 430 | out = (r.status, r.getheaders()) |
| 431 | c.close() |
| 432 | return out |
| 433 | |
| 434 | |
| 435 | def signin(port, keyf): |
| 436 | st, _, _, body, hs = get(port, "/login") |
| 437 | body = body.decode() |
| 438 | pn, pre = cookie(hs, "forge_pre") |
| 439 | nonce, ts, csrf = field(body, "nonce"), field(body, "ts"), field(body, "csrf") |
| 440 | sig = subprocess.run(["ssh-keygen", "-Y", "sign", "-f", keyf, "-n", "interplane-forge"], |
| 441 | input=("interplane-forge-login:%s:%s" % (nonce, ts)).encode(), |
| 442 | capture_output=True).stdout.decode() |
| 443 | st, hs = post(port, "/login", {"csrf": csrf, "nonce": nonce, "ts": ts, "did": did(keyf + ".pub"), "sig": sig}, |
| 444 | {"Cookie": "%s=%s" % (pn, pre)}) |
| 445 | sn, ses = cookie(hs, "forge_session") |
| 446 | print("%s=%s" % (sn, ses) if st == 303 and ses else "SIGNIN-FAILED %d" % st) |
| 447 | |
| 448 | |
| 449 | def star(port, ses, repo): |
| 450 | st, _, _, body, _ = get(port, "/settings", {"Cookie": ses}) |
| 451 | csrf = field(body.decode(), "csrf") |
| 452 | st, _ = post(port, "/%s/%s/star" % (OWNER, repo), {"csrf": csrf}, {"Cookie": ses}) |
| 453 | print(st) |
| 454 | |
| 455 | |
| 456 | def stars(port, repo): |
| 457 | st, _, _, body, _ = get(port, "/%s/%s/stargazers" % (OWNER, repo), {"Accept": JSON}) |
| 458 | print(json.loads(body)["count"] if st == 200 else "status-%d" % st) |
| 459 | |
| 460 | |
| 461 | def main(): |
| 462 | c, a = sys.argv[1], sys.argv[2:] |
| 463 | if c == "sample": |
| 464 | sample(*a) |
| 465 | elif c == "fetch": |
| 466 | fetch(int(a[0]), a[1], a[2]) |
| 467 | elif c == "key": |
| 468 | print(key(a[0], a[1])) |
| 469 | elif c == "same": |
| 470 | sys.exit(same(*a)) |
| 471 | elif c == "radicle": |
| 472 | sys.exit(radicle(*a)) |
| 473 | elif c == "replay": |
| 474 | sys.exit(replay(*a)) |
| 475 | elif c == "manylines": |
| 476 | manylines(*a) |
| 477 | elif c == "signin": |
| 478 | signin(int(a[0]), a[1]) |
| 479 | elif c == "star": |
| 480 | star(int(a[0]), a[1], a[2]) |
| 481 | elif c == "stars": |
| 482 | stars(int(a[0]), a[1]) |
| 483 | else: |
| 484 | sys.exit("compare.py: unknown command " + c) |
| 485 | |
| 486 | |
| 487 | if __name__ == "__main__": |
| 488 | main() |