-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithub.ts
More file actions
436 lines (386 loc) · 12.9 KB
/
Copy pathgithub.ts
File metadata and controls
436 lines (386 loc) · 12.9 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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
import type { UserData, SlidesData, LanguageData, QuarterStats } from '../store/useAppStore';
import { getDaysElapsedIn2025, getQuarter } from './timeUtils';
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api';
interface GitHubRepo {
name: string;
description: string;
stargazerCount: number;
forkCount: number;
isFork: boolean;
url: string;
updatedAt: string;
defaultBranchRef?: {
target?: {
history?: {
nodes?: Array<{
message: string;
committedDate: string;
author?: {
user?: {
id: string;
};
};
}>;
};
};
};
primaryLanguage: {
name: string;
color: string;
} | null;
languages: {
edges: Array<{
size: number;
node: {
name: string;
color: string;
};
}>;
};
}
interface ContributionDay {
date: string;
contributionCount: number;
}
interface ContributionWeek {
contributionDays: ContributionDay[];
}
interface ContributionCalendarDay {
date: string;
count: number;
level: number;
}
export async function fetchUserData(token: string): Promise<UserData> {
const query = `
query {
viewer {
login
name
avatarUrl
bio
}
}
`;
const response = await fetch(`${API_BASE}/graphql`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, token }),
});
const data = await response.json();
return data.data.viewer;
}
export async function fetchGitHubStats(token: string, username: string): Promise<SlidesData> {
const year = 2025;
const from = `${year}-01-01T00:00:00Z`;
const to = `${year}-12-31T23:59:59Z`;
const fromTimestamp = `${year}-01-01T00:00:00Z`;
const toTimestamp = `${year}-12-31T23:59:59Z`;
const query = `
query($username: String!, $from: DateTime!, $to: DateTime!, $fromTimestamp: GitTimestamp!, $toTimestamp: GitTimestamp!) {
user(login: $username) {
id
contributionsCollection(from: $from, to: $to) {
contributionCalendar {
totalContributions
weeks {
contributionDays {
contributionCount
date
}
}
}
pullRequestContributions {
totalCount
}
pullRequestReviewContributions {
totalCount
}
issueContributions {
totalCount
}
commitContributionsByRepository {
repository {
name
owner {
login
}
}
contributions {
totalCount
}
}
}
repositories(first: 100, ownerAffiliations: [OWNER, ORGANIZATION_MEMBER, COLLABORATOR], orderBy: {field: STARGAZERS, direction: DESC}) {
totalCount
nodes {
name
description
stargazerCount
forkCount
isFork
url
updatedAt
defaultBranchRef {
target {
... on Commit {
history(first: 20, since: $fromTimestamp, until: $toTimestamp) {
nodes {
message
committedDate
author {
user {
id
}
}
}
}
}
}
}
primaryLanguage {
name
color
}
languages(first: 10, orderBy: {field: SIZE, direction: DESC}) {
edges {
size
node {
name
color
}
}
}
}
}
}
}
`;
const response = await fetch(`${API_BASE}/graphql`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables: { username, from, to, fromTimestamp, toTimestamp }, token }),
});
const data = await response.json();
const userData = data.data.user;
const userId = userData.id;
const contributions = userData.contributionsCollection;
const totalCommits = contributions.contributionCalendar.totalContributions;
const totalPRs = contributions.pullRequestContributions.totalCount;
const totalReviews = contributions.pullRequestReviewContributions?.totalCount || 0;
const totalIssues = contributions.issueContributions?.totalCount || 0;
const repos = userData.repositories.nodes as GitHubRepo[];
const totalRepos = userData.repositories.totalCount;
const totalStars = repos.reduce((sum: number, repo) => sum + repo.stargazerCount, 0);
const totalForks = repos.reduce((sum: number, repo) => sum + (repo.forkCount || 0), 0);
const languageMap = new Map<string, { size: number; color: string }>();
repos.filter(repo => !repo.isFork).forEach((repo) => {
repo.languages.edges.forEach((edge) => {
const name = edge.node.name;
const existing = languageMap.get(name) || { size: 0, color: edge.node.color };
languageMap.set(name, {
size: existing.size + edge.size,
color: edge.node.color,
});
});
});
const totalSize = Array.from(languageMap.values()).reduce((sum, lang) => sum + lang.size, 0);
const topLanguages: LanguageData[] = Array.from(languageMap.entries())
.map(([name, data]) => ({
name,
percentage: (data.size / totalSize) * 100,
color: data.color || '#8b5cf6',
}))
.sort((a, b) => b.percentage - a.percentage)
.slice(0, 5);
const contributionDays: ContributionCalendarDay[] = (contributions.contributionCalendar.weeks as ContributionWeek[]).flatMap((week) =>
week.contributionDays.map((day) => ({
date: day.date,
count: day.contributionCount,
level: Math.min(Math.floor(day.contributionCount / 3), 4),
}))
);
const busiestDay = contributionDays.reduce((max, day) =>
day.count > max.count ? day : max
, { date: '', count: 0 });
let longestStreak = 0;
let currentStreak = 0;
contributionDays.forEach((day) => {
if (day.count > 0) {
currentStreak++;
longestStreak = Math.max(longestStreak, currentStreak);
} else {
currentStreak = 0;
}
});
const persona = calculatePersona(
contributionDays,
totalCommits,
totalPRs,
totalReviews,
totalIssues,
topLanguages.length,
longestStreak,
busiestDay.count
);
const daysElapsed = getDaysElapsedIn2025();
const activeDays = contributionDays.filter((d) => d.count > 0).length;
const activityRate = daysElapsed > 0 ? (activeDays / daysElapsed) * 100 : 0;
const radarData: Array<{ subject: string; value: number; fullMark: 100 }> = [
{ subject: '代码量', value: Math.min((totalCommits / 500) * 100, 100), fullMark: 100 as const },
{ subject: '活跃度', value: Math.min(activityRate, 100), fullMark: 100 as const },
{ subject: '协作力', value: Math.min((totalPRs / 50) * 100, 100), fullMark: 100 as const },
{ subject: '影响力', value: Math.min((totalStars / 100) * 100, 100), fullMark: 100 as const },
{ subject: '多样性', value: Math.min((topLanguages.length / 5) * 100, 100), fullMark: 100 as const },
{ subject: '创造力', value: Math.min((totalRepos / 20) * 100, 100), fullMark: 100 as const },
];
const averageCommitsPerDay = activeDays > 0 ? totalCommits / activeDays : 0;
const repoContributionsMap = new Map<string, number>();
const repoCommitsMap = new Map<string, Array<{ message: string; date: string }>>();
const commitContributionsByRepo = contributions.commitContributionsByRepository || [];
commitContributionsByRepo.forEach((item: {
repository: { name: string };
contributions?: {
totalCount: number;
}
}) => {
const repoName = item.repository.name;
const commits2025 = item.contributions?.totalCount || 0;
repoContributionsMap.set(repoName, commits2025);
});
repos.forEach((repo) => {
const repoName = repo.name;
const commits = repo.defaultBranchRef?.target?.history?.nodes || [];
const userCommits = commits
.filter(commit => commit.author?.user?.id === userId)
.map(commit => ({
message: commit.message.split('\n')[0],
date: commit.committedDate,
}))
.slice(0, 20);
if (userCommits.length > 0) {
repoCommitsMap.set(repoName, userCommits);
}
});
const topRepositories = repos
.map(repo => ({
name: repo.name,
description: repo.description || '',
stargazerCount: repo.stargazerCount,
forkCount: repo.forkCount || 0,
language: repo.primaryLanguage?.name || 'Unknown',
updatedAt: repo.updatedAt,
url: repo.url,
commits2025: repoContributionsMap.get(repo.name) || 0,
recentCommits: repoCommitsMap.get(repo.name) || [],
}))
.filter(repo => repo.commits2025 > 0)
.sort((a, b) => {
if (b.commits2025 !== a.commits2025) {
return b.commits2025 - a.commits2025;
}
return b.stargazerCount - a.stargazerCount;
})
.slice(0, 5);
const commitsByMonth = new Map<string, number>();
contributionDays.forEach(day => {
const month = day.date.substring(0, 7);
commitsByMonth.set(month, (commitsByMonth.get(month) || 0) + day.count);
});
const commitActivity = Array.from(commitsByMonth.entries())
.map(([month, count]) => ({ month, count }))
.sort((a, b) => a.month.localeCompare(b.month));
const quarterStatsMap = new Map<1 | 2 | 3 | 4, number>();
const quarterNames = ['', 'Q1', 'Q2', 'Q3', 'Q4'];
contributionDays.forEach(day => {
const quarter = getQuarter(day.date);
const existing = quarterStatsMap.get(quarter) || 0;
quarterStatsMap.set(quarter, existing + day.count);
});
const quarterStats: QuarterStats[] = [1, 2, 3, 4].map(q => {
const commits = quarterStatsMap.get(q as 1 | 2 | 3 | 4) || 0;
return {
quarter: q as 1 | 2 | 3 | 4,
name: quarterNames[q],
commits: commits,
prs: 0,
};
});
return {
totalCommits,
totalPRs,
totalStars,
totalRepos,
topLanguages,
busiestDay,
persona,
radarData,
contributionCalendar: contributionDays,
aiComment: '',
topRepositories,
commitActivity,
totalForks,
totalIssues,
totalReviews,
activeDays,
longestStreak,
averageCommitsPerDay,
quarterStats,
};
}
function calculatePersona(
contributionDays: ContributionCalendarDay[],
totalCommits: number,
totalPRs: number,
totalReviews: number,
totalIssues: number,
languageCount: number,
longestStreak: number,
maxDailyCommits: number
): string {
const weekendCount = contributionDays.filter((day) => {
const date = new Date(day.date);
const dayOfWeek = date.getDay();
return (dayOfWeek === 0 || dayOfWeek === 6) && day.count > 0;
}).length;
const activeDays = contributionDays.filter(d => d.count > 0);
if (activeDays.length === 0) return 'default';
const avgPerDay = activeDays.reduce((sum, d) => sum + d.count, 0) / activeDays.length;
const daysElapsed = getDaysElapsedIn2025();
const consistency = daysElapsed > 0 ? activeDays.length / daysElapsed : 0;
// 计算月份集中度(贡献最多的3个月占比)
const commitsByMonth = new Map<string, number>();
contributionDays.forEach(day => {
const month = day.date.substring(0, 7);
commitsByMonth.set(month, (commitsByMonth.get(month) || 0) + day.count);
});
const top3Months = Array.from(commitsByMonth.values())
.sort((a, b) => b - a)
.slice(0, 3)
.reduce((sum, val) => sum + val, 0);
const monthConcentration = top3Months / totalCommits;
// 按优先级判断类型(从特殊到一般)
// 1. 高产开发者 - 总贡献数非常高
if (totalCommits > 2000) return 'high-achiever';
// 2. 爆发型开发者 - 单日贡献非常高
if (maxDailyCommits > 35) return 'burst-coder';
// 3. 连续贡献者 - 最长连续天数很长
if (longestStreak > 60) return 'streak-master';
// 4. 语言探索者 - 使用多种编程语言
if (languageCount >= 6) return 'language-explorer';
// 5. 协作达人 - PR Review 或 PR 数量多
if (totalReviews > 15 || totalPRs > 25) return 'collaborator';
// 6. 维护者 - PR 和 Issue 都较多
if (totalPRs + totalIssues > 20) return 'maintainer';
// 7. 周末战士 - 周末贡献多
if (weekendCount > 50) return 'weekend-warrior';
// 8. 稳定贡献者 - 一致性很高
if (consistency > 0.7) return 'consistent-contributor';
// 9. 专注型开发者 - 集中在某些月份
if (monthConcentration > 0.5 && totalCommits > 500) return 'focused-coder';
// 10. 夜猫子程序员 - 平均每天贡献高
if (avgPerDay > 5) return 'night-owl';
// 11. 稳步建设者 - 中等但持续的贡献
if (totalCommits > 300 && consistency > 0.3 && consistency < 0.6) return 'steady-builder';
// 12. 早起鸟工程师 - 默认类型
return 'early-bird';
}