Add enquote util and change run_command_async
The new enquote function is used to enquote command input. For simplicity reasons the run_command_async doesn't read from stdout and stderr separately anymore but uses `.output().await` instead. Signed-off-by: trivernis <trivernis@protonmail.com>pull/9/head
parent
8b8fc8f814
commit
45d2ac84b1
@ -1,26 +1,19 @@
|
||||
use std::io;
|
||||
use std::process::Stdio;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::process::Command;
|
||||
|
||||
/// Asynchronously runs a given command and returns the output
|
||||
pub async fn run_command_async(command: &str, args: &[&str]) -> io::Result<String> {
|
||||
log::trace!("Running command '{}' with args {:?}", command, args);
|
||||
let cmd = Command::new(command)
|
||||
.args(args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()?;
|
||||
let mut stderr = String::new();
|
||||
let mut output = String::new();
|
||||
let process_output: std::process::Output = Command::new(command).args(args).output().await?;
|
||||
|
||||
cmd.stderr.unwrap().read_to_string(&mut stderr).await?;
|
||||
log::trace!("Reading from stderr...");
|
||||
let stderr = String::from_utf8_lossy(&process_output.stderr[..]);
|
||||
let stdout = String::from_utf8_lossy(&process_output.stdout[..]);
|
||||
|
||||
if stderr.len() != 0 {
|
||||
log::debug!("STDERR of command {}: {}", command, stderr);
|
||||
}
|
||||
cmd.stdout.unwrap().read_to_string(&mut output).await?;
|
||||
log::trace!("Command output is {}", output);
|
||||
log::trace!("Command output is {}", stdout);
|
||||
|
||||
Ok(output)
|
||||
Ok(stdout.to_string())
|
||||
}
|
||||
|
@ -0,0 +1,5 @@
|
||||
/// Enquotes a string in a safe way
|
||||
pub fn enquote<S: ToString>(value: S) -> String {
|
||||
let value = value.to_string();
|
||||
format!("\"{}\"", value.replace("\"", "\\\""))
|
||||
}
|
@ -1,2 +1,5 @@
|
||||
#[cfg(test)]
|
||||
mod url_tests;
|
||||
mod url_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod string_tests;
|
||||
|
@ -0,0 +1,8 @@
|
||||
use crate::string::enquote;
|
||||
|
||||
#[test]
|
||||
fn test_enquote() {
|
||||
assert_eq!(enquote("hello"), r#""hello""#);
|
||||
assert_eq!(enquote(r#"hello "there""#), r#""hello \"there\"""#);
|
||||
assert_eq!(enquote(""), r#""""#);
|
||||
}
|
@ -1,13 +1,10 @@
|
||||
use bot_coreutils::process::run_command_async;
|
||||
|
||||
use crate::utils::error::BotResult;
|
||||
use bot_coreutils::string::enquote;
|
||||
|
||||
/// Runs the qalc command with the given expression
|
||||
pub async fn qalc(expression: &str) -> BotResult<String> {
|
||||
let result = run_command_async(
|
||||
"qalc",
|
||||
&["-m", "1000", format!("\"{}\"", &*expression).as_str()],
|
||||
)
|
||||
.await?;
|
||||
let result = run_command_async("qalc", &["-m", "1000", enquote(expression).as_str()]).await?;
|
||||
Ok(result)
|
||||
}
|
||||
|
Loading…
Reference in New Issue