#!/usr/bin/env python3 """Link extraction for the npm release cascades. A link goes from an upstream release U to a dependent release W when W changes the declared dependency range of the upstream package so that the lowest version allowed by the range rises and equals exactly the version of U, and U was published 0 to 30 days before W. Inside one repository the link has kind 'hand_off', otherwise 'dependency'. The lowest version of a range is computed with the semver library of npm (minVersion, loose mode); the table range -> lowest version is part of the input ("range_lowest_version"). Usage: python build_links.py [--input input_events.json] [--output output_links.json] Only the Python standard library is needed. """ import argparse, collections, datetime as dt, json, re def secs(t): return int(dt.datetime.fromisoformat(t.replace('Z', '+00:00')).timestamp()) def stamp(t): return dt.datetime.fromisoformat(t.replace('Z', '+00:00')).timestamp() def norm_repo(u): u = u.lower().strip(); u = re.sub(r'^git\+', '', u); u = re.sub(r'\.git$', '', u) u = re.sub(r'^(ssh://)?git@github\.com[:/]', 'https://github.com/', u) return u.replace('git://', 'https://').replace('http://', 'https://').replace('www.', '') def build_links(inp): lo, hi = inp['window']['start'], inp['window']['end'] # compared as strings with the ISO time stamps max_gap = inp['parameters']['max_gap_days'] lowest = inp['range_lowest_version'] pkgs = inp['packages'] by_pkg = collections.defaultdict(list) for e in inp['events']: by_pkg[e['package']].append(e) for p in by_pkg: by_pkg[p].sort(key=lambda r: r['time']) # releases of a package in time order in_window = {} # (package, version) -> release inside the window for p, rel in by_pkg.items(): for r in rel: if lo <= r['time'] < hi: in_window[(p, r['version'])] = r found = {} for p, rel in by_pkg.items(): repo_p = norm_repo(pkgs[p]['repo']) for i, w in enumerate(rel): if not (lo <= w['time'] < hi) or i == 0: # only releases inside the window that have a predecessor continue prev = rel[i - 1] for a, rng in w['deps'].items(): if a not in pkgs or a == p: # dependencies on packages of the sample only continue before = prev['deps'].get(a) if before is None or before == rng: # the range must have changed continue m = lowest.get(rng) if not m or lowest.get(before) == m: # and its lowest version must have moved continue u = in_window.get((a, m)) # upstream release with exactly that version if u is None: continue days = (stamp(w['time']) - stamp(u['time'])) / 86400 if days <= 0 or days > max_gap: continue repo_a = norm_repo(pkgs[a]['repo']) same = bool(repo_a) and repo_a == repo_p found[(u['id'], w['id'])] = (u, w, same, a, rng, before, m, days) links = [] for (uid, wid), (u, w, same, a, rng, before, m, days) in found.items(): gs = secs(w['time']) - secs(u['time']) l = {'id': f'{uid}>{wid}', 'from': uid, 'to': wid, 'kind': 'hand_off' if same else 'dependency', 'propagates': True, 'direction': 'evidence' if gs == 0 else 'time', 'gap_seconds': gs, 'evidence': {'existence': {'level': 'rule', 'basis': 'manifest_diff', 'rule_id': 'R_MIN_VERSION_RAISED', 'text': f"{w['package']} {w['version']} raises its range for {a} from {before} to {rng}, whose lowest version is {m}; {a} {m} was published {days:.2f} days earlier", 'source_ref': {'source': 'npm_registry', 'id': wid}}}, 'attrs': {'dependency': a, 'range_before': before, 'range_after': rng, 'lowest_version': m}} if same: l['flags'] = ['same_owner'] links.append(l) links.sort(key=lambda l: (l['from'], l['to'], l['kind'], l.get('relation', ''))) # order of the package return links def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('--input', default='input_events.json'); ap.add_argument('--output', default='output_links.json') a = ap.parse_args() inp = json.load(open(a.input, encoding='utf8')) links = build_links(inp) out = {'spec_version': '0.1', 'package_id': inp['package_id'], 'link_count': len(links), 'propagating_links': len(links), 'omitted_counts': {}, 'links': links, 'omitted': []} json.dump(out, open(a.output, 'w', encoding='utf8'), ensure_ascii=False, separators=(',', ':')) print(f'{len(links)} links ({sum(1 for l in links if l["kind"] == "hand_off")} hand_off) -> {a.output}') if __name__ == '__main__': main()