1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Copyright (C) 2022 Leandro Lisboa Penz <lpenz@lpenz.org>
// This file is subject to the terms and conditions defined in
// file 'LICENSE', which is part of this source code package.

#![deny(future_incompatible)]
#![deny(nonstandard_style)]
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]

//! tokio-process-stream is a simple crate that wraps a [`tokio::process`] into a
//! [`tokio::stream`]
//!
//! Having a stream interface to processes is useful when we have multiple sources of data that
//! we want to merge and start processing from a single entry point.
//!
//! This crate provides a [`futures::stream::Stream`] wrapper for [`tokio::process::Child`]. The
//! main struct is [`ProcessLineStream`], which implements the trait, yielding one [`Item`] enum
//! at a time, each containing one line from either stdout ([`Item::Stdout`]) or stderr
//! ([`Item::Stderr`]) of the underlying process until it exits. At this point, the stream
//! yields a single [`Item::Done`] and finishes.
//!
//! Example usage:
//!
//! ```rust
//! use tokio_process_stream::ProcessLineStream;
//! use tokio::process::Command;
//! use tokio_stream::StreamExt;
//! use std::error::Error;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn Error>> {
//!     let mut sleep_cmd = Command::new("sleep");
//!     sleep_cmd.args(&["1"]);
//!     let ls_cmd = Command::new("ls");
//!
//!     let sleep_procstream = ProcessLineStream::try_from(sleep_cmd)?;
//!     let ls_procstream = ProcessLineStream::try_from(ls_cmd)?;
//!     let mut procstream = sleep_procstream.merge(ls_procstream);
//!
//!     while let Some(item) = procstream.next().await {
//!         println!("{:?}", item);
//!     }
//!
//!     Ok(())
//! }
//! ```
//!
//! # Streaming chunks
//!
//! It is also possible to stream `Item<Bytes>` chunks with [`ProcessChunkStream`].
//!
//! ```rust
//! use tokio_process_stream::{Item, ProcessChunkStream};
//! use tokio::process::Command;
//! use tokio_stream::StreamExt;
//! use std::error::Error;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn Error>> {
//!     let mut procstream: ProcessChunkStream = Command::new("/bin/sh")
//!         .arg("-c")
//!         .arg(r#"printf "1/2"; sleep 0.1; printf "\r2/2 done\n""#)
//!         .try_into()?;
//!
//!     while let Some(item) = procstream.next().await {
//!         println!("{:?}", item);
//!     }
//!     Ok(())
//! }
//! ```

use pin_project_lite::pin_project;
use std::{
    fmt,
    future::Future,
    io,
    pin::Pin,
    process::{ExitStatus, Stdio},
    task::{Context, Poll},
};
use tokio::{
    io::{AsyncBufReadExt, BufReader},
    process::{Child, ChildStderr, ChildStdout, Command},
};
use tokio_stream::{wrappers::LinesStream, Stream};
use tokio_util::io::ReaderStream;

/// [`ProcessStream`] output.
#[derive(Debug)]
pub enum Item<Out> {
    /// A stdout chunk printed by the process.
    Stdout(Out),
    /// A stderr chunk printed by the process.
    Stderr(Out),
    /// The [`ExitStatus`](std::process::ExitStatus), yielded after the process exits.
    Done(io::Result<ExitStatus>),
}

impl<T> Item<T>
where
    T: std::ops::Deref,
{
    /// Returns a [`Item::Stdout`] dereference, otherwise `None`.
    pub fn stdout(&self) -> Option<&T::Target> {
        match self {
            Self::Stdout(s) => Some(s),
            _ => None,
        }
    }

    /// Returns a [`Item::Stderr`] dereference, otherwise `None`.
    pub fn stderr(&self) -> Option<&T::Target> {
        match self {
            Self::Stderr(s) => Some(s),
            _ => None,
        }
    }
}

impl<Out: fmt::Display> fmt::Display for Item<Out> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Item::Stdout(s) => fmt::Display::fmt(&s, f),
            Item::Stderr(s) => fmt::Display::fmt(&s, f),
            _ => Ok(()),
        }
    }
}

pin_project! {
/// The main tokio-process-stream struct, which implements the
/// [`Stream`](tokio_stream::Stream) trait
#[derive(Debug)]
pub struct ChildStream<Sout, Serr> {
    child: Option<Child>,
    stdout: Option<Sout>,
    stderr: Option<Serr>,
}
}

impl<Sout, Serr> ChildStream<Sout, Serr> {
    /// Return a reference to the child object
    pub fn child(&self) -> Option<&Child> {
        self.child.as_ref()
    }

    /// Return a mutable reference to the child object
    pub fn child_mut(&mut self) -> Option<&mut Child> {
        self.child.as_mut()
    }
}

impl<Sout, Serr> TryFrom<Command> for ChildStream<Sout, Serr>
where
    ChildStream<Sout, Serr>: From<Child>,
{
    type Error = io::Error;
    fn try_from(mut command: Command) -> io::Result<Self> {
        Self::try_from(&mut command)
    }
}

impl<Sout, Serr> TryFrom<&mut Command> for ChildStream<Sout, Serr>
where
    ChildStream<Sout, Serr>: From<Child>,
{
    type Error = io::Error;
    fn try_from(command: &mut Command) -> io::Result<Self> {
        Ok(command
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?
            .into())
    }
}

impl<T, Sout, Serr> Stream for ChildStream<Sout, Serr>
where
    Sout: Stream<Item = io::Result<T>> + std::marker::Unpin,
    Serr: Stream<Item = io::Result<T>> + std::marker::Unpin,
{
    type Item = Item<T>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if self.child.is_none() {
            // Keep returning None after we are done and everything is dropped
            return Poll::Ready(None);
        }
        let this = self.project();
        if let Some(stderr) = this.stderr {
            match Pin::new(stderr).poll_next(cx) {
                Poll::Ready(Some(line)) => {
                    return Poll::Ready(Some(Item::Stderr(line.unwrap())));
                }
                Poll::Ready(None) => {
                    *this.stderr = None;
                }
                Poll::Pending => {}
            }
        }
        if let Some(stdout) = this.stdout {
            match Pin::new(stdout).poll_next(cx) {
                Poll::Ready(Some(line)) => {
                    return Poll::Ready(Some(Item::Stdout(line.unwrap())));
                }
                Poll::Ready(None) => {
                    *this.stdout = None;
                }
                Poll::Pending => {}
            }
        }
        if this.stdout.is_none() && this.stderr.is_none() {
            // Streams closed, all that is left is waiting for the child to exit:
            if let Some(mut child) = std::mem::take(&mut *this.child) {
                if let Poll::Ready(sts) = Pin::new(&mut Box::pin(child.wait())).poll(cx) {
                    return Poll::Ready(Some(Item::Done(sts)));
                }
                // Sometimes the process can close stdout+stderr before it's ready to be
                // 'wait'ed. To handle that, we put child back in this:
                *this.child = Some(child);
            }
        }
        Poll::Pending
    }
}

/// [`ChildStream`] that produces lines.
pub type ProcessLineStream =
    ChildStream<LinesStream<BufReader<ChildStdout>>, LinesStream<BufReader<ChildStderr>>>;

/// Alias for [`ProcessLineStream`].
pub type ProcessStream = ProcessLineStream;

impl From<Child> for ProcessLineStream {
    fn from(mut child: Child) -> Self {
        let stdout = child
            .stdout
            .take()
            .map(|s| LinesStream::new(BufReader::new(s).lines()));
        let stderr = child
            .stderr
            .take()
            .map(|s| LinesStream::new(BufReader::new(s).lines()));
        Self {
            child: Some(child),
            stdout,
            stderr,
        }
    }
}

/// [`ChildStream`] that produces chunks that may part of a line or multiple lines.
///
/// # Example
/// ```
/// use tokio_process_stream::{Item, ProcessChunkStream};
/// use tokio::process::Command;
/// use tokio_stream::StreamExt;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Example of a process that prints onto a single line using '\r'.
/// let mut procstream: ProcessChunkStream = Command::new("/bin/sh")
///     .arg("-c")
///     .arg(r#"printf "1/2"; sleep 0.1; printf "\r2/2 done\n""#)
///     .try_into()?;
///
/// assert_eq!(
///     procstream.next().await.as_ref().and_then(|n| n.stdout()),
///     Some(b"1/2" as _)
/// );
/// assert_eq!(
///     procstream.next().await.as_ref().and_then(|n| n.stdout()),
///     Some(b"\r2/2 done\n" as _)
/// );
/// assert!(matches!(procstream.next().await, Some(Item::Done(_))));
/// # Ok(()) }
/// ```
pub type ProcessChunkStream =
    ChildStream<ReaderStream<BufReader<ChildStdout>>, ReaderStream<BufReader<ChildStderr>>>;

impl From<Child> for ProcessChunkStream {
    fn from(mut child: Child) -> Self {
        let stdout = child
            .stdout
            .take()
            .map(|s| ReaderStream::new(BufReader::new(s)));
        let stderr = child
            .stderr
            .take()
            .map(|s| ReaderStream::new(BufReader::new(s)));
        Self {
            child: Some(child),
            stdout,
            stderr,
        }
    }
}