feat: add compiler fit for nextjs

This commit is contained in:
2024-12-29 16:11:54 +08:00
parent 5fdc916cba
commit 3093f7e624
21 changed files with 5533 additions and 151 deletions
+73
View File
@@ -0,0 +1,73 @@
'use server';
import Docker from 'dockerode';
import fs from 'fs';
import path from 'path';
// 创建 Docker 客户端实例
const docker = new Docker();
// 定义执行代码的 Server Action
export const runCode = async (params: { code: string; language: string }) => {
const { code, language } = params;
if (!code || !language) {
throw new Error('Code and language are required.');
}
const supportedLanguages = ['c', 'java'];
if (!supportedLanguages.includes(language)) {
throw new Error(`Language '${language}' is not supported. Only 'c' and 'java' are supported.`);
}
// 根据语言选择文件名和编译命令
const fileName = language === 'c' ? 'main.c' : 'Main.java';
const compileCmd = language === 'c' ? 'gcc main.c -o main && ./main' : 'javac Main.java && java Main';
// 创建临时目录用于存储代码文件
const tempDir = path.join('/tmp', `${Date.now()}`);
fs.mkdirSync(tempDir, { recursive: true });
const filePath = path.join(tempDir, fileName);
fs.writeFileSync(filePath, code);
try {
// 创建并启动 Docker 容器
const container = await docker.createContainer({
Image: 'fly6516.synology.me:8080/multilang:latest',
Cmd: ['sh', '-c', compileCmd],
AttachStdout: true,
AttachStderr: true,
Tty: false,
HostConfig: {
Binds: [`${tempDir}:/workspace`], // 将临时目录挂载到容器
},
WorkingDir: '/workspace',
});
await container.start();
const logs = await container.logs({ stdout: true, stderr: true, follow: true });
let output = '';
logs.on('data', (data: Buffer) => {
output += data.toString().replace(/[\x00-\x1F\x7F]/g, ''); // 去除不可见字符
});
const exitCode = await container.wait();
await container.remove();
if (exitCode.StatusCode === 0) {
return { output };
} else {
// 返回详细的错误信息
return { error: `Execution failed with exit code ${exitCode.StatusCode}. Output: ${output}` };
}
} catch (error) {
// 捕获并返回详细的错误信息
return { error: `An error occurred: ${(error as Error).message}` };
} finally {
// 清理临时目录
fs.rmSync(tempDir, { recursive: true, force: true });
}
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

+21
View File
@@ -0,0 +1,21 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
}
+34
View File
@@ -0,0 +1,34 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
{children}
</body>
</html>
);
}
+62
View File
@@ -0,0 +1,62 @@
'use client';
import { useState } from 'react';
import { runCode } from '@/actions'; // 导入 Server Action
const CodeRunner = () => {
const [code, setCode] = useState('');
const [language, setLanguage] = useState('c');
const [output, setOutput] = useState('');
const [error, setError] = useState('');
const runCodeHandler = async () => {
try {
// 调用 Server Action 执行代码
const result = await runCode({ code, language });
setOutput(result.output);
setError('');
} catch (err) {
setError((err as Error).message);
setOutput('');
}
};
return (
<div>
<h1>Code Runner</h1>
<textarea
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="Write your code here"
rows={10}
cols={50}
/>
<div>
<label>
Language:
<select value={language} onChange={(e) => setLanguage(e.target.value)}>
<option value="c">C</option>
<option value="java">Java</option>
</select>
</label>
</div>
<button onClick={runCodeHandler}>Run Code</button>
{output && (
<div>
<h3>Output:</h3>
<pre>{output}</pre>
</div>
)}
{error && (
<div>
<h3>Error:</h3>
<pre>{error}</pre>
</div>
)}
</div>
);
};
export default CodeRunner;