-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathGithubController.js
More file actions
502 lines (417 loc) · 18.6 KB
/
GithubController.js
File metadata and controls
502 lines (417 loc) · 18.6 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
const axios = require('axios');
const User = require('../models/UserModel');
const redisClient = require('../util/RediaClient');
const { Octokit } = require("@octokit/rest");
const { createGithubApi } = require('../util/GithubApiHelper');
exports.getRepoTimeline = async (req, res) => {
const { username, reponame } = req.params;
const userId = req.session.userId || 'public';
const cacheKey = `repo:timeline:${userId}:${username}:${reponame}`;
try {
const cachedData = await redisClient.get(cacheKey);
if (cachedData) {
console.log(`Cache hit for timeline of ${username}/${reponame} for user ${userId}`);
return res.json(JSON.parse(cachedData));
}
const githubApi = await createGithubApi(req.session);
// 1. Fetch all branches
const { data: branchesData } = await githubApi.get(`/repos/${username}/${reponame}/branches`);
// 2. Fetch all tags
const { data: tagsData } = await githubApi.get(`/repos/${username}/${reponame}/tags`);
// 3. Fetch commits (limit to 500 using per_page and pagination with early exit)
const commits = [];
const maxCommits = 500;
const perPage = 100;
const maxPages = Math.ceil(maxCommits / perPage);
// Use Promise.all to fetch pages in parallel for better performance
const pagePromises = [];
for (let page = 1; page <= maxPages; page++) {
pagePromises.push(
githubApi.get(`/repos/${username}/${reponame}/commits`, {
params: { per_page: perPage, page },
}).catch(err => {
console.warn(`Failed to fetch page ${page}:`, err.message);
return { data: [] };
})
);
}
const pageResults = await Promise.all(pagePromises);
for (const { data: pageCommits } of pageResults) {
if (pageCommits.length === 0) break;
commits.push(...pageCommits);
if (commits.length >= maxCommits) break;
}
// Trim to exact limit if we exceeded - keep only first maxCommits items
const trimmedCommits = commits.slice(0, maxCommits);
// Map tags to SHAs
const tagMap = {};
for (const tag of tagsData) {
tagMap[tag.commit.sha] = tag.name;
}
const processedCommits = trimmedCommits.map(commit => ({
sha: commit.sha,
message: commit.commit.message,
author: {
name: commit.commit.author.name,
login: commit.author ? commit.author.login : commit.commit.author.name,
avatar_url: commit.author ? commit.author.avatar_url : null,
},
date: commit.commit.author.date,
parents: commit.parents.map(p => p.sha),
tag: tagMap[commit.sha] || null,
}));
const responsePayload = {
commits: processedCommits,
branches: branchesData.map(b => ({ name: b.name, sha: b.commit.sha })),
tags: tagsData.map(t => ({ name: t.name, sha: t.commit.sha })),
};
await redisClient.set(cacheKey, JSON.stringify(responsePayload), { EX: 3600 });
res.json(responsePayload);
} catch (error) {
console.error("Error fetching repo timeline data:", error);
const status = error.response?.status || 500;
res.status(status).json({ message: "Failed to fetch repository timeline data from GitHub." });
}
};
exports.fetchCodeHotspots = async (req, res) => {
const { username, reponame } = req.params;
const userId = req.session.userId || 'public';
const cacheKey = `repo:hotspots:${userId}:${username}:${reponame}`;
try {
const cachedData = await redisClient.get(cacheKey);
if (cachedData) {
console.log(`Cache hit for hotspots: ${username}/${reponame}`);
return res.json(JSON.parse(cachedData));
}
const githubApi = await createGithubApi(req.session);
const commitsResponse = await githubApi.get(`/repos/${username}/${reponame}/commits`, {
params: { per_page: 100 }
});
// Limit concurrency to avoid overwhelming the API
const CONCURRENCY_LIMIT = 10;
const fileChurn = new Map();
for (let i = 0; i < commitsResponse.data.length; i += CONCURRENCY_LIMIT) {
const batch = commitsResponse.data.slice(i, i + CONCURRENCY_LIMIT);
const batchPromises = batch.map(commit => githubApi.get(commit.url));
const batchDetails = await Promise.all(batchPromises);
batchDetails.forEach(commitDetail => {
if (commitDetail.data.files) {
commitDetail.data.files.forEach(file => {
fileChurn.set(file.filename, (fileChurn.get(file.filename) || 0) + 1);
});
}
});
}
const hotspots = Array.from(fileChurn, ([path, churn]) => ({ path, churn }))
.sort((a, b) => b.churn - a.churn);
await redisClient.set(cacheKey, JSON.stringify(hotspots), { EX: 3600 });
res.json(hotspots);
} catch (error) {
console.error("Error fetching code hotspots:", error.response?.data || error.message);
res.status(error.response?.status || 500).json({ message: "Error fetching code hotspots from GitHub." });
}
};
exports.fetchIssueTimeline = async (req, res) => {
const { username, reponame, issue_number } = req.params;
const userId = req.session.userId || 'public';
const cacheKey = `issue:timeline:${userId}:${username}:${reponame}:${issue_number}`;
try {
const cachedData = await redisClient.get(cacheKey);
if (cachedData) {
console.log(`Cache hit for issue timeline: #${issue_number}`);
return res.json(JSON.parse(cachedData));
}
const githubApi = await createGithubApi(req.session);
const timelineResponse = await githubApi.get(`/repos/${username}/${reponame}/issues/${issue_number}/timeline`, {
headers: { 'Accept': 'application/vnd.github.mockingbird-preview+json' }
});
await redisClient.set(cacheKey, JSON.stringify(timelineResponse.data), { EX: 1800 });
res.json(timelineResponse.data);
} catch (error) {
console.error("Error fetching issue timeline:", error.response?.data || error.message);
res.status(error.response?.status || 500).json({ message: "Error fetching issue timeline from GitHub." });
}
};
exports.fetchFileCommits = async (req, res) => {
const { username, reponame } = req.params;
const { path } = req.query;
if (!path) {
return res.status(400).json({ message: 'A file path query parameter is required.' });
}
const userId = req.session.userId || 'public';
const cacheKey = `repo:commits:${userId}:${username}:${reponame}:${path}`;
try {
const cachedCommits = await redisClient.get(cacheKey);
if (cachedCommits) {
console.log(`Cache hit for commits on file: ${path}`);
return res.json(JSON.parse(cachedCommits));
}
const githubApi = await createGithubApi(req.session);
const response = await githubApi.get(`/repos/${username}/${reponame}/commits`, {
params: { path: path }
});
await redisClient.set(cacheKey, JSON.stringify(response.data), { EX: 3600 });
res.json(response.data);
} catch (error) {
console.error("Error fetching file commits:", error.response?.data || error.message);
const status = error.response?.status || 500;
res.status(status).json({ message: "Error fetching file commit history from GitHub." });
}
};
exports.fetchRepoDetails = async (req, res) => {
const { username, reponame } = req.params;
const userId = req.session.userId || 'public';
const cacheKey = `repo:contributors:${userId}:${username}:${reponame}`;
try {
const cachedData = await redisClient.get(cacheKey);
if (cachedData) {
console.log(`Cache hit for repo: ${username}/${reponame} for user: ${userId}`);
return res.json(JSON.parse(cachedData));
}
const githubApi = await createGithubApi(req.session);
const response = await githubApi.get(`/repos/${username}/${reponame}`);
await redisClient.set(cacheKey, JSON.stringify(response.data), { EX: 3600 });
res.json(response.data);
} catch (error) {
const status = error.response?.status || 500;
res.status(status).json({ message: 'Error fetching repository data from GitHub.' });
}
};
exports.fetchPullRequests = async (req, res) => {
const { username, reponame } = req.params;
const githubApi = await createGithubApi(req.session);
try {
const { data } = await githubApi.get(`/repos/${username}/${reponame}/pulls`, {
params: {
state: 'all',
per_page: 100,
sort: 'updated',
direction: 'desc'
}
});
res.json(data);
} catch (error) {
console.error("Error fetching pull requests:", error.response?.data || error.message);
res.status(error.response?.status || 500).json({ message: "Error fetching pull requests." });
}
};
exports.fetchGitTree = async (req, res) => {
let { username, reponame, branch } = req.params;
const userId = req.session.userId || 'public';
const cacheKey = `repo:tree:${userId}:${username}:${reponame}:${branch || 'default'}`;
try {
const cachedTree = await redisClient.get(cacheKey);
if (cachedTree) return res.json(JSON.parse(cachedTree));
const githubApi = await createGithubApi(req.session);
const repoRes = await githubApi.get(`/repos/${username}/${reponame}`);
const defaultBranch = repoRes.data.default_branch;
if (!branch) branch = defaultBranch;
const branchInfo = await githubApi.get(`/repos/${username}/${reponame}/branches/${branch}`);
const treeSha = branchInfo.data.commit.commit.tree.sha;
const treeRes = await githubApi.get(`/repos/${username}/${reponame}/git/trees/${treeSha}?recursive=1`);
await redisClient.set(cacheKey, JSON.stringify(treeRes.data), { EX: 3600 });
res.json(treeRes.data);
} catch (error) {
console.error("Error fetching Git tree:", error.response?.data || error.message);
const status = error.response?.status || 500;
res.status(status).json({ message: "Error fetching Git tree from GitHub." });
}
};
exports.fetchContributors = async (req, res) => {
const { username, reponame } = req.params;
const cacheKey = `repo:contributors:${username}:${reponame}`;
try {
const cachedData = await redisClient.get(cacheKey);
if (cachedData) return res.json(JSON.parse(cachedData));
const githubApi = await createGithubApi(req.session);
const response = await githubApi.get(`/repos/${username}/${reponame}/contributors`);
await redisClient.set(cacheKey, JSON.stringify(response.data), { EX: 3600 });
res.json(response.data);
} catch (error) {
const status = error.response?.status || 500;
console.error("Error fetching contributors:", error.response?.data || error.message);
res.status(status).json({ message: "Error fetching contributors from GitHub." });
}
};
exports.fetchRepoFileContents = async (req, res) => {
const { username, reponame, path } = req.params;
try {
const githubApi = await createGithubApi(req.session);
const response = await githubApi.get(`/repos/${username}/${reponame}/contents/${path}`);
res.json(response.data);
} catch (error) {
console.error('Error fetching file content:', error.response?.data || error.message);
const status = error.response?.status || 500;
res.status(status).json({ message: 'Error fetching file content from GitHub.' });
}
};
exports.fetchFileContent = async (req, res) => {
// Get the path parameter and join any additional path segments
const filePath = req.params.path || '';
const additionalPath = req.params[0] || ''; // For wildcard matches
const fullPath = [filePath, additionalPath].filter(Boolean).join('/');
// Rest of your code remains the same
const { username, reponame } = req.params;
if (!fullPath) {
return res.status(400).json({ message: "A file path is required." });
}
try {
const githubApi = await createGithubApi(req.session);
const response = await githubApi.get(`/repos/${username}/${reponame}/contents/${fullPath}`, {
headers: { Accept: 'application/vnd.github.v3.raw' }
});
res.json({
content: response.data,
fileName: fullPath,
fileUrl: `https://github.com/${username}/${reponame}/blob/HEAD/${fullPath}`
});
} catch (error) {
console.error("Error fetching file content:", error.response?.data || error.message);
const status = error.response?.status || 500;
const errorMsg = error.response?.data?.message || "Failed to fetch file content.";
res.status(status).json({ message: errorMsg });
}
};
exports.fetchIssues = async (req, res) => {
const { username, reponame } = req.params;
const userId = req.session.userId || 'public';
const cacheKey = `repo:issues:${userId}:${username}:${reponame}`;
try {
const cachedData = await redisClient.get(cacheKey);
if (cachedData) {
console.log(`Cache hit for issues: ${username}/${reponame}`);
return res.json(JSON.parse(cachedData));
}
const githubApi = await createGithubApi(req.session);
const [openIssuesRes, closedIssuesRes] = await Promise.all([
githubApi.get(`/repos/${username}/${reponame}/issues`, { params: { state: 'open', per_page: 50 } }),
githubApi.get(`/repos/${username}/${reponame}/issues`, { params: { state: 'closed', per_page: 50 } })
]);
const issuesData = {
open: openIssuesRes.data,
closed: closedIssuesRes.data
};
await redisClient.set(cacheKey, JSON.stringify(issuesData), { EX: 1800 });
res.json(issuesData);
} catch (error) {
console.error("Error fetching issues:", error.response?.data || error.message);
const status = error.response?.status || 500;
res.status(status).json({ message: "Error fetching issues from GitHub." });
}
};
exports.fetchDeployments = async (req, res) => {
const { username, reponame } = req.params;
const userId = req.session.userId || 'public';
const cacheKey = `repo:deployments:${userId}:${username}:${reponame}`;
try {
const cachedData = await redisClient.get(cacheKey);
if (cachedData) {
console.log(`Cache hit for deployments: ${username}/${reponame}`);
return res.json(JSON.parse(cachedData));
}
const githubApi = await createGithubApi(req.session);
const deploymentsResponse = await githubApi.get(`/repos/${username}/${reponame}/deployments`);
const deployments = deploymentsResponse.data;
if (!deployments || deployments.length === 0) {
return res.json([]);
}
// Batch deployment status fetches with concurrency control
const CONCURRENCY_LIMIT = 10;
const deploymentsWithStatuses = [];
for (let i = 0; i < deployments.length; i += CONCURRENCY_LIMIT) {
const batch = deployments.slice(i, i + CONCURRENCY_LIMIT);
const batchPromises = batch.map(deployment =>
githubApi.get(deployment.statuses_url)
.then(statusResponse => ({
...deployment,
statuses: statusResponse.data
}))
.catch(err => {
console.warn(`Failed to fetch status for deployment ${deployment.id}:`, err.message);
return { ...deployment, statuses: [] };
})
);
const batchResults = await Promise.all(batchPromises);
deploymentsWithStatuses.push(...batchResults);
}
const activeDeploymentUrls = new Map();
deploymentsWithStatuses.forEach(deployment => {
if (deployment.statuses && deployment.statuses.length > 0) {
const latestSuccessStatus = deployment.statuses.find(
status => status.state === 'success' && status.environment_url
);
if (latestSuccessStatus) {
if (!activeDeploymentUrls.has(deployment.environment)) {
activeDeploymentUrls.set(deployment.environment, {
url: latestSuccessStatus.environment_url,
environment: deployment.environment,
createdAt: deployment.created_at,
});
}
}
}
});
const finalUrls = Array.from(activeDeploymentUrls.values());
await redisClient.set(cacheKey, JSON.stringify(finalUrls), { EX: 3600 });
res.json(finalUrls);
} catch (error) {
console.error("Error fetching deployments:", error.response?.data || error.message);
const status = error.response?.status || 500;
if (status === 404) return res.json([]);
res.status(status).json({ message: "Error fetching deployments from GitHub." });
}
};
exports.fetchRepoInsights = async (req, res) => {
try {
const { username, reponame } = req.params;
const githubApi = await createGithubApi(req.session);
const prs = await githubApi.get(`/repos/${username}/${reponame}/pulls`, {
params: { state: 'closed', per_page: 100 }
});
const mergedPRs = prs.data.filter(pr => pr.merged_at);
const averageMergeTime = calculateAverageMergeTime(mergedPRs);
res.json({
averageMergeTime,
acceptanceRate: Math.round((mergedPRs.length / prs.data.length) * 100),
totalClosed: prs.data.length,
mergedCount: mergedPRs.length
});
} catch (error) {
console.error("Error fetching pull request insights:", error.response?.data || error.message);
res.status(error.response?.status || 500).json({ message: "Error fetching pull request insights from GitHub." });
}
};
function calculateAverageMergeTime(prs) {
if (!prs.length) return null;
const totalMs = prs.reduce((sum, pr) => {
const createdAt = new Date(pr.created_at);
const mergedAt = new Date(pr.merged_at);
return sum + (mergedAt - createdAt);
}, 0);
return totalMs / prs.length;
}
exports.fetchGoodFirstIssues = async (req, res) => {
const { username, reponame } = req.params;
const userId = req.session.userId || 'public';
const cacheKey = `repo:good-first-issues:${userId}:${username}:${reponame}`;
try {
const cachedData = await redisClient.get(cacheKey);
if (cachedData) {
console.log(`Cache hit for good-first-issues: ${username}/${reponame}`);
return res.json(JSON.parse(cachedData));
}
const githubApi = await createGithubApi(req.session);
const response = await githubApi.get(`/repos/${username}/${reponame}/issues`, {
params: {
labels: 'good first issue,help wanted',
state: 'open'
}
});
await redisClient.set(cacheKey, JSON.stringify(response.data), { EX: 1800 });
res.json(response.data);
} catch (error) {
console.error("Error fetching good first issues:", error.response?.data || error.message);
const status = error.response?.status || 500;
res.status(status).json({ message: "Error fetching good first issues from GitHub." });
}
};