Skip to main content

pistonite_cu/process/pio/
print.rs

1use std::process::Stdio;
2
3use tokio::process::{Child as TokioChild, ChildStderr, ChildStdout, Command as TokioCommand};
4
5use crate::BoxedFuture;
6use crate::lv::Lv;
7
8use super::{ChildOutConfig, ChildOutTask, Driver, DriverOutput};
9
10impl ChildOutConfig for Lv {
11    type Task = PrintTask;
12    type __Null = super::__OCNull;
13
14    fn configure_stdout(&mut self, command: &mut TokioCommand) {
15        command.stdout(Stdio::piped());
16    }
17
18    fn configure_stderr(&mut self, command: &mut TokioCommand) {
19        command.stderr(Stdio::piped());
20    }
21
22    fn take(
23        self,
24        child: &mut TokioChild,
25        name: Option<&str>,
26        is_out: bool,
27    ) -> crate::Result<Self::Task> {
28        let name = name.unwrap_or_default();
29        let prefix = if !name.is_empty() {
30            format!("[{name}] ")
31        } else {
32            String::new()
33        };
34
35        if is_out {
36            Ok(PrintTask {
37                lv: self,
38                prefix,
39                out: child.stdout.take(),
40                err: None,
41            })
42        } else {
43            Ok(PrintTask {
44                lv: self,
45                prefix,
46                out: None,
47                err: child.stderr.take(),
48            })
49        }
50    }
51}
52
53pub struct PrintTask {
54    lv: Lv,
55    prefix: String,
56    out: Option<ChildStdout>,
57    err: Option<ChildStderr>,
58}
59impl ChildOutTask for PrintTask {
60    type Output = ();
61
62    fn run(self) -> (Option<BoxedFuture<()>>, Self::Output) {
63        (Some(Box::pin(self.main())), ())
64    }
65}
66impl PrintTask {
67    async fn main(self) {
68        let lv = self.lv;
69        let prefix = self.prefix;
70        let mut driver = Driver::new(self.out, self.err, false);
71        loop {
72            match driver.next().await {
73                DriverOutput::Line(line) => {
74                    for l in line.lines() {
75                        crate::cli::__print_with_level(lv, format_args!("{prefix}{l}"));
76                    }
77                }
78                DriverOutput::Done => break,
79                _ => {}
80            }
81        }
82    }
83}