pub fn run_funcs_with_lines(
command: &mut Command,
stdout_func: impl FnOnce(Lines<BufReader<ChildStdout>>) -> Vec<Line> + Send + 'static,
stderr_func: impl FnOnce(Lines<BufReader<ChildStderr>>) -> Vec<Line> + Send + 'static,
) -> CmdOutput
Expand description
Runs a command while simultaneously running a provided Fn
as the command prints line-by-line, including line handling
The CmdOutput
will contain Some(lines)
, not a None.
Example:
use better_commands::run_funcs_with_lines;
use better_commands::Line;
use std::process::Command;
let cmd = run_funcs_with_lines(&mut Command::new("echo").arg("hi"), {
|stdout_lines| { // your function *must* return the lines
let mut lines = Vec::new();
for line in stdout_lines {
lines.push(Line::from_stdout(line.unwrap()));
/* send line to database */
}
return lines;
}
},
{
|stderr_lines| {
// this code is for stderr and won't run because echo won't print anything to stderr, so we'll just put this placeholder here
return Vec::new();
}
});
// prints the following: [Line { printed_to: Stdout, time: Instant { tv_sec: 16316, tv_nsec: 283884648 }, content: "hi" }]
// (timestamp varies)
assert_eq!("hi", cmd.lines().unwrap()[0].content);
In order for the built-in lines
functionality to work, your function must return the lines like this; if this doesn’t work for you, you can use run
or run_funcs
instead.
ⓘ
use better_commands::Line;
let mut lines = Vec::new();
for line in stdout_lines {
lines.push(Line::from_stdout(line.unwrap())); // from_stdout/from_stderr depending on which
}
return lines;