use std::path::Path;
use std::time::Instant;
use serde::de::DeserializeOwned;
use super::PhpSettings;
use super::ansi::plain;
use super::process::{Run, RunEnd, RunEvent, Runs, StartError, Stream};
use crate::package::{DataError, whole_document};
#[derive(Debug)]
pub struct Read {
run: Run,
stdout: Vec<String>,
stderr: Vec<String>,
stdout_cut: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReadEnd {
pub end: RunEnd,
pub stdout: Vec<String>,
pub stderr: Vec<String>,
pub stdout_cut: bool,
}
impl Read {
pub fn start(
runs: &Runs,
app: &Path,
php: &PhpSettings,
args: &[String],
) -> Result<Read, StartError> {
Self::start_with_input(runs, app, php, args, None)
}
pub fn start_with_input(
runs: &Runs,
app: &Path,
php: &PhpSettings,
args: &[String],
input: Option<Vec<u8>>,
) -> Result<Read, StartError> {
let run = runs.start_with_input(app, php, args, php.time_limit(), input)?;
Ok(Read {
run,
stdout: Vec::new(),
stderr: Vec::new(),
stdout_cut: false,
})
}
pub fn poll(&mut self) -> Option<ReadEnd> {
let events = self.run.events();
self.take(events)
}
pub fn wait(&mut self, deadline: Instant) -> Option<ReadEnd> {
let events = self.run.wait(deadline);
self.take(events)
}
pub fn stop(&self) {
self.run.stop();
}
fn take(&mut self, events: Vec<RunEvent>) -> Option<ReadEnd> {
for event in events {
match event {
RunEvent::Line {
stream: Stream::Out,
text,
cut,
} => {
self.stdout_cut = cut || (self.stdout_cut && text.trim().is_empty());
self.stdout.push(text);
}
RunEvent::Line {
stream: Stream::Err,
text,
..
} => self.stderr.push(text),
RunEvent::Cut => self.stdout_cut = true,
RunEvent::Ended(end) => {
return Some(ReadEnd {
end,
stdout: std::mem::take(&mut self.stdout),
stderr: std::mem::take(&mut self.stderr),
stdout_cut: self.stdout_cut,
});
}
}
}
None
}
}
impl ReadEnd {
pub fn document<T: DeserializeOwned>(&self) -> Result<T, DataError> {
whole_document(&self.stdout, self.stdout_cut)
}
pub fn error_line(&self) -> Option<String> {
self.stderr
.iter()
.rev()
.map(|line| plain(line).trim().to_string())
.find(|line| !line.is_empty())
}
}