refactor: move doas-wrapper to function, rename output->util
This commit is contained in:
parent
82dd07f293
commit
c98adcee74
3 changed files with 31 additions and 30 deletions
29
src/main.rs
29
src/main.rs
|
@ -6,7 +6,7 @@ use ntex::{
|
|||
};
|
||||
|
||||
mod error;
|
||||
mod output;
|
||||
mod util;
|
||||
|
||||
type Result<T> = core::result::Result<T, error::ErrorWrapper>;
|
||||
|
||||
|
@ -47,22 +47,16 @@ async fn root() -> impl Responder {
|
|||
async fn poweroff(cfg: State<Config>) -> Result<impl Responder> {
|
||||
const EXE: &str = "/sbin/poweroff";
|
||||
|
||||
let mut cmd = if let Some(doas) = &cfg.doas {
|
||||
let mut cmd = tokio::process::Command::new(&**doas);
|
||||
cmd.arg(EXE);
|
||||
cmd
|
||||
} else {
|
||||
tokio::process::Command::new(EXE)
|
||||
};
|
||||
|
||||
cmd.kill_on_drop(false).spawn()?;
|
||||
util::run_as_root(&cfg.doas, EXE)
|
||||
.kill_on_drop(false)
|
||||
.spawn()?;
|
||||
|
||||
Ok("OK")
|
||||
}
|
||||
|
||||
#[web::get("/ping")]
|
||||
async fn ping() -> Result<impl Responder> {
|
||||
Ok(output::format(
|
||||
Ok(util::format_output(
|
||||
tokio::process::Command::new("/bin/ping")
|
||||
.arg("-c")
|
||||
.arg("4")
|
||||
|
@ -83,15 +77,10 @@ async fn clients() -> Result<impl Responder> {
|
|||
async fn temp(cfg: State<Config>) -> Result<impl Responder> {
|
||||
const EXE: &str = "/usr/bin/vcgencmd";
|
||||
|
||||
let mut cmd = if let Some(doas) = &cfg.doas {
|
||||
let mut cmd = tokio::process::Command::new(&**doas);
|
||||
cmd.arg(EXE);
|
||||
cmd
|
||||
} else {
|
||||
tokio::process::Command::new(EXE)
|
||||
};
|
||||
|
||||
let out = cmd.arg("measure_temp").output().await?;
|
||||
let out = util::run_as_root(&cfg.doas, EXE)
|
||||
.arg("measure_temp")
|
||||
.output()
|
||||
.await?;
|
||||
|
||||
Ok(String::from_utf8(out.stdout)?)
|
||||
}
|
||||
|
|
|
@ -1,10 +0,0 @@
|
|||
use std::process::Output;
|
||||
|
||||
pub fn format(out: Output) -> String {
|
||||
format!(
|
||||
"exited with {}\n\nstdout:\n{}\n----\n\nstderr:\n{}",
|
||||
out.status.code().unwrap_or(-1),
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr),
|
||||
)
|
||||
}
|
22
src/util.rs
Normal file
22
src/util.rs
Normal file
|
@ -0,0 +1,22 @@
|
|||
use std::process::Output;
|
||||
|
||||
use tokio::process::Command;
|
||||
|
||||
pub fn run_as_root(doas: &Option<impl AsRef<String>>, exe: &str) -> Command {
|
||||
if let Some(doas) = doas {
|
||||
let mut cmd = Command::new(doas.as_ref());
|
||||
cmd.arg(exe);
|
||||
cmd
|
||||
} else {
|
||||
Command::new(exe)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format_output(out: Output) -> String {
|
||||
format!(
|
||||
"exited with {}\n\nstdout:\n{}\n----\n\nstderr:\n{}",
|
||||
out.status.code().unwrap_or(-1),
|
||||
String::from_utf8_lossy(&out.stdout),
|
||||
String::from_utf8_lossy(&out.stderr),
|
||||
)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue