-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
441 lines (387 loc) · 16.4 KB
/
main.js
File metadata and controls
441 lines (387 loc) · 16.4 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
// server.js
// Required dependencies:
// npm install express jsonwebtoken axios
// You'll also need your private key file (.pem) and a 'db.json' file.
const express = require('express');
const jwt = require('jsonwebtoken');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = 3000;
// --- Configuration ---
// Replace these values with your GitHub App's specific details.
const APP_ID = '1845091';
const PRIVATE_KEY_PATH = path.join(__dirname, './private.pem');
const DB_PATH = path.join(__dirname, 'db.json');
// --- Helper Functions ---
/**
* Reads data from the JSON database file.
* @returns {object} The parsed JSON data.
*/
function readDb() {
try {
if (fs.existsSync(DB_PATH)) {
const data = fs.readFileSync(DB_PATH, 'utf8');
return JSON.parse(data);
}
} catch (error) {
console.error('Error reading from db.json:', error);
}
// Return a default structure if the file doesn't exist or is empty/corrupt
return { installation_id: null, repositories: [] };
}
/**
* Writes data to the JSON database file.
* @param {object} data - The JavaScript object to write.
*/
function writeDb(data) {
try {
fs.writeFileSync(DB_PATH, JSON.stringify(data, null, 2));
console.log('Successfully wrote to db.json');
} catch (error)
{
console.error('Error writing to db.json:', error);
}
}
// --- GitHub App Logic ---
/**
* Generates a JSON Web Token (JWT) to authenticate as the GitHub App.
* @returns {string} The generated JWT.
*/
function generateJwt() {
const privateKey = fs.readFileSync(PRIVATE_KEY_PATH, 'utf8');
const now = Math.floor(Date.now() / 1000);
// Convert APP_ID to an integer, which is required by the GitHub API.
const appIdInt = parseInt(APP_ID, 10);
// Add a check to ensure the ID was parsed correctly.
if (isNaN(appIdInt)) {
throw new Error('APP_ID is not a valid number. Please check your configuration in server.js.');
}
const payload = {
iat: now - 60,
exp: now + (10 * 60),
iss: appIdInt // Use the integer version of the App ID
};
console.log('Generating JWT...');
return jwt.sign(payload, privateKey, { algorithm: 'RS256' });
}
/**
* Gets an installation access token.
* @param {string} appJwt - The JWT for the GitHub App.
* @param {string} installationId - The ID of the installation.
* @returns {Promise<string>} A promise that resolves with the installation access token.
*/
async function getInstallationAccessToken(appJwt, installationId) {
console.log('Requesting installation access token...');
try {
const response = await axios.post(
`https://api.github.com/app/installations/${installationId}/access_tokens`,
{},
{
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `Bearer ${appJwt}`,
'X-GitHub-Api-Version': '2022-11-28'
}
}
);
console.log('Successfully received installation access token.');
return response.data.token;
} catch (error) {
console.error('Error getting installation access token:', error.response ? error.response.data : error.message);
throw error;
}
}
/**
* NEW: Fetches the list of repositories an app installation has access to.
* @param {string} accessToken - The installation access token.
* @returns {Promise<Array>} A promise that resolves with an array of repository objects.
*/
async function getInstallationRepos(accessToken) {
console.log('Fetching installation repositories...');
try {
const response = await axios.get('https://api.github.com/installation/repositories', {
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `token ${accessToken}`,
'X-GitHub-Api-Version': '2022-11-28'
}
});
console.log(`Found ${response.data.repositories.length} repositories.`);
return response.data.repositories;
} catch (error) {
console.error('Error fetching installation repos:', error.response ? error.response.data : error.message);
throw error;
}
}
/**
* Fetches the diff between two branches with detailed file information.
* @param {string} accessToken - The installation access token.
* @param {string} owner - The repository owner.
* @param {string} repo - The repository name.
* @param {string} branch - The branch to compare.
* @returns {Promise<object>} A promise that resolves with detailed diff information.
*/
async function getBranchDiff(accessToken, owner, repo, branch) {
const compareUrl = `https://api.github.com/repos/${owner}/${repo}/compare/main...${branch}`;
console.log(`Fetching diff from: ${compareUrl}`);
try {
const response = await axios.get(compareUrl, {
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `token ${accessToken}`,
'X-GitHub-Api-Version': '2022-11-28'
}
});
console.log('Successfully fetched diff!');
// Dump the diff data to a JSON file for debugging
const diffFilePath = path.join(__dirname, `diff_${owner}_${repo}_${branch}_${Date.now()}.json`);
fs.writeFileSync(diffFilePath, JSON.stringify(response.data, null, 2));
console.log(`Diff data saved to: ${diffFilePath}`);
return response.data;
} catch (error) {
console.error('Error fetching diff:', error.response ? error.response.data : error.message);
throw error;
}
}
/**
* Gets commit details for a specific commit.
* @param {string} accessToken - The installation access token.
* @param {string} owner - The repository owner.
* @param {string} repo - The repository name.
* @param {string} sha - The commit SHA.
* @returns {Promise<object>} A promise that resolves with commit details.
*/
async function getCommitDetails(accessToken, owner, repo, sha) {
try {
const response = await axios.get(`https://api.github.com/repos/${owner}/${repo}/commits/${sha}`, {
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': `token ${accessToken}`,
'X-GitHub-Api-Version': '2022-11-28'
}
});
console.log('Successfully fetched commit details!');
// Dump the commit data to a JSON file for debugging
const commitFilePath = path.join(__dirname, `commit_${owner}_${repo}_${sha}_${Date.now()}.json`);
fs.writeFileSync(commitFilePath, JSON.stringify(response.data, null, 2));
console.log(`Commit data saved to: ${commitFilePath}`);
return response.data;
} catch (error) {
console.error('Error fetching commit details:', error.response ? error.response.data : error.message);
throw error;
}
}
/**
* Extracts file changes and authors from diff data.
* @param {string} accessToken - The installation access token.
* @param {string} owner - The repository owner.
* @param {string} repo - The repository name.
* @param {object} diffData - The diff data from GitHub API.
* @returns {Promise<object>} A promise that resolves with file changes and authors.
*/
async function extractFileChangesAndAuthors(accessToken, owner, repo, diffData) {
const fileChanges = [];
const authorMap = new Map();
// Extract files from the diff
const files = diffData.files || [];
console.log(`Processing ${files.length} changed files...`);
// Get unique commit SHAs from the diff
const commits = diffData.commits || [];
const commitShas = commits.map(commit => commit.sha);
// Fetch detailed commit information for each commit
for (const sha of commitShas) {
try {
const commitDetails = await getCommitDetails(accessToken, owner, repo, sha);
const author = commitDetails.commit.author;
const committer = commitDetails.commit.committer;
// Store author information
if (author && author.email) {
authorMap.set(author.email, {
name: author.name,
email: author.email,
commits: (authorMap.get(author.email)?.commits || 0) + 1
});
}
// Also include committer if different from author
if (committer && committer.email && committer.email !== author?.email) {
authorMap.set(committer.email, {
name: committer.name,
email: committer.email,
commits: (authorMap.get(committer.email)?.commits || 0) + 1
});
}
} catch (error) {
console.error(`Error fetching commit details for ${sha}:`, error.message);
}
}
// Process each changed file
for (const file of files) {
fileChanges.push({
filename: file.filename,
status: file.status, // 'added', 'removed', 'modified', 'renamed'
additions: file.additions,
deletions: file.deletions,
changes: file.changes,
patch: file.patch ? file.patch.substring(0, 500) + '...' : null // Truncate patch for readability
});
}
return {
filesChanged: fileChanges,
authors: Array.from(authorMap.values()),
summary: {
totalFiles: files.length,
totalCommits: commits.length,
totalAuthors: authorMap.size
}
};
}
// --- Express Server Routes ---
/**
* Homepage route.
*/
app.get('/', (req, res) => {
res.send(`
<h1>GitHub App Server</h1>
<p>Install the app on a repository, then use these endpoints:</p>
<ul>
<li><strong>/get-diff?branch=your-branch-name</strong> - Get detailed diff with files and authors (text format)</li>
<li><strong>/get-diff?branch=your-branch-name&format=json</strong> - Get detailed diff in JSON format</li>
<li><strong>/get-summary?branch=your-branch-name</strong> - Get concise summary of changed files and authors</li>
</ul>
<p>Example: <code>/get-summary?branch=feature-branch</code></p>
`);
});
/**
* GitHub App callback URL.
* This is now an async function to handle API calls.
*/
app.get('/github/callback', async (req, res) => {
const { installation_id, setup_action } = req.query;
if (setup_action === 'install' || setup_action === 'update') {
console.log(`${setup_action === 'install' ? 'New installation' : 'Installation update'} received. ID: ${installation_id}`);
try {
// Step 1: Authenticate as the app to make API calls
const appJwt = generateJwt();
const accessToken = await getInstallationAccessToken(appJwt, installation_id);
// Step 2: Fetch the list of repositories this installation can access
const repos = await getInstallationRepos(accessToken);
// Step 3: Save the installation ID and repository details to our DB
const db = readDb();
db.installation_id = installation_id;
// We only care about the full name (e.g., "owner/repo")
db.repositories = repos.map(repo => ({
full_name: repo.full_name,
owner: repo.owner.login,
name: repo.name
}));
writeDb(db);
const action = setup_action === 'install' ? 'Installed' : 'Updated';
res.send(`<h1>App ${action}!</h1><p>Successfully configured for repositories: ${db.repositories.map(r => r.full_name).join(', ')}</p>`);
} catch (error) {
console.error('Failed during callback setup:', error);
res.status(500).send(`<h1>Error</h1><p>Something went wrong during ${setup_action}: ${error.message}</p>`);
}
} else {
res.send('<h1>Callback Received</h1><p>No action taken.</p>');
}
});
/**
* API endpoint to get the diff with file changes and author information.
* It now uses the repo details from our db.json file.
*/
app.get('/get-diff', async (req, res) => {
const { branch, format } = req.query;
if (!branch) {
return res.status(400).send('Missing required query parameter: branch');
}
const db = readDb();
const installationId = db.installation_id;
const firstRepo = db.repositories && db.repositories[0];
if (!installationId || !firstRepo) {
return res.status(400).send('Installation or repository data not found. Please install the GitHub App first.');
}
// Use the details from the first repository found in our DB
const REPO_OWNER = firstRepo.owner;
const REPO_NAME = firstRepo.name;
const BRANCH_NAME = branch;
try {
const appJwt = generateJwt();
console.log(appJwt)
const accessToken = await getInstallationAccessToken(appJwt, installationId);
const diffData = await getBranchDiff(accessToken, REPO_OWNER, REPO_NAME, BRANCH_NAME);
const fileChangesAndAuthors = await extractFileChangesAndAuthors(accessToken, REPO_OWNER, REPO_NAME, diffData);
// Return different formats based on query parameter
if (format === 'json') {
res.header('Content-Type', 'application/json');
res.json(fileChangesAndAuthors);
} else {
// Return formatted text output
let output = `=== BRANCH DIFF SUMMARY ===\n`;
output += `Repository: ${REPO_OWNER}/${REPO_NAME}\n`;
output += `Branch: ${BRANCH_NAME}\n`;
output += `Total Files Changed: ${fileChangesAndAuthors.summary.totalFiles}\n`;
output += `Total Commits: ${fileChangesAndAuthors.summary.totalCommits}\n`;
output += `Total Authors: ${fileChangesAndAuthors.summary.totalAuthors}\n\n`;
output += `=== FILES CHANGED ===\n`;
fileChangesAndAuthors.filesChanged.forEach((file, index) => {
output += `${index + 1}. ${file.filename}\n`;
output += ` Status: ${file.status}\n`;
output += ` Changes: +${file.additions} -${file.deletions} (${file.changes} total)\n\n`;
});
output += `=== AUTHORS ===\n`;
fileChangesAndAuthors.authors.forEach((author, index) => {
output += `${index + 1}. ${author.name} (${author.email})\n`;
output += ` Commits: ${author.commits}\n\n`;
});
res.header('Content-Type', 'text/plain');
res.send(output);
}
} catch (error) {
res.status(500).send('Failed to fetch diff: ' + error.message);
}
});
/**
* API endpoint to get a concise summary of file changes and authors.
*/
app.get('/get-summary', async (req, res) => {
const { branch } = req.query;
if (!branch) {
return res.status(400).send('Missing required query parameter: branch');
}
const db = readDb();
const installationId = db.installation_id;
const firstRepo = db.repositories && db.repositories[0];
if (!installationId || !firstRepo) {
return res.status(400).send('Installation or repository data not found. Please install the GitHub App first.');
}
const REPO_OWNER = firstRepo.owner;
const REPO_NAME = firstRepo.name;
const BRANCH_NAME = branch;
try {
const appJwt = generateJwt();
const accessToken = await getInstallationAccessToken(appJwt, installationId);
const diffData = await getBranchDiff(accessToken, REPO_OWNER, REPO_NAME, BRANCH_NAME);
const fileChangesAndAuthors = await extractFileChangesAndAuthors(accessToken, REPO_OWNER, REPO_NAME, diffData);
const summary = {
repository: `${REPO_OWNER}/${REPO_NAME}`,
branch: BRANCH_NAME,
changedFiles: fileChangesAndAuthors.filesChanged.map(file => file.filename),
authors: fileChangesAndAuthors.authors.map(author => author.name),
stats: fileChangesAndAuthors.summary
};
res.header('Content-Type', 'application/json');
res.json(summary);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch summary: ' + error.message });
}
});
// --- Start the server ---
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
// Ensure db.json exists on startup with the new structure
if (!fs.existsSync(DB_PATH)) {
writeDb({ installation_id: null, repositories: [] });
}
});