-
Notifications
You must be signed in to change notification settings - Fork 30.4k
Expand file tree
/
Copy pathghostbuster.js
More file actions
195 lines (178 loc) · 6.06 KB
/
Copy pathghostbuster.js
File metadata and controls
195 lines (178 loc) · 6.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { Octokit } from "octokit";
/** @type {<T, U>(array: readonly T[] | undefined, mapfn: (x: T, i: number) => readonly U[]) => readonly U[]} */
function flatMap(array, mapfn) {
const result = [];
if (array) {
for (let i = 0; i < array.length; i++) {
result.push(...mapfn(array[i], i));
}
}
return result;
}
/** @type {<T, U>(arr: Iterable<T>, mapper: (t: T) => U | undefined) => U[]} */
function mapDefined(arr, mapper) {
const out = [];
for (const a of arr) {
const res = mapper(a);
if (res !== undefined) {
out.push(res);
}
}
return out;
}
/**
* @typedef {{ githubUsername?: string }} Owner
* @typedef {{ owners: Owner[]; raw: string; }} PackageInfo
*/
void 0;
/**
* @param {string} packageJsonPath
* @param {PackageInfo} info
* @param {Set<string>} ghosts
*/
function bust(packageJsonPath, info, ghosts) {
/** @param {Owner} c */
const isGhost = c => c.githubUsername && ghosts.has(c.githubUsername.toLowerCase());
if (info.owners.some(isGhost)) {
console.error(`Found one or more deleted accounts in ${packageJsonPath}. Patching...`);
const parsed = JSON.parse(info.raw);
parsed.owners = info.owners.filter(c => !isGhost(c));
const newContent = JSON.stringify(parsed, undefined, 4);
writeFileSync(packageJsonPath, newContent + "\n", "utf-8");
}
}
/**
* @param {URL} dir
* @param {(subpath: URL) => void} fn
*/
function recurse(dir, fn) {
const entryPoints = readdirSync(dir, { withFileTypes: true });
for (const subdir of entryPoints) {
if (subdir.isDirectory() && subdir.name !== "node_modules") {
const subpath = new URL(`${subdir.name}/`, dir);
fn(subpath);
recurse(subpath, fn);
}
}
}
function getAllPackageJsons() {
/** @type {Record<string, PackageInfo>} */
const headers = {};
console.error("Reading headers...");
recurse(new URL("../types/", import.meta.url), subpath => {
const index = new URL("package.json", subpath);
if (existsSync(index)) {
const indexContent = readFileSync(index, "utf-8");
let parsed;
try {
parsed = JSON.parse(indexContent);
} catch (e) {}
if (parsed && parsed.owners && Array.isArray(parsed.owners)) {
headers[index.pathname] = { owners: parsed.owners, raw: indexContent };
}
}
});
return headers;
}
/**
* @param {Set<string>} users
*/
async function fetchGhosts(users) {
console.error("Checking for deleted accounts...");
const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });
const maxPageSize = 500;
const pages = Math.ceil(users.size / maxPageSize);
const userArray = Array.from(users);
/** @type string[] */
const ghosts = [];
for (let page = 0; page < pages; page++) {
const startIndex = page * maxPageSize;
const endIndex = Math.min(startIndex + maxPageSize, userArray.length);
const query = `query {
${userArray.slice(startIndex, endIndex).map((user, i) => `u${i}: user(login: "${user}") { id }`).join("\n")}
}`;
const result = await tryGQL(() => octokit.graphql(query));
for (const k in result) {
if (result[k] === null) {
ghosts.push(userArray[startIndex + parseInt(k.substring(1), 10)]);
}
}
}
// Filter out organizations
if (ghosts.length) {
const query = `query {
${ghosts.map((user, i) => `o${i}: organization(login: "${user}") { id }`).join("\n")}
}`;
const result = await tryGQL(() => octokit.graphql(query));
if (result) {
return new Set(ghosts.filter(g => result[`o${ghosts.indexOf(g)}`] === null));
}
}
return new Set(ghosts);
}
/**
* @param {() => Promise<any>} fn
*/
async function tryGQL(fn) {
try {
const result = await fn();
if (result.data) return result.data;
return result;
// @ts-expect-error
} catch (/** @type {{}} */ resultWithErrors) {
if (resultWithErrors.data) {
return resultWithErrors.data;
}
throw resultWithErrors;
}
}
process.on("unhandledRejection", err => {
console.error(err);
process.exit(1);
});
(async () => {
if (!process.env.GITHUB_TOKEN) {
throw new Error("GITHUB_TOKEN environment variable is not set");
}
const packageJsons = getAllPackageJsons();
const users = new Set(
flatMap(Object.values(packageJsons), h => mapDefined(h.owners, c => c.githubUsername?.toLowerCase())),
);
const ghosts = await fetchGhosts(users);
if (!ghosts.size) {
console.error("No ghosts found");
return;
}
const renames = [];
for (const oldName of ghosts) {
try {
const result = await fetch(`https://github.com/${oldName}/DefinitelyTyped`, { method: "HEAD" });
const url = new URL(result.url);
const newName = url.pathname.split("/")[1].toLowerCase();
if (newName !== oldName) {
renames.push(`@${newName}`);
}
} catch {
// ignore
}
}
for (const indexPath in packageJsons) {
bust(indexPath, packageJsons[indexPath], ghosts);
}
console.log(
"Generated from [.github/workflows/ghostbuster.yml](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/.github/workflows/ghostbuster.yml)",
);
console.log();
console.log(
"Some of these users may have simply changed their usernames; you may want do a bit of searching and ping them to see if they still want to be owners.",
);
if (renames.length) {
console.log();
console.log(
`Hey ${
renames.join(", ")
}, if you'd still like to be an owner for these types, please feel free (but no pressure) to add your new account name back to \`package.json\`. Thanks!`,
);
}
})();