-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
321 lines (273 loc) · 9.31 KB
/
index.ts
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import * as puppeteer from "puppeteer";
import { readFileSync, writeFileSync } from "fs";
import { exit } from "process";
import { isDeepStrictEqual } from "util";
interface Dependent {
owner: string;
repo: string;
stars: number;
forks: number;
previousGithubDependentsPageUrl: string | null;
}
async function getDependentsFromFile(dependentsFile: string) {
return JSON.parse(
await readFileSync(dependentsFile, { encoding: "utf8" })
) as Dependent[];
}
async function saveDependentsToFile(
dependentsFile: string,
dependents: Dependent[],
overwriteDependentsFile: Boolean
) {
console.log(
`Saving ${dependents.length} found dependents to ${dependentsFile}...`
);
let _dependents = dependents;
if (!overwriteDependentsFile) {
const existingDependents = await getDependentsFromFile(dependentsFile);
_dependents = existingDependents.concat(dependents);
}
await writeFileSync(dependentsFile, JSON.stringify(_dependents));
}
async function parseDependents(page: puppeteer.Page) {
try {
const dependents: Dependent[] = [];
let element: puppeteer.ElementHandle<Element> | null;
try {
element = await page.waitForSelector("#dependents > div.Box", {
timeout: 15000,
});
} catch (error) {
throw new Error(
"Unable to find dependents, probably reached rate limit page," +
"try running crawler again in a few minutes with resumeCrawler = true.\n" +
'**NOTE** Running script again without passing "true" for resumeCrawler will' +
"overwrite dependentsFile if same file name is used. Recommend use is to use" +
"same file name for dependentsFile and pass true as third argument when starting crawler.\n" +
"Exiting..."
);
}
const numberOfDependents = (await page.evaluate(
(el) => el?.childElementCount,
element
)) as number;
// -1 Because containing div has a header div we don't want
// #dependents > div.Box > div.Box-header.clearfix
console.log(`Found ${numberOfDependents - 1} dependents, parsing them...`);
for (let index = 2; index <= numberOfDependents; index++) {
let text: string = "";
try {
const element = await page.waitForSelector(
`#dependents > div.Box > div:nth-child(${index})`
);
text = (await page.evaluate(
(el) => el?.textContent,
element
)) as string;
const reg = /(\S+\s\/)(\s+\S+)\s+((?:\d+,?)+)(\s+)((?:\d+,?)+)/;
const res = reg.exec(text as string) as string[];
dependents.push({
owner: res[1].replace(/\s\//g, ""),
repo: res[2].replace(/\s/g, ""),
stars: parseInt(res[3].replace(/,/g, "")),
forks: parseInt(res[5].replace(/,/g, "")),
previousGithubDependentsPageUrl: null,
});
} catch (error) {
console.error(error);
console.log(text);
}
}
return dependents;
} catch (error) {
console.error(error);
await page.screenshot({ path: "./screenshot.jpg" });
}
}
async function getPreviousDependentsPageUrl(page: puppeteer.Page) {
let element: puppeteer.ElementHandle<Element> | null;
try {
element = await page.waitForSelector(
"#dependents > div.paginate-container > div > a:nth-child(1)",
{ timeout: 15000 }
);
} catch (error) {
try {
element = await page.waitForSelector(
"#dependents > div.paginate-container > div > button",
{ timeout: 15000 }
);
} catch (error) {
throw new Error(
'Unable to find "Previous" button to go to previous dependents page'
);
}
}
return await page.evaluate((el) => {
// We're on the first dependencies page
if (el?.getAttribute("disabled") === "disabled") return null;
return el?.getAttribute("href");
}, element);
}
async function getNextDependentsPageUrl(page: puppeteer.Page) {
let element: puppeteer.ElementHandle<Element> | null;
try {
element = await page.waitForSelector(
"#dependents > div.paginate-container > div > a:nth-child(2)",
{ timeout: 15000 }
);
} catch (error) {
try {
// We are at the last dependents page
if ((await getPreviousDependentsPageUrl(page)) !== null) return null;
element = await page.waitForSelector(
"#dependents > div.paginate-container > div > a",
{ timeout: 15000 }
);
} catch (error) {
throw new Error(
'Unable to find "Next" button to go to next dependents page'
);
}
}
return await page.evaluate((el) => {
// We're on the last dependencies page
if (el?.getAttribute("disabled") === "disabled") return null;
return el?.getAttribute("href");
}, element);
}
async function removeDuplicateDependents(
dependentsFile: string,
parsedDependents: Dependent[]
) {
const _parsedDependents = parsedDependents;
const existingDependents = await getDependentsFromFile(dependentsFile);
for (const [index, parsedDependent] of parsedDependents.entries()) {
if (
existingDependents.findIndex((dependent) =>
isDeepStrictEqual(dependent, parsedDependent)
) !== -1
) {
console.log("Found duplicate dependent when parsing, skipping it...");
_parsedDependents.splice(index, 1);
}
}
return _parsedDependents;
}
async function startCrawl(
dependentsFile: string,
page: puppeteer.Page,
overwriteDependentsFile = false
) {
let _overwriteDependentsFile = overwriteDependentsFile;
console.log("Starting crawl...");
try {
while (true) {
let parsedDependents = await parseDependents(page);
if (parsedDependents === undefined)
throw new Error("Unable to parse dependents");
try {
parsedDependents = await removeDuplicateDependents(
dependentsFile,
parsedDependents
);
} catch (error) {
throw error;
}
const previousPageUrl = await getPreviousDependentsPageUrl(page);
if (previousPageUrl !== null && previousPageUrl !== undefined) {
for (const dependent of parsedDependents) {
dependent.previousGithubDependentsPageUrl = previousPageUrl;
}
}
await saveDependentsToFile(
dependentsFile,
parsedDependents,
_overwriteDependentsFile
);
// We are saving after parsing each page, so we no longer want to overwrite
// the dependentsFile if overwriteDependentsFile was true
_overwriteDependentsFile = false;
const nextPageUrl = await getNextDependentsPageUrl(page);
if (nextPageUrl === null) {
console.log("Reached last dependency page, exiting...");
break;
} else if (nextPageUrl === undefined)
throw new Error("Unable to find next dependency page URL");
await page.goto(nextPageUrl);
}
} catch (error) {
console.error(error);
}
}
async function resumeCrawlFromFile(
dependentsFile: string,
page: puppeteer.Page
) {
console.log(`Resuming crawl from last dependent in ${dependentsFile}...`);
const dependentsFileJson = await getDependentsFromFile(dependentsFile);
const lastDependent = dependentsFileJson.pop();
if (lastDependent === undefined)
throw new Error(`${dependentsFile} appears to be empty`);
if (lastDependent.previousGithubDependentsPageUrl !== null) {
await page.goto(lastDependent.previousGithubDependentsPageUrl);
const nextPageUrl = await getNextDependentsPageUrl(page);
if (nextPageUrl === null) {
console.log("Reached last dependency page, exiting...");
exit(0);
}
if (nextPageUrl === undefined) {
throw new Error("Unable to find next dependency page URL");
}
await page.goto(nextPageUrl);
}
await startCrawl(dependentsFile, page);
}
async function launchPuppeteer(): Promise<[puppeteer.Browser, puppeteer.Page]> {
const browser = await puppeteer.launch({});
const page = await browser.newPage();
return [browser, page];
}
function getArgs(): [string, string, boolean] {
const [githubOwnerAndRepo, dependentsFile, resumeCrawl] =
process.argv.slice(2);
if (
githubOwnerAndRepo === undefined ||
githubOwnerAndRepo.match(/(\S+\/\S+)/) === null
)
throw new Error(
`Unable to parse Github Owner and Repo names from ${githubOwnerAndRepo}. ` +
`Please provide Owner and Repo names like so: owner/repo`
);
if (dependentsFile === undefined || !dependentsFile.match(/\w+.json/))
throw new Error(
`Expected dependents file to have .json extension. ${dependentsFile} was provided`
);
if (
resumeCrawl !== "false" &&
resumeCrawl !== "true" &&
resumeCrawl !== undefined
)
throw new Error(
`Expected resumeCrawl to be true or false. ${resumeCrawl} was provided`
);
return [githubOwnerAndRepo, dependentsFile, Boolean(resumeCrawl)];
}
async function start() {
const [githubOwnerAndRepo, dependentsFile, resumeCrawl] = getArgs();
console.log(`Scrapping dependents for ${githubOwnerAndRepo}`);
console.log(`Saving dependents to ${dependentsFile}`);
const [browser, page] = await launchPuppeteer();
if (resumeCrawl) await resumeCrawlFromFile(dependentsFile, page);
else {
await page.goto(
`https://github.com/${githubOwnerAndRepo}/network/dependents`
);
await saveDependentsToFile(dependentsFile, [], true);
await startCrawl(dependentsFile, page, true);
}
browser.close();
}
(async () => {
start();
})();