-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathcommitStatsCommand.ts
265 lines (247 loc) · 9.35 KB
/
commitStatsCommand.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
/*
* Copyright (c) 2022, Filiph Sandström <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
import {
ChatInputCommandInteraction,
ColorResolvable,
EmbedBuilder,
SlashCommandBuilder,
} from "discord.js";
import githubAPI, { Commit, Repository } from "../apis/githubAPI";
import { CommitClubColor, GitHubColor } from "../util/color";
import { toMedal } from "../util/emoji";
import { extractCopy, trimString } from "../util/text";
import Command from "./command";
export class CommitStatsCommand extends Command {
override data() {
return [
new SlashCommandBuilder()
.setName("commits")
.setDescription("Show user's total amount of commits")
.addStringOption(author =>
author
.setName("author")
.setDescription("Username or email of the commit author")
.setRequired(true)
)
.addBooleanOption(silent =>
silent
.setName("silent")
.setDescription("Set this to `false` to broadcast the output")
.setRequired(false)
)
.toJSON(),
];
}
override async handleCommand(interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.isCommand()) return;
const author = interaction.options.getString("author", true);
if (!author) return;
const silent =
interaction.options.getBoolean("silent", false) !== null
? (interaction.options.getBoolean("silent") as boolean)
: true;
interface RepoInfo {
repo: Repository;
commits: Commit[];
totalCount?: number;
}
// FIXME: Don't try-catch everything; instead do it on a
// per - throwable function basis.
try {
const user = await githubAPI.getUser(author);
if (!user) {
await interaction.reply({
ephemeral: true,
content: `We looked everywhere; but we couldn't find \`${author}\` :^(`,
});
return;
}
await interaction.deferReply({ ephemeral: silent });
const repos = await githubAPI.fetchSerenityRepos();
// GitHub may return non-complete data for some people
// when using either their username or their email (even
// if it's connected as the primary one).
//
// So as a work-around we'll test both the email and the
// username to figure out which one of them returns the
// complete set of commits.
//
// https://support.github.com/ticket/personal/0/1867096
const useEmail =
((await githubAPI.getCommitsCount(user.email ?? author)) ?? 0) >
((await githubAPI.getCommitsCount(user.login ?? author)) ?? 0);
const userCommits = (
await Promise.all(
repos.map<Promise<RepoInfo>>(async repo => {
const commits = await githubAPI.searchCommit(
undefined,
useEmail ? `author-email:${user.email}` : `author:${user.login}`,
repo
);
return {
repo,
commits: commits?.items ?? [],
totalCount: commits.total_count,
};
})
)
).sort((a, b) => (b.totalCount ?? 0) - (a.totalCount ?? 0));
const totalCommits = userCommits.reduce(
(n, { totalCount }) => (totalCount ?? 0) + n,
0
);
const name = `__${user.name ?? user.login}__`;
const total = `**${totalCommits.toLocaleString("en-US")}** commit${
totalCommits === 0 || totalCommits > 1 ? "s" : ""
}`;
const { title, description, color } = extractCopy(totalCommits, milestonesCopy);
const card = new EmbedBuilder()
.setTitle(
title({
name,
total,
})
)
.setDescription(
description?.({
name,
total,
}) || "\u200b"
)
.setColor((color?.({}) as ColorResolvable) || GitHubColor.Draft)
.setThumbnail(user.avatar_url)
.addFields(
...userCommits
.slice(0, 3)
.filter(({ totalCount }) => totalCount! > 0)
.map(({ repo, commits, totalCount }, index) => ({
name: `${toMedal(index + 1)} **${repo.owner}/${
repo.name
}** - **${totalCount?.toLocaleString("en-US")} commit${
totalCount! > 1 ? "s" : ""
}**`,
value: [
...commits
.slice(0, 3)
.map(
({ commit, sha, html_url: url }) =>
`\u200b\u2001- ${trimString(
commit.message.split("\n")[0],
45
)} ([${sha.slice(0, 7)}](${url})).`
),
commits.length > 3
? `\u200b\u2001- [**View All...**](<https://github.com/${repo.owner}/${repo.name}/commits?author=${user.login}>)`
: null,
]
.filter(a => a)
.join("\n"),
}))
.flat()
)
.setTimestamp()
.setFooter({
text: "SerenityOS Contributor Statistics",
iconURL: "https://github.com/SerenityOS.png",
});
await interaction.editReply({
embeds: [card],
});
} catch (e) {
console.trace(e);
await interaction.editReply({
content: `Something went really wrong :^(\n\n\`\`\`${
(e as Error)?.stack ?? e ?? ""
}\`\`\``,
});
}
}
}
interface MilestonesContentCopy {
[text: string]: (a: { [index: string]: string }) => string;
}
const milestonesCopy: Array<{
min: number;
max: number;
copy: MilestonesContentCopy;
}> = [
{
min: Number.MIN_VALUE,
max: 0,
copy: {
color: () => GitHubColor.Closed,
title: ({ name }) => `${name} has not started contributing yet`,
description: () =>
[
"If you need some inspiration on where to start, you can always",
"[take a look at these issues](<https://github.com/SerenityOS/serenity/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22>).",
].join(" "),
},
},
{
min: 1,
max: 24,
copy: {
color: () => GitHubColor.Draft,
title: ({ name, total }) =>
`A wild ${name} has appeared, and they've already got ${total} under their belt`,
},
},
{
min: 25,
max: 49,
copy: {
color: () => GitHubColor.Open,
title: ({ name, total }) =>
`${name} has so far landed a total of ${total} across the SerenityOS project(s)`,
},
},
{
min: 50,
max: 99,
copy: {
color: () => GitHubColor.Open,
title: ({ name, total }) =>
`${name} has crossed the halfway point on the road to triple digits with their ${total} contributed so far`,
},
},
{
min: 100,
max: 499,
copy: {
color: () => CommitClubColor.OneHundred,
title: ({ name, total }) =>
`${name} is a "100 Commit Club" member with an unbelievable ${total} contributed as of right now`,
},
},
{
min: 500,
max: 999,
copy: {
color: () => CommitClubColor.FiveHundred,
title: ({ name, total }) =>
`${name} is a "500 Commit Club" member with their ${total} contributed so far`,
},
},
{
min: 1000,
max: 9999,
copy: {
color: () => CommitClubColor.OneThousand,
title: ({ name, total }) =>
`${name} is a "1000 Commit Club" member with a whopping ${total} contributed to SerenityOS`,
},
},
{
min: 10000,
max: Number.MAX_VALUE,
copy: {
color: () => CommitClubColor.TenThousand,
title: ({ name, total }) =>
`${name} is a "10,000 Commit Club" member with an incredible ${total}`,
},
},
];