Skip to main content

mortise_core/run/
read.rs

1//! A read: a package command whose only purpose is data.
2//!
3//! A read starts as a run does, through [`Runs::start`], so it shares the lock of
4//! one command per app and the time limit of the app. It keeps standard output and
5//! standard error apart, and it is not kept in the history.
6
7use 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/// A read that runs.
18#[derive(Debug)]
19pub struct Read {
20    run: Run,
21    stdout: Vec<String>,
22    stderr: Vec<String>,
23    stdout_cut: bool,
24}
25
26/// How a read ended, with its lines.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct ReadEnd {
29    pub end: RunEnd,
30    pub stdout: Vec<String>,
31    pub stderr: Vec<String>,
32    /// The last non-empty line of standard output was cut, or the output passed
33    /// its limit and its later lines were dropped. [`ReadEnd::document`] then gives
34    /// [`DataError::Cut`].
35    pub stdout_cut: bool,
36}
37
38impl Read {
39    /// Starts artisan with `args` in the app, for at most the app's time limit.
40    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    /// [`Read::start`], with `input` on the standard input of the command.
50    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    /// Takes what arrived. It never blocks. `Some` once the read ended; the read
67    /// is over then and gives nothing more.
68    pub fn poll(&mut self) -> Option<ReadEnd> {
69        let events = self.run.events();
70        self.take(events)
71    }
72
73    /// Waits until the read ended or `deadline` passed. `Some` once it ended.
74    pub fn wait(&mut self, deadline: Instant) -> Option<ReadEnd> {
75        let events = self.run.wait(deadline);
76        self.take(events)
77    }
78
79    /// Asks the read to end its process tree. Safe to call twice or after the end.
80    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                    // An empty line after a cut one leaves the mark.
93                    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                // The later lines are dropped, the document with them: a line kept
102                // before is not the document.
103                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    /// The document on standard output, read as `T` ([`whole_document`]).
120    pub fn document<T: DeserializeOwned>(&self) -> Result<T, DataError> {
121        whole_document(&self.stdout, self.stdout_cut)
122    }
123
124    /// The last non-empty line of standard error, without escape codes. It says
125    /// why a read failed that gave no document.
126    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}