-
Notifications
You must be signed in to change notification settings - Fork 0
/
github-star-count.js
executable file
·204 lines (164 loc) · 4.2 KB
/
github-star-count.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
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
#!/usr/bin/env node
const fetch = require("node-fetch")
async function fetchStarsOfUserRepos({
login = readfileSync(require("path").join(__dirname, "USERNAME")), //
token = readfileSync(require("path").join(__dirname, "TOKEN")),
/**
* set to `true` if only care about total count,
* because will affect the json output:
*
* if true, won't add repos w/ 0 stars
* because they simply won't be fetched.
*/
BREAK_IF_ENCOUNTERED_ZERO_STARS_SINCE_SORTED = false,
REPOS_PER_REQ = 100,
DEBUG = !!process.env.DEBUG,
} = {}) {
const startTime = new Date().toISOString();
const log = (...xs) => {
if (DEBUG) {
console.log(...xs);
}
};
const pages = [];
let pageIdx = 0;
let getCurrFetchedRepos = () => REPOS_PER_REQ * pageIdx;
let totalRepoCount = Infinity;
let maxFetchedRepoCount;
let lastFetchedRepoCursor;
let brokeEarlyBecauseFoundZeroStars = false;
let totalStarCount = 0;
while ((maxFetchedRepoCount = getCurrFetchedRepos()) < totalRepoCount) {
const variables = {
login,
first: 100,
...(!!lastFetchedRepoCursor ? { after: lastFetchedRepoCursor } : {}),
};
console.log({ variables });
const res = await fetch("https://api.github.com/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
query: QUERY_USER_REPOS_STARS, //
variables,
}),
});
log({ res });
const page = await res.json();
log({ page });
log(JSON.stringify(page, null, 2));
if (page.errors) {
const { errors } = page;
console.error({ errors });
throw new Error("failed fetching");
}
pages.push(page);
totalRepoCount = page.data.user.repositories.totalCount;
totalStarCount += page.data.user.repositories.edges.map((e) => e.node.stargazers.totalCount).reduce(sum, 0);
const lastEdge = last(page.data.user.repositories.edges)
lastFetchedRepoCursor = lastEdge.cursor;
++pageIdx;
console.log({
totalRepoCount, //
pageIdx,
maxFetchedRepoCount,
totalStarCount,
});
if (BREAK_IF_ENCOUNTERED_ZERO_STARS_SINCE_SORTED) {
if (lastEdge.node.stargazers.totalCount === 0) {
brokeEarlyBecauseFoundZeroStars = true;
break;
}
}
}
const stats = {
stars: totalStarCount, //
repos: totalRepoCount,
maxFetchedRepos: maxFetchedRepoCount,
...(BREAK_IF_ENCOUNTERED_ZERO_STARS_SINCE_SORTED ? { brokeEarlyBecauseFoundZeroStars } : {}),
};
console.log({ stats });
const repos = getFlatRepos(pages);
const meta = {
login,
startTime,
};
return {
meta,
stats, //
repos,
};
}
const readfileSync = (file, opts = {}) =>
require("fs")
.readFileSync(file, { encoding: "utf-8", ...opts })
.trim();
const sum = (acc, curr) => acc + curr;
const QUERY_USER_REPOS_STARS = gql`
query ($login: String!, $first: Int!, $after: String) {
user(login: $login) {
repositories(
first: $first
after: $after
ownerAffiliations: OWNER
orderBy: { direction: DESC, field: STARGAZERS }
) {
totalCount
edges {
cursor
node {
name
id
stargazers {
totalCount
}
}
}
}
}
}
`;
function gql(x) {
return x[0];
}
const getFlatRepos = (pages) => pages.flatMap(getFlatReposEdges);
const getFlatReposEdges = (page) => page.data.user.repositories.edges;
async function github_star_count_CLI(argv = process.argv.slice(2)) {
const fs = require("fs");
const path = require("path");
const data = await fetchStarsOfUserRepos();
const outDirBase = path.join(__dirname, "out"); // TODO ARGV
const outDir = path.join(outDirBase, data.meta.login);
ensureDirSync(outDir, fs);
const outfile = path.join(outDir, data.meta.startTime + ".json");
fs.writeFileSync(outfile, JSON.stringify(data, null, 2), { encoding: "utf-8" });
process.stdout.write(outfile + "\n");
return outfile;
}
function ensureDirSync(dir, fs = require("fs")) {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
function last(xs) {
return xs[xs.length - 1]
}
if (!module.parent) {
github_star_count_CLI()
.then(() => {
process.exit(0);
})
.catch((e) => {
console.error(e);
process.exit(1);
});
}
module.exports = {
fetchStarsOfUserRepos,
getFlatRepos,
getFlatReposEdges,
github_star_count_CLI,
};