refactor: unify scripting commands

This commit is contained in:
2025-02-16 01:06:03 -05:00
parent 5752e94ad2
commit c4702a74f2
3 changed files with 62 additions and 79 deletions

View File

@@ -1,4 +1,7 @@
use crate::State;
use crate::{
State,
scripting::{eval, exec, reload},
};
use http_body_util::{BodyExt, Empty, Full, combinators::BoxBody};
use hyper::{Method, Request, Response, StatusCode, body::Bytes};
@@ -9,57 +12,32 @@ pub async fn handle(
let path = request.uri().path().to_owned();
match (request.method(), path.as_str()) {
(&Method::POST, "/reload") => {
let lua = state.lua.lock();
let config_path = match lua.globals().get::<String>("config_path") {
Ok(path) => path,
Err(error) => {
return Ok(status_code_response(
StatusCode::INTERNAL_SERVER_ERROR,
Some(full(format!(
"failed to get config_path from lua globals: {error:?}"
))),
));
}
};
if let Err(error) = match &std::fs::read_to_string(&config_path) {
Ok(string) => lua.load(string).exec(),
Err(error) => {
return Ok(status_code_response(
StatusCode::INTERNAL_SERVER_ERROR,
Some(full(format!("failed to read {config_path:?}: {error:?}"))),
));
}
} {
return Ok(status_code_response(
StatusCode::INTERNAL_SERVER_ERROR,
Some(full(format!(
"failed to execute configuration as lua code: {error:?}"
))),
));
}
Ok(Response::new(empty()))
}
(&Method::POST, "/reload") => Ok(match reload(&state.lua.lock()) {
Ok(()) => Response::new(empty()),
Err(error) => status_code_response(
StatusCode::INTERNAL_SERVER_ERROR,
Some(full(format!("{error:?}"))),
),
}),
(&Method::POST, "/eval" | "/exec") => {
let bytes = request.into_body().collect().await?.to_bytes();
let code = match std::str::from_utf8(&bytes) {
Ok(code) => code,
Ok(match std::str::from_utf8(&bytes) {
Ok(code) => {
let lua = state.lua.lock();
Response::new(full(match path.as_str() {
"/eval" => format!("{:?}", eval(&lua, code)),
"/exec" => format!("{:?}", exec(&lua, code)),
_ => unreachable!(),
}))
}
Err(error) => {
return Ok(status_code_response(
StatusCode::BAD_REQUEST,
Some(full(format!("invalid utf-8 data received: {error:?}"))),
));
}
};
let chunk = state.lua.lock().load(code);
Ok(Response::new(full(match path.as_str() {
"/eval" => format!("{:?}", chunk.eval::<String>()),
"/exec" => format!("{:?}", chunk.exec()),
_ => unreachable!(),
})))
})
}
(&Method::GET, "/ping") => Ok(Response::new(full("pong!"))),