-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
358 lines (318 loc) · 11.3 KB
/
server.js
File metadata and controls
358 lines (318 loc) · 11.3 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
const express = require("express");
const axios = require("axios");
const cors=require('cors');
const dotenv = require("dotenv");
const { URL } = require("url");
const atob = require("atob");
const {
GoogleGenAI,
Type,
HarmBlockThreshold,
HarmCategory,
} = require('@google/genai');
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
// Environment variables
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
const HEADERS = { Authorization: `token ${GITHUB_TOKEN}` };
// Constants from your original file
const IMPORTANT_DIRS = new Set(["src", "app", "component", "components", "pages", "readme"]);
const IMPORTANT_FILE_EXTENSIONS = [".py", ".js", ".ts", ".java", ".cpp", ".ipynb", ".html", ".css"];
const SKIP_KEYWORDS = new Set(["test", "mock", "logo", "docs", "doc", "readme", "config", "setup", "LICENSE", "env", "data"]);
// System prompt for Gemini AI
const SYSTEM_PROMPT = `
You are a senior software engineer who analyzes GitHub repositories for Hackathon. Based on the users provided repository project data, and the hackathon requirements do the following activities and strictly generate a response with the data model given as a structured schema without any empty values:
1. Make comprehensive analysis of the project structure and architecture
2. Figure out exactly what technology stack they have used and functionalites they have implemented compare them with the actual hackathon requirements and update the matched reuirements values in the data model.
3. Code quality observations
4. Provide a short 1-2 line info based on the hackathon requirements and the project of the repository in the final_remarks data (no politeness only strict reqirements judgemental feedback is must if required else just tell good to go with this repository).
Be technical provide response strictly using the given structured schema, if readme is not provided or if its very less to understand in the projectData then generate it based on your analysis of the repositories code files in project data with atleast 200 words or more for sure [if readme contains image urls or emojis don't replace them with unknown characters !!!], also use only english text with utf desktop compatible emojis instead of random characters (Readability should be high priority).
`;
const ai = new GoogleGenAI({ apiKey: `${GEMINI_API_KEY}` });
// Helper functions (from your original file)
async function parseRepoUrl(repoUrl) {
const parsed = new URL(repoUrl);
const pathParts = parsed.pathname.replace(/^\/|\/$/g, "").split("/");
if (pathParts.length < 2) {
throw new Error("Invalid GitHub repository URL.");
}
const owner = pathParts[0];
const repo = pathParts[1].replace(".git", "");
return { owner, repo };
}
async function getRepoInfo(owner, repo) {
const url = `https://api.github.com/repos/${owner}/${repo}`;
const resp = await axios.get(url, { headers: HEADERS });
return resp.data;
}
async function getLanguages(owner, repo) {
const url = `https://api.github.com/repos/${owner}/${repo}/languages`;
const resp = await axios.get(url, { headers: HEADERS });
return Object.keys(resp.data);
}
async function getContributorsCount(owner, repo) {
const url = `https://api.github.com/repos/${owner}/${repo}/contributors?per_page=1&anon=1`;
const resp = await axios.get(url, { headers: HEADERS });
const linkHeader = resp.headers.link;
if (linkHeader && linkHeader.includes('rel="last"')) {
const lastPage = linkHeader.match(/page=(\d+)>; rel="last"/)[1];
return parseInt(lastPage, 10);
}
return resp.data.length;
}
async function getCommitsCount(owner, repo) {
const url = `https://api.github.com/repos/${owner}/${repo}/commits?per_page=1`;
const resp = await axios.get(url, { headers: HEADERS });
const linkHeader = resp.headers.link;
if (linkHeader && linkHeader.includes('rel="last"')) {
const lastPage = linkHeader.match(/page=(\d+)>; rel="last"/)[1];
return parseInt(lastPage, 10);
}
return resp.data.length;
}
function isImportantFile(filePath, fileName) {
const lowerName = fileName.toLowerCase();
if ([...SKIP_KEYWORDS].some(skip => lowerName.includes(skip))) {
return false;
}
if (!IMPORTANT_FILE_EXTENSIONS.some(ext => fileName.endsWith(ext))) {
return false;
}
const parts = filePath.toLowerCase().split("/");
if ([...IMPORTANT_DIRS].some(dir => parts.includes(dir))) {
return true;
}
if (lowerName.includes("main") || lowerName.includes("app") || parts.length === 1) {
return true;
}
return false;
}
async function getCodeFiles(owner, repo, path = "") {
const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`;
try {
const resp = await axios.get(url, { headers: HEADERS });
if (resp.status === 404) {
return {};
}
const items = resp.data;
const codeData = {};
for (const item of items) {
const filePath = item.path;
const fileName = item.name;
if (item.type === "file" && isImportantFile(filePath, fileName)) {
try {
const fileResp = await axios.get(item.download_url);
// Limit file size to prevent overwhelming the API
const content = fileResp.data.toString();
codeData[filePath] = content.length > 5000 ? content.slice(0, 5000) + "\n... (truncated)" : content;
} catch {
continue;
}
} else if (item.type === "dir") {
const subCodeData = await getCodeFiles(owner, repo, item.path);
Object.assign(codeData, subCodeData);
}
}
return codeData;
} catch (error) {
console.error(`Error fetching contents for ${path}:`, error.message);
return {};
}
}
async function getReadme(owner, repo) {
const url = `https://api.github.com/repos/${owner}/${repo}/readme`;
try {
const resp = await axios.get(url, { headers: HEADERS });
const content = resp.data.content;
return atob(content);
} catch {
return "No README found.";
}
}
async function analyzeWithGemini(projectData, hquery){
const response = await ai.models.generateContent({
// model: "gemini-2.0-flash",
model: "gemini-2.5-flash-preview-05-20",
contents:
`${projectData}`,
config: {
responseMimeType: "application/json",
systemInstruction: `${SYSTEM_PROMPT+'\n\n'+"hackathon requirements: "+hquery}`,
responseSchema: {
type: Type.OBJECT,
properties:{
langs_used:{
type: Type.ARRAY,
items:{
type: Type.STRING
}
},
tech_stack:{
type: Type.ARRAY,
items:{
type: Type.STRING
}
},
readme:{
type: Type.STRING
},
matched_requirements:{
type: Type.ARRAY,
items:{
type:Type.OBJECT,
properties:{
requirement:{
type:Type.STRING
},
matched:{
type: Type.BOOLEAN
}
}
}
},
final_remarks:{
type: Type.STRING
},
}
},
maxOutputTokens: 7000,
temperature: 0.3
},
});
// console.log(response.text);
return(response.text);
}
// Main route to analyze GitHub repository
app.get('/analyze-repo', async (req, res) => {
try {
const { repoUrl, hreq } = req.query;
const hquery= hreq?.replaceAll("+"," ") || hreq?.replaceAll("%20"," ");
if (!repoUrl) {
return res.status(400).json({
error: 'Repository URL is required',
message: 'Please provide a repoUrl query parameter'
});
}
// Validate environment variables
if (!GITHUB_TOKEN) {
return res.status(500).json({
error: 'GitHub token not configured',
message: 'GITHUB_TOKEN environment variable is required'
});
}
if (!GEMINI_API_KEY) {
return res.status(500).json({
error: 'Gemini API key not configured',
message: 'GEMINI_API_KEY environment variable is required'
});
}
console.log(`Analyzing repository: ${repoUrl}`);
// Parse repository URL
const { owner, repo } = await parseRepoUrl(repoUrl);
// Gather all repository data
const [repoInfo, languages, contributors, commits, readme, codeFiles] = await Promise.all([
getRepoInfo(owner, repo),
getLanguages(owner, repo),
getContributorsCount(owner, repo),
getCommitsCount(owner, repo),
getReadme(owner, repo),
getCodeFiles(owner, repo)
]);
// Create the data model
const projectData = {
repository: {
name: repoInfo.name,
description: repoInfo.description || "No description",
url: repoUrl,
owner: owner,
stars: repoInfo.stargazers_count,
createdAt: repoInfo.created_at,
updatedAt: repoInfo.updated_at
},
statistics: {
languages: languages,
contributorsCount: contributors,
commitsCount: commits
},
documentation: {
readme: readme //.slice(0, 2000) + (readme.length > 2000 ? "\n... (truncated)" : "")
},
codeFiles: codeFiles,
analysis: {
totalFiles: Object.keys(codeFiles).length,
fileTypes: [...new Set(Object.keys(codeFiles).map(file => file.split('.').pop()))],
directories: [...new Set(Object.keys(codeFiles).map(file => file.split('/')[0]))]
}
};
console.log(projectData);
// Analyze with Gemini AI
const aiAnalysis = await analyzeWithGemini(JSON.stringify(projectData), hquery);
// console.log(aiAnalysis);
// Return the final response
res.json({
success: true,
aiAnalysis: JSON.parse(aiAnalysis),
repository: {
name: repoInfo.name,
description: repoInfo.description || "No description",
url: repoUrl,
owner: owner,
stars: repoInfo.stargazers_count,
createdAt: repoInfo.created_at,
updatedAt: repoInfo.updated_at,
commitsCount: commits
},
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('Error analyzing repository:', error);
res.status(500).json({
success: false,
error: error.message,
timestamp: new Date().toISOString()
});
}
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
env: {
githubToken: !!GITHUB_TOKEN,
geminiApiKey: !!GEMINI_API_KEY
}
});
});
// Root endpoint
app.get('/', (req, res) => {
res.json({
message: 'GitHub Repository Analyzer API',
endpoints: {
analyze: '/analyze-repo?repoUrl=<github-repo-url>',
health: '/health'
},
example: '/analyze-repo?repoUrl=https://github.com/facebook/react'
});
});
// Error handling middleware
app.use((error, req, res, next) => {
console.error('Unhandled error:', error);
res.status(500).json({
success: false,
error: 'Internal server error',
timestamp: new Date().toISOString()
});
});
// Start server
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
console.log(`📊 Analyze repos at: http://localhost:${PORT}/analyze-repo?repoUrl=<github-repo-url>`);
console.log(`💚 Health check at: http://localhost:${PORT}/health`);
});