(feat) add php executor

This commit is contained in:
b1ek 2024-02-19 16:34:45 +10:00
parent ca8c439df6
commit 63b9f40815
Signed by: blek
GPG Key ID: 14546221E3595D0C
4 changed files with 62 additions and 5 deletions

View File

@ -1,13 +1,14 @@
use crate::executor::python::PythonExecutor;
use crate::executor::{php::PhpExecutor, python::PythonExecutor};
pub mod php;
pub mod python;
pub mod helper;
pub fn executors() -> Vec<Box<dyn Executor>> {
vec![
Box::new(PhpExecutor {}),
Box::new(PythonExecutor {}),
]
}

View File

@ -1,4 +1,4 @@
use std::{fs::create_dir_all, process::ExitStatus};
use std::{fs::create_dir_all, io::Read, process::{ChildStdout, ExitStatus}};
use rand::{distributions::Alphanumeric, Rng, thread_rng};
@ -28,3 +28,17 @@ pub fn exit_code_msg(code: ExitStatus) -> String {
"Command exited with unknown code".into()
}
}
pub fn get_stdout(stdout: Option<ChildStdout>) -> Result<String, String> {
let ret = {
if let Some(mut sout) = stdout {
let mut buf = vec![];
sout.read_to_end(&mut buf).map_err(|x| x.to_string())?;
String::from_utf8(buf).map_err(|x| x.to_string())?
} else {
"Couldn't get stdout from the process".into()
}
};
Ok(ret)
}

42
src/executor/php.rs Normal file
View File

@ -0,0 +1,42 @@
use std::fs;
use std::process::Command;
use std::process::Stdio;
use super::Executor;
use super::helper::*;
#[derive(Debug, Clone, Copy)]
pub struct PhpExecutor {}
impl Executor for PhpExecutor {
fn id(&self) -> String {
"php".into()
}
fn exec(&self, code: String) -> Result<String, String> {
assure_dir_exists().map_err(|x| x.to_string())?;
let path = create_path();
// 1. Save the code
fs::write(path.clone(), code).map_err(|x| x.to_string())?;
// 2. Run it!
let mut out = Command::new("php")
.arg(path)
.stdout(Stdio::piped())
.spawn()
.map_err(|x| x.to_string())?;
// 3. Grab the exit code
let exit_status = out.wait().map_err(|x| x.to_string())?;
let mut stdout: String = get_stdout(out.stdout)?;
stdout += "\n\n";
stdout += exit_code_msg(exit_status).as_str();
Ok(stdout)
}
}

View File

@ -2,7 +2,7 @@ use serde::{Serialize, Deserialize};
use warp::{reject::Rejection, reply::{json, with_status, Reply}, Filter, http::StatusCode};
use crate::{executor::{executors, executors_id, get_executor, python::PythonExecutor, Executor}, SharedState};
use crate::{executor::{executors, get_executor}, SharedState};
#[derive(Serialize, Deserialize)]
struct ExecutorData {