Compare commits

...

2 commits

Author SHA1 Message Date
askiiart
1f312e57e5
add run_with_funcs() 2025-01-01 21:05:47 -06:00
askiiart
1cc6903c04
make release compile with opt level 3 2025-01-01 20:54:10 -06:00
3 changed files with 236 additions and 98 deletions

View file

@ -5,3 +5,6 @@ version = "0.1.1"
edition = "2021" edition = "2021"
license = "GPL-3.0-only" license = "GPL-3.0-only"
keywords = ["command", "cmd"] keywords = ["command", "cmd"]
[profile.release]
opt-level = 3

View file

@ -1,6 +1,6 @@
use std::cmp::Ordering; use std::cmp::Ordering;
use std::io::{BufRead, BufReader}; use std::io::{BufRead, BufReader, Lines};
use std::process::{Command, Stdio}; use std::process::{ChildStderr, ChildStdout, Command, Stdio};
use std::thread; use std::thread;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@ -9,61 +9,71 @@ mod tests;
/// Holds the output for a command /// Holds the output for a command
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct CmdOutput { pub struct CmdOutput {
lines: Vec<Line>, lines: Option<Vec<Line>>,
status: Option<i32>, status_code: Option<i32>,
start_time: Instant, start_time: Instant,
end_time: Instant, end_time: Instant,
} duration: Duration,
#[derive(Debug, Clone, PartialEq, Eq, Ord)]
pub struct Line {
pub stdout: bool,
pub time: Instant,
pub content: String,
} }
impl CmdOutput { impl CmdOutput {
/// Returns only stdout /// Returns only stdout
pub fn stdout(self) -> Vec<Line> { pub fn stdout(self) -> Option<Vec<Line>> {
return self match self.lines {
.lines Some(lines) => {
.into_iter() return Some(
.filter(|l| { lines
if l.stdout { .into_iter()
return true; .filter(|l| {
} if l.printed_to == LineType::Stdout {
return false; return true;
}) }
.collect(); return false;
})
.collect(),
);
}
None => {
return None;
}
}
} }
/// Returns only stdout /// Returns only stdout
pub fn stderr(self) -> Vec<Line> { pub fn stderr(self) -> Option<Vec<Line>> {
return self match self.lines {
.lines Some(lines) => {
.into_iter() return Some(
.filter(|l| { lines
if !l.stdout { .into_iter()
return true; .filter(|l| {
} if l.printed_to == LineType::Stderr {
return false; return true;
}) }
.collect(); return false;
})
.collect(),
);
}
None => {
return None;
}
}
} }
/// Returns all output /// Returns all output
pub fn lines(self) -> Vec<Line> { pub fn lines(self) -> Option<Vec<Line>> {
return self.lines; return self.lines;
} }
/// Returns the exit status code, if there was one /// Returns the exit status code, if there was one
pub fn status(self) -> Option<i32> { pub fn status_code(self) -> Option<i32> {
return self.status; return self.status_code;
} }
/// Returns the duration the command ran for /// Returns the duration the command ran for
pub fn duration(self) -> Duration { pub fn duration(self) -> Duration {
return self.end_time.duration_since(self.start_time); return self.duration;
} }
/// Returns the time the command was started at /// Returns the time the command was started at
@ -77,61 +87,21 @@ impl CmdOutput {
} }
} }
pub fn run(command: &mut Command) -> CmdOutput { /// Specifies what a line was printed to - stdout or stderr
// https://stackoverflow.com/a/72831067/16432246 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
let start = Instant::now(); pub enum LineType {
let mut child = command Stdout,
.stdout(Stdio::piped()) Stderr,
.stderr(Stdio::piped()) }
.spawn()
.unwrap();
let child_stdout = child.stdout.take().unwrap(); /// A single line from the output of a command
let child_stderr = child.stderr.take().unwrap(); ///
/// This contains what the line was printed to (stdout/stderr), a timestamp, and the content of course.
let (stdout_tx, stdout_rx) = std::sync::mpsc::channel(); #[derive(Debug, Clone, PartialEq, Eq, Ord)]
let (stderr_tx, stderr_rx) = std::sync::mpsc::channel(); pub struct Line {
pub printed_to: LineType,
let stdout_lines = BufReader::new(child_stdout).lines(); pub time: Instant,
thread::spawn(move || { pub content: String,
for line in stdout_lines {
stdout_tx
.send(Line {
content: line.unwrap(),
stdout: true,
time: Instant::now(),
})
.unwrap();
}
});
let stderr_lines = BufReader::new(child_stderr).lines();
thread::spawn(move || {
for line in stderr_lines {
let time = Instant::now();
stderr_tx
.send(Line {
content: line.unwrap(),
stdout: false,
time: time,
})
.unwrap();
}
});
let status = child.wait().unwrap().code();
let end = Instant::now();
let mut lines = stdout_rx.into_iter().collect::<Vec<Line>>();
lines.append(&mut stderr_rx.into_iter().collect::<Vec<Line>>());
//lines.sort();
return CmdOutput {
lines: lines,
status: status,
start_time: start,
end_time: end,
};
} }
impl PartialOrd for Line { impl PartialOrd for Line {
@ -173,3 +143,111 @@ impl PartialOrd for Line {
return Some(Ordering::Equal); return Some(Ordering::Equal);
} }
} }
/// Runs a command, returning a
///
/// Example:
///
/// ```
/// use better_commands::run;
/// use std::process::Command;
/// let cmd = run(&mut Command::new("echo").arg("hi"));
///
/// // prints the following: [Line { printed_to: Stdout, time: Instant { tv_sec: 16316, tv_nsec: 283884648 }, content: "hi" }]
/// // (timestamp varies)
/// println!("{:?}", cmd.lines().unwrap());
/// ```
pub fn run(command: &mut Command) -> CmdOutput {
// https://stackoverflow.com/a/72831067/16432246
let start = Instant::now();
let mut child = command
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let child_stdout = child.stdout.take().unwrap();
let child_stderr = child.stderr.take().unwrap();
let (stdout_tx, stdout_rx) = std::sync::mpsc::channel();
let (stderr_tx, stderr_rx) = std::sync::mpsc::channel();
let stdout_lines = BufReader::new(child_stdout).lines();
thread::spawn(move || {
for line in stdout_lines {
stdout_tx
.send(Line {
content: line.unwrap(),
printed_to: LineType::Stdout,
time: Instant::now(),
})
.unwrap();
}
});
let stderr_lines = BufReader::new(child_stderr).lines();
thread::spawn(move || {
for line in stderr_lines {
let time = Instant::now();
stderr_tx
.send(Line {
content: line.unwrap(),
printed_to: LineType::Stderr,
time: time,
})
.unwrap();
}
});
let status = child.wait().unwrap().code();
let end = Instant::now();
let mut lines = stdout_rx.into_iter().collect::<Vec<Line>>();
lines.append(&mut stderr_rx.into_iter().collect::<Vec<Line>>());
//lines.sort();
return CmdOutput {
lines: Some(lines),
status_code: status,
start_time: start,
end_time: end,
duration: end.duration_since(start),
};
}
pub fn run_with_funcs(
command: &mut Command,
stdout_func: impl Fn(Lines<BufReader<ChildStdout>>) -> () + std::marker::Send + 'static,
stderr_func: impl Fn(Lines<BufReader<ChildStderr>>) -> () + std::marker::Send + 'static,
) -> CmdOutput {
// https://stackoverflow.com/a/72831067/16432246
let start = Instant::now();
let mut child = command
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let child_stdout = child.stdout.take().unwrap();
let child_stderr = child.stderr.take().unwrap();
let stdout_lines = BufReader::new(child_stdout).lines();
let stdout_thread = thread::spawn(move || stdout_func(stdout_lines));
let stderr_lines = BufReader::new(child_stderr).lines();
let stderr_thread = thread::spawn(move || stderr_func(stderr_lines));
let status = child.wait().unwrap().code();
let end = Instant::now();
stdout_thread.join().unwrap();
stderr_thread.join().unwrap();
return CmdOutput {
lines: None,
status_code: status,
start_time: start,
end_time: end,
duration: end.duration_since(start),
};
}

View file

@ -1,6 +1,11 @@
#[cfg(test)] #[cfg(test)]
use crate::*; use crate::*;
use std::hash::{BuildHasher, Hasher, RandomState}; use std::{
fs::remove_file,
hash::{BuildHasher, Hasher, RandomState},
};
use std::{fs::File, os::unix::fs::FileExt, thread::sleep};
use std::process::Command;
/// Tests what stdout prints /// Tests what stdout prints
#[test] #[test]
@ -14,6 +19,7 @@ fn stdout_content() {
.arg("-n") .arg("-n")
.arg("helloooooooooo\nhiiiiiiiiiiiii")) .arg("helloooooooooo\nhiiiiiiiiiiiii"))
.stdout() .stdout()
.unwrap()
.into_iter() .into_iter()
.map(|line| { line.content }) .map(|line| { line.content })
.collect::<Vec<String>>() .collect::<Vec<String>>()
@ -24,20 +30,18 @@ fn stdout_content() {
/// Tests what stderr prints /// Tests what stderr prints
#[test] #[test]
fn stderr_content() { fn stderr_content() {
let expected = "[\"helloooooooooo\", \"hiiiiiiiiiiiii\"]"; let expected = vec!["helloooooooooo", "hiiiiiiiiiiiii"];
// `>&2` redirects to stderr // `>&2` redirects to stderr
assert_eq!( assert_eq!(
expected, expected,
format!(
"{:?}",
run(&mut Command::new("bash") run(&mut Command::new("bash")
.arg("-c") .arg("-c")
.arg("echo -n 'helloooooooooo\nhiiiiiiiiiiiii' >&2")) .arg("echo -n 'helloooooooooo\nhiiiiiiiiiiiii' >&2"))
.stderr() .stderr()
.unwrap()
.into_iter() .into_iter()
.map(|line| { line.content }) .map(|line| { line.content })
.collect::<Vec<String>>() .collect::<Vec<String>>()
)
); );
} }
@ -49,7 +53,7 @@ fn test_exit_code() {
assert_eq!( assert_eq!(
expected, expected,
run(&mut Command::new("bash").arg("-c").arg("exit 10")) run(&mut Command::new("bash").arg("-c").arg("exit 10"))
.status() .status_code()
.unwrap() .unwrap()
); );
} }
@ -57,7 +61,11 @@ fn test_exit_code() {
/// Tests that the output is sorted by default /// Tests that the output is sorted by default
#[test] #[test]
fn test_output_is_sorted_sort_works() { fn test_output_is_sorted_sort_works() {
let cmd = run(&mut Command::new("bash").arg("-c").arg("echo hi; sleep 0.01; echo hi; sleep 0.01; echo hi; sleep 0.01; echo hi; sleep 0.01; echo hi; sleep 0.01; echo hi; sleep 0.01; echo hi; sleep 0.01; echo hi; sleep 0.01; echo hi; sleep 0.01; echo hi")).stdout(); let cmd = run(&mut Command::new("bash")
.arg("-c")
.arg("echo hi; echo hi; echo hi; echo hi; echo hi"))
.stdout()
.unwrap();
let mut sorted = cmd.clone(); let mut sorted = cmd.clone();
// To avoid an accidental bogosort // To avoid an accidental bogosort
while sorted.is_sorted() { while sorted.is_sorted() {
@ -78,3 +86,52 @@ fn shuffle_vec<T>(vec: &mut [T]) {
vec.swap(i, j); vec.swap(i, j);
} }
} }
#[test]
fn test_run_with_funcs() {
let _ = thread::spawn(|| {
let _ = run_with_funcs(
Command::new("bash")
.arg("-c")
.arg("echo hi; sleep 0.5; >&2 echo hello"),
{
|stdout_lines| {
sleep(Duration::from_secs(1));
for _ in stdout_lines {
Command::new("bash")
.arg("-c")
.arg("echo stdout >> ./tmp")
.output()
.unwrap();
}
}
},
{
|stderr_lines| {
sleep(Duration::from_secs(3));
for _ in stderr_lines {
Command::new("bash")
.arg("-c")
.arg("echo stderr >> ./tmp")
.output()
.unwrap();
}
}
},
);
});
sleep(Duration::from_secs(2));
let f = File::open("./tmp").unwrap();
let mut buf: [u8; 14] = [0u8; 14];
f.read_at(&mut buf, 0).unwrap();
assert_eq!(buf, [115, 116, 100, 111, 117, 116, 10, 0, 0, 0, 0, 0, 0, 0]);
sleep(Duration::from_secs(2));
f.read_at(&mut buf, 0).unwrap();
assert_eq!(
buf,
[115, 116, 100, 111, 117, 116, 10, 115, 116, 100, 101, 114, 114, 10]
);
remove_file("./tmp").unwrap();
}