1use std::path::Path;
8use std::time::Instant;
9
10use serde::de::DeserializeOwned;
11
12use super::PhpSettings;
13use super::ansi::plain;
14use super::process::{Run, RunEnd, RunEvent, Runs, StartError, Stream};
15use crate::package::{DataError, whole_document};
16
17#[derive(Debug)]
19pub struct Read {
20 run: Run,
21 stdout: Vec<String>,
22 stderr: Vec<String>,
23 stdout_cut: bool,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct ReadEnd {
29 pub end: RunEnd,
30 pub stdout: Vec<String>,
31 pub stderr: Vec<String>,
32 pub stdout_cut: bool,
36}
37
38impl Read {
39 pub fn start(
41 runs: &Runs,
42 app: &Path,
43 php: &PhpSettings,
44 args: &[String],
45 ) -> Result<Read, StartError> {
46 Self::start_with_input(runs, app, php, args, None)
47 }
48
49 pub fn start_with_input(
51 runs: &Runs,
52 app: &Path,
53 php: &PhpSettings,
54 args: &[String],
55 input: Option<Vec<u8>>,
56 ) -> Result<Read, StartError> {
57 let run = runs.start_with_input(app, php, args, php.time_limit(), input)?;
58 Ok(Read {
59 run,
60 stdout: Vec::new(),
61 stderr: Vec::new(),
62 stdout_cut: false,
63 })
64 }
65
66 pub fn poll(&mut self) -> Option<ReadEnd> {
69 let events = self.run.events();
70 self.take(events)
71 }
72
73 pub fn wait(&mut self, deadline: Instant) -> Option<ReadEnd> {
75 let events = self.run.wait(deadline);
76 self.take(events)
77 }
78
79 pub fn stop(&self) {
81 self.run.stop();
82 }
83
84 fn take(&mut self, events: Vec<RunEvent>) -> Option<ReadEnd> {
85 for event in events {
86 match event {
87 RunEvent::Line {
88 stream: Stream::Out,
89 text,
90 cut,
91 } => {
92 self.stdout_cut = cut || (self.stdout_cut && text.trim().is_empty());
94 self.stdout.push(text);
95 }
96 RunEvent::Line {
97 stream: Stream::Err,
98 text,
99 ..
100 } => self.stderr.push(text),
101 RunEvent::Cut => self.stdout_cut = true,
104 RunEvent::Ended(end) => {
105 return Some(ReadEnd {
106 end,
107 stdout: std::mem::take(&mut self.stdout),
108 stderr: std::mem::take(&mut self.stderr),
109 stdout_cut: self.stdout_cut,
110 });
111 }
112 }
113 }
114 None
115 }
116}
117
118impl ReadEnd {
119 pub fn document<T: DeserializeOwned>(&self) -> Result<T, DataError> {
121 whole_document(&self.stdout, self.stdout_cut)
122 }
123
124 pub fn error_line(&self) -> Option<String> {
127 self.stderr
128 .iter()
129 .rev()
130 .map(|line| plain(line).trim().to_string())
131 .find(|line| !line.is_empty())
132 }
133}