first feed the input, then read its output

This commit is contained in:
Abraham Toriz 2021-09-07 14:03:51 -05:00
parent 56e7c525a4
commit 422d6bb593
No known key found for this signature in database
GPG Key ID: D5B4A746DB5DD42A
1 changed files with 29 additions and 28 deletions

View File

@ -1,7 +1,6 @@
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::io::Read;
use std::io::{Read, Write};
use csv::Writer;
use chrono::SecondsFormat;
@ -64,7 +63,6 @@ where
})?;
let config = get_formatter_config(&facts.config, formatter);
let mut command = Command::new(&path);
command
@ -74,35 +72,40 @@ where
.stderr(Stdio::piped());
let mut child = command.spawn().map_err(|e| CustomFormatterFailed(path, e))?;
let stdin = child.stdin.take().expect("Failed to take stdin");
let mut stdout = child.stdout.take().expect("Failed to take stdout");
let mut stderr = child.stderr.take().expect("Failed to take stdout");
let mut wtr = Writer::from_writer(stdin);
{
let mut wtr = Writer::from_writer(stdin);
for entry in entries {
// write to process' stdin
wtr.write_record(&[
entry.id.to_string(),
entry.start.to_rfc3339_opts(SecondsFormat::Micros, true),
entry.end.map(|t| t.to_rfc3339_opts(SecondsFormat::Micros, true)).unwrap_or_else(|| "".into()),
entry.note.unwrap_or_else(|| "".into()),
entry.sheet,
])?;
}
}
// All the input has been fed to the child process, now we wait for it to
// finish and then read its output
child.wait()?;
let mut captured_out = String::new();
let mut captured_err = String::new();
for entry in entries {
// write to process' stdin
wtr.write_record(&[
entry.id.to_string(),
entry.start.to_rfc3339_opts(SecondsFormat::Micros, true),
entry.end.map(|t| t.to_rfc3339_opts(SecondsFormat::Micros, true)).unwrap_or_else(|| "".into()),
entry.note.unwrap_or_else(|| "".into()),
entry.sheet,
])?;
wtr.flush()?;
// read process' stdout and stderr
stdout.read_to_string(&mut captured_out)?;
write!(out, "{}", &captured_out)?;
captured_out.clear();
// read process' stdout and stderr
stdout.read_to_string(&mut captured_out)?;
write!(out, "{}", &captured_out)?;
captured_out.clear();
stderr.read_to_string(&mut captured_err)?;
write!(err, "{}", &captured_err)?;
captured_err.clear();
}
stderr.read_to_string(&mut captured_err)?;
write!(err, "{}", &captured_err)?;
captured_err.clear();
Ok(())
}
@ -122,8 +125,7 @@ mod tests {
assert_eq!(err.to_string(), "\
The specified name for a custom formatter \"pol/lo\" is not valid. Only ascii
letters, numbers, dots, dashes and underscores are allowed.
");
letters, numbers, dots, dashes and underscores are allowed.");
}
#[test]
@ -139,8 +141,7 @@ where to look for it.
You can set a path using
t config --formatter-search-paths <path>..
");
t config --formatter-search-paths <path>..");
}
#[test]