0% found this document useful (0 votes)
6 views11 pages

Code Review Bot Backend Development

Uploaded by

dihagat825
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views11 pages

Code Review Bot Backend Development

Uploaded by

dihagat825
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Week-IV Milestone Report

1. Backend development started and core server functionality


implemented
The backend development for the Code Review Bot project was started in Week-
IV.
- The server-side code is implemented using [Link] and Express, located in the
`server` directory.
- Multiple API routes are created for code analysis, feedback collection,
dashboard statistics, GitHub integration, and rejection tracking.
- Utility modules for code analysis in Python, Java, JavaScript, and C/C++ are
present, leveraging tools like Pylint, ESLint, Checkstyle, and Tree-sitter.

(Fig: [Link])

The main server file ([Link]): - Show the Express app setup, middleware
(CORS, JSON), and route registrations.
fig: Folder Structure

/*

// Helper to fetch past rejection comments for the same code and language

async function getRejectionComments(code, language) {

try {

const { data, error } = await supabase

.from("feedback")

.select("comment, suggestion")

.eq("language", language)

.eq("code", code)

.eq("decision", "reject");

if (error) {

[Link]("Error fetching rejection comments:", error);

return [];
}

return data

.filter(d => [Link]?.trim())

.map(d => `• Previously, the suggestion "${[Link]}" was rejected because: "${[Link]}"`);

} catch (err) {

[Link]("Supabase fetch error:", err);

return [];

// Main analysis route

[Link]("/", async (req, res) => {

const { language, code } = [Link];

if (!language || !code) {

return [Link](400).json({ error: "Missing code or language" });

const rejectionComments = await getRejectionComments(code, language);

// Python

if (language === "python") {

const filePath = [Link](__dirname, "../temp/[Link]");

[Link](filePath, code);

exec("python python/analyze_python.py", async (err, stdout, stderr) => {

[Link]("Python STDOUT:", stdout);

[Link]("Python STDERR:", stderr);


let staticSuggestions = [];

try {

staticSuggestions = [Link](stdout);

} catch (e) {

[Link]("Parse error:", e);

const { rawReview, suggestions: geminiSuggestions } =

await reviewWithGemini(code, language, rejectionComments);

[Link]({

suggestions: [...staticSuggestions, ...geminiSuggestions],

geminiReview: { rawReview, suggestions: geminiSuggestions }

});

}); */

- Defines an Express route (POST /api/analyze) that receives code and language from
the client.

- Depending on the language (Python, JavaScript, Java, C/C++), it:

1. Runs static analysis using language-specific tools (Pylint, ESLint, Checkstyle, Tree-
sitter).
2. Calls Gemini AI for advanced code review and suggestions.
3. Fetches any previously rejected feedback for the same code/language from
Supabase.

- Combines static and AI suggestions, then sends them back in the response.

- Handles errors and supports only specific languages (Python, JavaScript, Java, C,
C++).

This route is the core backend logic for analyzing code and providing feedback in your
project.
/*
const { GoogleGenerativeAI } = require("@google/generative-ai");

require("dotenv").config();

const genAI = new GoogleGenerativeAI([Link].GEMINI_API_KEY);

/**

* Calls Gemini and returns:

* - rawReview: string summary of the review

* - suggestions: [{ message, line, replacement?, source }]

* @param {string} code - Code to analyze

* @param {string} language - Language of the code

* @param {Array<string>} rejectionComments - Array of previous rejection comments

*/

async function reviewWithGemini(code, language = "python", rejectionComments = []) {

try {

const model = [Link]({ model: "models/gemini-1.5-flash" });

// Format rejection feedback

let rejectionNotes = "";

if ([Link] > 0) {

rejectionNotes =

`The following feedback was previously rejected by the user. Avoid making similar suggestions:\n` +

[Link]((comment, idx) => `${idx + 1}. ${comment}`).join("\n") +

`\n\n`;

const prompt = `

${rejectionNotes}

You are a code reviewer. Analyze the following ${language} code and return your feedback in the
following JSON format:
{

"review": "<overall_summary>",

"suggestions": [

"line": <line_number>,

"message": "<explanation of issue or improvement>",

"replacement": {

"from": "<existing code snippet if applicable>",

"to": "<replacement suggestion if applicable>"

Only return the JSON. Do not add any explanations or commentary.

Code:

\`\`\`${language}

${code}

\`\`\`

`;

const result = await [Link](prompt);

const response = await [Link];

const raw = [Link]();

// Extract JSON safely

let parsed = null;

try {
const jsonStart = [Link]("{");

const jsonEnd = [Link]("}");

const jsonText = [Link](jsonStart, jsonEnd + 1);

parsed = [Link](jsonText);

} catch (e) {

[Link]("Gemini JSON parse error:", [Link]);

[Link]("Gemini raw output:", raw);

return {

rawReview: "Gemini returned invalid JSON. Please check the model output.",

suggestions: []

};

return {

rawReview: [Link],

suggestions: ([Link] || []).map(s => ({

line: [Link] || null,

message: [Link] || '',

source: "gemini",

replacement: [Link] || null

}))

};

} catch (err) {

[Link]("Gemini Error:", [Link]);

return {

rawReview: "Gemini failed to review the code.",

suggestions: []

};

}
}

[Link] = reviewWithGemini;

*/

The above code show’s how AI-powered code review is implemented.

2. Environment Setup
The backend uses both [Link] and Python
environments to support code analysis and
server operations. - All required libraries and
frameworks are installed and managed
via [Link] for [Link] (including
Express, Supabase JS, Google Generative AI,
ESLint, Axios, etc.). - Python dependencies
(such as Pylint for code analysis) are installed
as needed for the analysis scripts. -
Environment variables (such as API keys,
database URLs, and service credentials) are
securely managed using a .env file and loaded
in the code using the dotenv package. - The
server is configured to run on port 5000 and
uses middleware for CORS and JSON parsing
to handle requests from the frontend. - This
setup ensures the backend is ready for
development, testing, and secure operation,
with all dependencies and configurations
properly managed.

3. Server Configuration
 The Express server is initialized in [Link].
 Middleware is set up for:
 CORS (Cross-Origin Resource Sharing) to allow requests from the
frontend.
 JSON parsing to handle API request bodies.
 All API routes are registered:
/api/analyze for code analysis
/api/feedback for feedback submission and retrieval
/api/stats for dashboard statistics
/api/github for GitHub OAuth and integration
/api/rejections for tracking rejected suggestions
The server listens on port 5000.

4. Database Integration
 Supabase is used as the backend database.
 The Supabase client is initialized in [Link] using environment
variables for URL and service key.
 Feedback data is stored and retrieved via API endpoints, supporting
decision tracking (accepted/rejected) and user comments.
 The feedback table in Supabase serves as the main dataset for analysis
and reporting.
 User authentication and statistics are also managed via Supabase.
 API routes interact with Supabase to insert, select, and aggregate
feedback and user data.
5. Architecture, Model, and Algorithms
architecture
 The backend is designed with a modular architecture:
 Separate folders for routes, utilities, models, and language-specific
analysis scripts.
 Each API route (e.g., analyze, feedback, dashboardStats, github,
rejections) is implemented in its own file for clarity and maintainability.
 Utility modules handle code analysis for different languages and AI
integration.
 The server uses Express for routing and middleware management

Model

 The main data model is the feedback record, stored in the Supabase
database:
 Fields include language, code, suggestion, decision (accepted/rejected),
comment, timestamp, and suggestion type.
 The feedback table is used for storing user actions, code review
suggestions, and comments.
 User authentication and statistics are also modeled in Supabase.

Algorithms

 Static code analysis algorithms are implemented for multiple languages:


 Python: Uses Pylint via a Python script to analyze code and return issues.
 JavaScript: Uses ESLint to lint code and provide suggestions and
autofixes.
 Java: Uses Checkstyle to check code style and report violations.
 C/C++: Uses Tree-sitter to parse codeand extract function definitions and
other structural info.
 AI-powered review:
 Integrates Google Gemini to provide advanced code feedback and
suggestions.
 Combines static analysis results with AI-generated suggestions for
comprehensive review.
 Feedback collection and rejection tracking:
 The system records user feedback on suggestions, tracks rejected
suggestions, and uses this data to improve future reviews.
 Dashboard statistics:
 Aggregates feedback data to provide error type breakdowns and user
action statistics for admin analysis.

Fig: Gemini Integration

You might also like