返回 CodeWhale
report-contribution-cohorts.mjs
根目录 / telemetry-ingest / scripts / report-contribution-cohorts.mjs
1 #!/usr/bin/env node
2 import { readFileSync } from "node:fs";
3 import { execFile } from "node:child_process";
4 import { promisify } from "node:util";
5 import { pathToFileURL } from "node:url";
6
7 const run = promisify(execFile);
8 const REPOSITORY = "codewhale-hq/CodeWhale";
9 const MAX_PAGES = 100;
10 const MAX_ITEMS = MAX_PAGES * 100;
11
12 function date(value, field) {
13 if (typeof value !== "string" || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(value) || !Number.isFinite(Date.parse(value))) throw new Error(`invalid ${field}`);
14 return new Date(value);
15 }
16 function isPerson(user) {
17 return user && user.type === "User" && Number.isSafeInteger(user.id) && user.id > 0;
18 }
19
20 export function contributionCohorts(snapshot, { from = "1970-01-01T00:00:00Z", to = new Date().toISOString().slice(0, 19) + "Z" } = {}) {
21 if (!snapshot || snapshot.format !== "codewhale-public-contributions-v1" || snapshot.repository?.toLowerCase() !== REPOSITORY.toLowerCase() || !["github-public-api", "synthetic"].includes(snapshot.source)) throw new Error("unsupported public contribution receipt");
22 if (snapshot.coverage?.issues_complete !== true || snapshot.coverage?.pulls_complete !== true) throw new Error("incomplete GitHub pagination; earliest contribution unavailable");
23 if (!Array.isArray(snapshot.issues) || !Array.isArray(snapshot.pulls) || snapshot.issues.length > MAX_ITEMS || snapshot.pulls.length > MAX_ITEMS) throw new Error("missing or oversized GitHub history");
24 const start = date(from, "from"); const end = date(to, "to");
25 if (start >= end) throw new Error("from must precede to");
26 const issueAuthors = new Map(); const pullAuthors = new Map();
27 let botOrDeleted = 0; let issueCount = 0; let mergedCount = 0;
28 const issueNumbers = new Set(); const pullNumbers = new Set();
29 for (const issue of snapshot.issues) {
30 if (!Number.isSafeInteger(issue.number) || issue.number < 1) throw new Error("invalid issue number");
31 if (issueNumbers.has(issue.number)) continue;
32 issueNumbers.add(issue.number);
33 if (issue.pull_request) continue;
34 if (!isPerson(issue.user)) { botOrDeleted++; continue; }
35 const at = date(issue.created_at, "issue created_at");
36 const id = issue.user.id; issueCount++;
37 if (!issueAuthors.has(id) || at < issueAuthors.get(id)) issueAuthors.set(id, at);
38 }
39 for (const pull of snapshot.pulls) {
40 if (!Number.isSafeInteger(pull.number) || pull.number < 1) throw new Error("invalid pull number");
41 if (pullNumbers.has(pull.number)) continue;
42 pullNumbers.add(pull.number);
43 if (!pull.merged_at) continue;
44 if (!isPerson(pull.user)) { botOrDeleted++; continue; }
45 const at = date(pull.merged_at, "pull merged_at");
46 const id = pull.user.id; mergedCount++;
47 if (!pullAuthors.has(id) || at < pullAuthors.get(id)) pullAuthors.set(id, at);
48 }
49 const days = new Map();
50 const add = (at, key) => {
51 if (at < start || at >= end) return;
52 const day = at.toISOString().slice(0, 10);
53 const row = days.get(day) ?? { day, first_public_issue_authors: 0, first_merged_pr_authors: 0 };
54 row[key]++; days.set(day, row);
55 };
56 for (const at of issueAuthors.values()) add(at, "first_public_issue_authors");
57 for (const at of pullAuthors.values()) add(at, "first_merged_pr_authors");
58 const daily = [...days.values()].sort((a, b) => a.day.localeCompare(b.day));
59 return {
60 report: "codewhale_public_contribution_cohorts", repository: REPOSITORY, source: snapshot.source, synthetic: snapshot.source === "synthetic",
61 coverage: { from, to, issues_complete: true, pulls_complete: true, accessible_public_history_only: true },
62 input_counts: { public_issues: issueCount, merged_prs: mergedCount, excluded_bot_or_deleted_records: botOrDeleted },
63 totals: { first_public_issue_authors: daily.reduce((sum, row) => sum + row.first_public_issue_authors, 0), first_merged_pr_authors: daily.reduce((sum, row) => sum + row.first_merged_pr_authors, 0) },
64 days: daily,
65 caveats: [
66 "First means earliest in the complete accessible public repository export, not first open-source contribution anywhere. Deleted or inaccessible history cannot be recovered.",
67 "First public issue authors and first merged PR authors are separate cohorts; this report does not attribute them to website visits, install IDs or runtime tasks.",
68 "Stable public author IDs are used only in memory to aggregate the export. Output contains no author identities, content, account profile or attribution join.",
69 "Paginated API reads are not an atomic snapshot. The export is bounded and fails rather than declaring incomplete history complete.",
70 ],
71 };
72 }
73
74 export async function exportPublicHistory({ get = githubGet, maxPages = MAX_PAGES } = {}) {
75 if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > MAX_PAGES) throw new Error("maxPages must be between 1 and 100");
76 const repo = await get(`repos/${REPOSITORY}`);
77 if (repo.private !== false) throw new Error("repository must be verified public before exporting history");
78 const paginate = async (endpoint) => {
79 const records = [];
80 for (let page = 1; page <= maxPages; page++) {
81 const batch = await get(`${endpoint}&per_page=100&page=${page}`);
82 if (!Array.isArray(batch) || batch.length > 100) throw new Error("malformed GitHub page");
83 records.push(...batch);
84 if (batch.length < 100) return records;
85 }
86 throw new Error("incomplete GitHub pagination at bounded page limit; no cohort report generated");
87 };
88 const issues = await paginate(`repos/${REPOSITORY}/issues?state=all&sort=created&direction=asc`);
89 const pulls = await paginate(`repos/${REPOSITORY}/pulls?state=all&sort=created&direction=asc`);
90 return { format: "codewhale-public-contributions-v1", repository: REPOSITORY, source: "github-public-api", coverage: { issues_complete: true, pulls_complete: true }, issues, pulls };
91 }
92
93 async function githubGet(endpoint) {
94 try {
95 const { stdout } = await run("gh", ["api", endpoint], { maxBuffer: 8 * 1024 * 1024, timeout: 30_000 });
96 return JSON.parse(stdout);
97 } catch {
98 throw new Error("GitHub API read failed; no credentials or response content were printed");
99 }
100 }
101
102 export async function main(argv = process.argv.slice(2)) {
103 let input; let from; let to;
104 for (let i = 0; i < argv.length; i++) {
105 const flag = argv[i]; const value = argv[++i];
106 if (!value || value.startsWith("--")) throw new Error("missing contribution report option");
107 if (flag === "--input") input = value;
108 else if (flag === "--from") from = value;
109 else if (flag === "--to") to = value;
110 else throw new Error("unknown contribution report option");
111 }
112 const snapshot = input ? JSON.parse(readFileSync(input, "utf8")) : await exportPublicHistory();
113 return contributionCohorts(snapshot, { from, to });
114 }
115
116 if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
117 main().then((report) => process.stdout.write(`${JSON.stringify(report, null, 2)}\n`)).catch((error) => { process.stderr.write(`report:contributions: ${error instanceof SyntaxError ? "invalid JSON receipt" : error.message}\n`); process.exitCode = 1; });
118 }
119
119 lines Plain Text