Mahdi Naser Moghadasi
Fix C++ execution: remove duplicate helpers, use namespace std, fix Solution method calls
9a2c618 Download app/api/execute-cpp/route.ts from brightmind-ai/codepractice-ai: direct link, hf CLI and curl.
- Browser
- Download file 5.97 kB
-
https://huggingface.co/spaces/brightmind-ai/codepractice-ai/resolve/main/app/api/execute-cpp/route.ts
- Command line
-
hf download hf://spaces/brightmind-ai/codepractice-ai/app/api/execute-cpp/route.ts
-
curl -L -o route.ts https://huggingface.co/spaces/brightmind-ai/codepractice-ai/resolve/main/app/api/execute-cpp/route.ts
5.97 kB
| import { NextRequest, NextResponse } from 'next/server' | |
| import { spawn } from 'child_process' | |
| import { writeFile, unlink } from 'fs/promises' | |
| import { join } from 'path' | |
| import { tmpdir } from 'os' | |
| export async function POST(request: NextRequest) { | |
| let tempFile: string | null = null | |
| let execFile: string | null = null | |
| try { | |
| const body = await request.json() | |
| const { code, testCase, functionName } = body | |
| if (!code || !testCase) { | |
| return NextResponse.json( | |
| { error: 'Code and test case are required' }, | |
| { status: 400 } | |
| ) | |
| } | |
| // Create a temporary C++ file | |
| const tempDir = tmpdir() | |
| const fileId = `${Date.now()}_${Math.random().toString(36).substring(7)}` | |
| tempFile = join(tempDir, `cpp_exec_${fileId}.cpp`) | |
| execFile = join(tempDir, `cpp_exec_${fileId}`) | |
| // Wrap user code with main function for testing | |
| const wrappedCode = ` | |
| #include <iostream> | |
| #include <vector> | |
| #include <string> | |
| #include <sstream> | |
| #include <unordered_map> | |
| using namespace std; | |
| ${code} | |
| // Helper to convert C++ vector to JSON string | |
| string convertToJson(const vector<int>& vec) { | |
| ostringstream oss; | |
| oss << "["; | |
| for (size_t i = 0; i < vec.size(); ++i) { | |
| if (i > 0) oss << ","; | |
| oss << vec[i]; | |
| } | |
| oss << "]"; | |
| return oss.str(); | |
| } | |
| // Helper to convert int to JSON string | |
| string convertToJson(int val) { | |
| return to_string(val); | |
| } | |
| int main() { | |
| try { | |
| // Test input | |
| ${generateCppTestCode(testCase.input, functionName)} | |
| } catch (const exception& e) { | |
| cerr << "ERROR: " << e.what() << endl; | |
| return 1; | |
| } | |
| return 0; | |
| } | |
| ` | |
| await writeFile(tempFile, wrappedCode, 'utf-8') | |
| // Compile and execute C++ code | |
| const result = await new Promise<{ output: string; error: string; exitCode: number }>(async (resolve) => { | |
| // First compile | |
| const compileResult = await new Promise<{ success: boolean; error: string }>((resolveCompile) => { | |
| const gpp = spawn('g++', ['-std=c++17', '-o', execFile!, tempFile!]) | |
| let compileError = '' | |
| gpp.stderr.on('data', (data) => { | |
| compileError += data.toString() | |
| }) | |
| gpp.on('close', (code) => { | |
| resolveCompile({ success: code === 0, error: compileError }) | |
| }) | |
| setTimeout(() => { | |
| gpp.kill() | |
| resolveCompile({ success: false, error: 'Compilation timeout' }) | |
| }, 5000) | |
| }) | |
| if (!compileResult.success) { | |
| resolve({ output: '', error: compileResult.error, exitCode: 1 }) | |
| return | |
| } | |
| // Then execute | |
| const exec = spawn(execFile!) | |
| let output = '' | |
| let error = '' | |
| exec.stdout.on('data', (data) => { | |
| output += data.toString() | |
| }) | |
| exec.stderr.on('data', (data) => { | |
| error += data.toString() | |
| }) | |
| exec.on('close', (code) => { | |
| resolve({ output: output.trim(), error: error.trim(), exitCode: code || 0 }) | |
| }) | |
| // Timeout after 5 seconds | |
| setTimeout(() => { | |
| exec.kill() | |
| resolve({ output: '', error: 'Execution timeout (5 seconds)', exitCode: -1 }) | |
| }, 5000) | |
| }) | |
| // Clean up temp files | |
| if (tempFile) { | |
| try { | |
| await unlink(tempFile) | |
| } catch (e) { | |
| // Ignore cleanup errors | |
| } | |
| } | |
| if (execFile) { | |
| try { | |
| await unlink(execFile) | |
| } catch (e) { | |
| // Ignore cleanup errors | |
| } | |
| } | |
| if (result.exitCode !== 0 || result.error) { | |
| if (result.output && result.output.trim() && !result.error.includes('ERROR')) { | |
| try { | |
| const actualOutput = JSON.parse(result.output) | |
| return NextResponse.json({ | |
| success: true, | |
| output: actualOutput, | |
| }) | |
| } catch (e) { | |
| // If parsing fails, return the error | |
| } | |
| } | |
| return NextResponse.json({ | |
| success: false, | |
| error: result.error || 'Execution failed', | |
| output: result.output, | |
| }) | |
| } | |
| if (!result.output || !result.output.trim()) { | |
| return NextResponse.json({ | |
| success: false, | |
| error: 'No output from code execution', | |
| rawOutput: result.output, | |
| }) | |
| } | |
| try { | |
| const actualOutput = JSON.parse(result.output) | |
| return NextResponse.json({ | |
| success: true, | |
| output: actualOutput, | |
| }) | |
| } catch (e) { | |
| return NextResponse.json({ | |
| success: false, | |
| error: `Failed to parse output as JSON: ${result.output}`, | |
| rawOutput: result.output, | |
| }) | |
| } | |
| } catch (error: any) { | |
| // Clean up temp files on error | |
| if (tempFile) { | |
| try { | |
| await unlink(tempFile) | |
| } catch (e) { | |
| // Ignore cleanup errors | |
| } | |
| } | |
| if (execFile) { | |
| try { | |
| await unlink(execFile) | |
| } catch (e) { | |
| // Ignore cleanup errors | |
| } | |
| } | |
| return NextResponse.json( | |
| { error: error.message || 'Internal server error' }, | |
| { status: 500 } | |
| ) | |
| } | |
| } | |
| function generateCppTestCode(input: any, functionName: string): string { | |
| // Generate C++ code to call the function with test input | |
| // Create Solution instance and call the method | |
| if (Array.isArray(input) && input.length === 1) { | |
| return `Solution solution; | |
| auto result = solution.${functionName}(${formatCppValue(input[0])}); | |
| cout << convertToJson(result) << endl;` | |
| } else if (Array.isArray(input) && input.length === 2) { | |
| return `Solution solution; | |
| auto result = solution.${functionName}(${formatCppValue(input[0])}, ${formatCppValue(input[1])}); | |
| cout << convertToJson(result) << endl;` | |
| } else { | |
| return `Solution solution; | |
| auto result = solution.${functionName}(${formatCppValue(input)}); | |
| cout << convertToJson(result) << endl;` | |
| } | |
| } | |
| function formatCppValue(value: any): string { | |
| if (Array.isArray(value)) { | |
| return `vector<int>{${value.join(', ')}}` | |
| } | |
| if (typeof value === 'string') { | |
| return `"${value}"` | |
| } | |
| return String(value) | |
| } | |