Compare commits

..

No commits in common. "1f312e57e503a4b62772beb811aecc7aa7b03733" and "3c4b786c7d62f8614f981af669531729514ea5f3" have entirely different histories.

3 changed files with 98 additions and 236 deletions

View file

@ -5,6 +5,3 @@ 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, Lines}; use std::io::{BufRead, BufReader};
use std::process::{ChildStderr, ChildStdout, Command, Stdio}; use std::process::{Command, Stdio};
use std::thread; use std::thread;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@ -9,71 +9,61 @@ 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: Option<Vec<Line>>, lines: Vec<Line>,
status_code: Option<i32>, status: 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) -> Option<Vec<Line>> { pub fn stdout(self) -> Vec<Line> {
match self.lines { return self
Some(lines) => { .lines
return Some(
lines
.into_iter() .into_iter()
.filter(|l| { .filter(|l| {
if l.printed_to == LineType::Stdout { if l.stdout {
return true; return true;
} }
return false; return false;
}) })
.collect(), .collect();
);
}
None => {
return None;
}
}
} }
/// Returns only stdout /// Returns only stdout
pub fn stderr(self) -> Option<Vec<Line>> { pub fn stderr(self) -> Vec<Line> {
match self.lines { return self
Some(lines) => { .lines
return Some(
lines
.into_iter() .into_iter()
.filter(|l| { .filter(|l| {
if l.printed_to == LineType::Stderr { if !l.stdout {
return true; return true;
} }
return false; return false;
}) })
.collect(), .collect();
);
}
None => {
return None;
}
}
} }
/// Returns all output /// Returns all output
pub fn lines(self) -> Option<Vec<Line>> { pub fn lines(self) -> 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_code(self) -> Option<i32> { pub fn status(self) -> Option<i32> {
return self.status_code; return self.status;
} }
/// 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.duration; return self.end_time.duration_since(self.start_time);
} }
/// Returns the time the command was started at /// Returns the time the command was started at
@ -87,21 +77,61 @@ impl CmdOutput {
} }
} }
/// Specifies what a line was printed to - stdout or stderr pub fn run(command: &mut Command) -> CmdOutput {
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] // https://stackoverflow.com/a/72831067/16432246
pub enum LineType { let start = Instant::now();
Stdout, let mut child = command
Stderr, .stdout(Stdio::piped())
} .stderr(Stdio::piped())
.spawn()
.unwrap();
/// A single line from the output of a command let child_stdout = child.stdout.take().unwrap();
/// let child_stderr = child.stderr.take().unwrap();
/// This contains what the line was printed to (stdout/stderr), a timestamp, and the content of course.
#[derive(Debug, Clone, PartialEq, Eq, Ord)] let (stdout_tx, stdout_rx) = std::sync::mpsc::channel();
pub struct Line { let (stderr_tx, stderr_rx) = std::sync::mpsc::channel();
pub printed_to: LineType,
pub time: Instant, let stdout_lines = BufReader::new(child_stdout).lines();
pub content: String, thread::spawn(move || {
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 {
@ -143,111 +173,3 @@ 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,11 +1,6 @@
#[cfg(test)] #[cfg(test)]
use crate::*; use crate::*;
use std::{ use std::hash::{BuildHasher, Hasher, RandomState};
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]
@ -19,7 +14,6 @@ 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>>()
@ -30,18 +24,20 @@ fn stdout_content() {
/// Tests what stderr prints /// Tests what stderr prints
#[test] #[test]
fn stderr_content() { fn stderr_content() {
let expected = vec!["helloooooooooo", "hiiiiiiiiiiiii"]; let expected = "[\"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>>()
)
); );
} }
@ -53,7 +49,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_code() .status()
.unwrap() .unwrap()
); );
} }
@ -61,11 +57,7 @@ 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") 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();
.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() {
@ -86,52 +78,3 @@ 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();
}