-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
51 lines (40 loc) · 1.55 KB
/
index.js
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
#!/usr/bin/env node
import process from 'node:process';
import got from 'got';
import kleur from 'kleur';
import random from 'random';
const user = process.argv.slice(2)[0];
const lastPage = /(.*)page=(.*)>; rel="last"/;
if (!user) {
console.log('Usage: `npx -q random-starred-repository username`');
process.exit(1);
}
const getStars = async (user, page) => {
const response = await got(`https://api.github.com/users/${user}/starred?page=${page}`)
.catch(error => {
console.error(kleur.red().bold(`Unable to get stars (${error.response?.statusCode} ${error.response?.statusMessage})`));
process.exit(1);
});
const starred = JSON.parse(response.body);
if (starred.length === 0) {
console.warn(kleur.yellow().bold(`${user} doesn’t have any starred repositories yet.`));
process.exit(0);
}
return starred.map(s => ({
owner: s.owner.login,
repo: s.name,
}));
};
const getRandomPage = async user => {
const response = await got(`https://api.github.com/users/${user}/starred`)
.catch(error => {
console.error(kleur.red().bold(`Unable to get random page (${error.response?.statusCode} ${error.response?.statusMessage})`));
process.exit(1);
});
const pages = response.headers.link ? response.headers.link.replace(lastPage, '$2') : 1;
return random.int(1, Number(pages));
};
const page = await getRandomPage(user);
const results = await getStars(user, page);
const result = results[random.int(0, results.length - 1)];
console.log(kleur.green().bold(`https://github.com/${result.owner}/${result.repo}`));