From eed90a9fe4a1c4026011e951337ad752c89cdb67 Mon Sep 17 00:00:00 2001 From: ngc2207 Date: Sat, 11 Jan 2025 00:40:50 +0800 Subject: [PATCH] feat(docker): support C and C++ code compilation and execution in Docker environment feat(page): redirect HomePage to playground --- src/actions/docker/run.ts | 25 +++++++++++++++++++------ src/app/(main)/page.tsx | 4 +++- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/actions/docker/run.ts b/src/actions/docker/run.ts index 2a4ece0..dff4170 100644 --- a/src/actions/docker/run.ts +++ b/src/actions/docker/run.ts @@ -33,9 +33,22 @@ async function prepareEnvironment(docker: Dockerode, imageGCC: string) { async function compileAndRun( code: string, + language: string, docker: Dockerode, imageGCC: string ): Promise { + let compileCommand = ""; + + if (language === "c") { + compileCommand = `gcc main.c -o main && ./main`; + } else if (language === "cpp") { + compileCommand = `g++ main.cpp -o main && ./main`; + } else { + throw new Error("Unsupported language: " + language); + } + + const extension = language === "c" ? "c" : "cpp"; + const container = await docker.createContainer({ Image: imageGCC, Cmd: [ @@ -44,7 +57,7 @@ async function compileAndRun( `export LANG=C.UTF-8 && printf '%s' '${code.replace( /'/g, "'\\''" - )}' > main.c && gcc main.c -o main && ./main`, + )}' > main.${extension} && ${compileCommand}`, ], Tty: false, }); @@ -119,9 +132,9 @@ export async function runCode( let container: Dockerode.Container | undefined; try { - if (language === "c") { + if (language === "c" || language === "cpp") { await prepareEnvironment(docker, imageGCC); - container = await compileAndRun(code, docker, imageGCC); + container = await compileAndRun(code, language, docker, imageGCC); const stream = await container.attach({ stream: true, stdout: true, @@ -135,13 +148,13 @@ export async function runCode( output: result.output, }; } else { - throw new Error(`不支持的语言: ${language}`); + throw new Error(`Unsupported language: ${language}`); } } catch (error) { - console.error("运行代码时出错:", error); + console.error("Error running code:", error); return { type: "error", - message: error instanceof Error ? error.message : "未知错误", + message: error instanceof Error ? error.message : "Unknown error", output: "", }; } finally { diff --git a/src/app/(main)/page.tsx b/src/app/(main)/page.tsx index ec018ab..db3e3b4 100644 --- a/src/app/(main)/page.tsx +++ b/src/app/(main)/page.tsx @@ -32,6 +32,8 @@ // ); // } +import { redirect } from "next/navigation"; + export default function HomePage() { - return null; + redirect("/playground"); }