• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lpenz / ogle / 29170707323

11 Jul 2026 10:29PM UTC coverage: 60.289% (+0.05%) from 60.241%
29170707323

push

github

lpenz
chore: clarify why sleeping status uses self.start for timestamp

501 of 831 relevant lines covered (60.29%)

1.6 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.24
/src/process_wrapper.rs
1
// Copyright (C) 2025 Leandro Lisboa Penz <lpenz@lpenz.org>
2
// This file is subject to the terms and conditions defined in
3
// file 'LICENSE', which is part of this source code package.
4

5
//! Wrapper for process functions.
6
//!
7
//! # `Cmd`
8
//!
9
//! The [`Cmd`] type has an inner `Vec<String>` that we can turn into
10
//! a [`tokio::process::Command`]. It implements `Clone`, which we use
11
//! to spawn the same process multiple times.
12
//!
13
//! # `ProcessStream`
14
//!
15
//! The [`ProcessStream`] type wraps [`tokio_process_stream`] in order
16
//! to provide an [`Item`] that implements `Eq` which we can then use
17
//! for testing.
18

19
use color_eyre::Result;
20
use nix::sys::signal::Signal;
21
use std::collections::VecDeque;
22
use std::fmt;
23
use std::io;
24
use std::os::unix::process::ExitStatusExt;
25
use std::pin::Pin;
26
use std::process::ExitStatus;
27
use std::process::Stdio;
28
use std::task::{Context, Poll};
29
use tokio::process::Child;
30
use tokio::process::Command;
31
use tokio_process_stream as tps;
32
use tokio_stream::Stream;
33
use tracing::instrument;
34

35
// Command wrapper ///////////////////////////////////////////////////
36

37
/// A [`tokio::process::Command`] pseudo-wrapper that `impl Clone`.
38
#[derive(Debug, Default, Clone)]
39
pub struct Cmd(Vec<String>);
40

41
impl From<&Cmd> for Command {
42
    fn from(cmd: &Cmd) -> Command {
8✔
43
        let mut command = Command::new(&cmd.0[0]);
8✔
44
        command.args(cmd.0.iter().skip(1));
8✔
45
        command.stdin(Stdio::null());
8✔
46
        command.stdout(Stdio::piped());
8✔
47
        command.stderr(Stdio::piped());
8✔
48
        command
8✔
49
    }
8✔
50
}
51

52
impl From<Vec<String>> for Cmd {
53
    fn from(s: Vec<String>) -> Cmd {
2✔
54
        Self(s)
2✔
55
    }
2✔
56
}
57

58
impl From<&[&str]> for Cmd {
59
    fn from(s: &[&str]) -> Cmd {
6✔
60
        Self(s.iter().map(|s| s.to_string()).collect::<Vec<_>>())
11✔
61
    }
6✔
62
}
63

64
impl fmt::Display for Cmd {
65
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1✔
66
        let joined = self.0.join(" ");
1✔
67
        write!(f, "{joined}")
1✔
68
    }
1✔
69
}
70

71
// Exit status ///////////////////////////////////////////////////////
72

73
/// A [`std::process::ExitStatus`] pseudo-wrapper that impl Clone
74
/// and custom Display.
75
#[derive(Debug, Default, Clone, PartialEq, Eq)]
76
pub enum ExitSts {
77
    #[default]
78
    Success,
79
    Code(u8),
80
    Signal(i32),
81
}
82

83
impl ExitSts {
84
    pub fn success(&self) -> bool {
5✔
85
        self == &ExitSts::Success
5✔
86
    }
5✔
87
}
88

89
impl From<ExitStatus> for ExitSts {
90
    fn from(sts: ExitStatus) -> ExitSts {
6✔
91
        if sts.success() {
6✔
92
            ExitSts::Success
4✔
93
        } else if let Some(code) = sts.code() {
2✔
94
            debug_assert!((0..=255).contains(&code), "exit code {code} out of u8 range");
1✔
95
            ExitSts::Code(code as u8)
1✔
96
        } else if let Some(signal) = sts.signal() {
1✔
97
            ExitSts::Signal(signal)
1✔
98
        } else {
99
            panic!("Unable to figure out exit status {sts:?}")
×
100
        }
101
    }
6✔
102
}
103

104
impl fmt::Display for ExitSts {
105
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4✔
106
        match self {
4✔
107
            ExitSts::Success => write!(f, "success"),
1✔
108
            ExitSts::Code(code) => write!(f, "code {code}"),
1✔
109
            ExitSts::Signal(signal) => {
2✔
110
                if let Ok(s) = Signal::try_from(*signal) {
2✔
111
                    write!(f, "signal {signal} ({s})")
1✔
112
                } else {
113
                    write!(f, "signal {signal}")
1✔
114
                }
115
            }
116
        }
117
    }
4✔
118
}
119

120
// ProcessStream /////////////////////////////////////////////////////
121

122
/// A clonable, Eq replacement for [`tokio_process_stream::Item`]
123
#[derive(Debug, Clone, PartialEq, Eq)]
124
pub enum Item {
125
    /// A stdout line printed by the process.
126
    Stdout(String),
127
    /// A stderr line printed by the process.
128
    Stderr(String),
129
    /// The [`ExitSts`], yielded after the process exits.
130
    Done(Result<ExitSts, io::ErrorKind>),
131
}
132

133
impl From<tps::Item<String>> for Item {
134
    fn from(item: tps::Item<String>) -> Self {
8✔
135
        match item {
8✔
136
            tps::Item::Stdout(s) => Item::Stdout(s),
1✔
137
            tps::Item::Stderr(s) => Item::Stderr(s),
1✔
138
            tps::Item::Done(result) => Item::Done(match result {
6✔
139
                Ok(sts) => Ok(sts.into()),
6✔
140
                Err(err) => Err(err.kind()),
×
141
            }),
142
        }
143
    }
8✔
144
}
145

146
/// A wrapper for [`tokio_process_stream::ProcessLineStream`].
147
///
148
/// Also provides a virtual implementation for use in tests.
149
pub enum ProcessStream {
150
    /// Wrapper for [`tokio_process_stream::ProcessLineStream`].
151
    Real { stream: Box<tps::ProcessLineStream> },
152
    /// Mock for a running process stream that just returns items from
153
    /// a list. Useful for testing.
154
    Virtual { items: VecDeque<Item> },
155
}
156

157
impl ProcessStream {
158
    /// Return a mutable reference to the child object
159
    pub fn child_mut(&mut self) -> Option<&mut Child> {
1✔
160
        if let ProcessStream::Real { stream } = self {
1✔
161
            stream.child_mut()
1✔
162
        } else {
163
            None
×
164
        }
165
    }
1✔
166
}
167

168
impl std::fmt::Debug for ProcessStream {
169
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1✔
170
        match self {
1✔
171
            ProcessStream::Real { stream: _ } => f.debug_struct("ProcessStream::Real"),
×
172
            ProcessStream::Virtual { items: _ } => f.debug_struct("ProcessStream::Virtual"),
1✔
173
        }
174
        .finish()
1✔
175
    }
1✔
176
}
177

178
impl From<tps::ProcessLineStream> for ProcessStream {
179
    fn from(stream: tps::ProcessLineStream) -> Self {
6✔
180
        ProcessStream::Real {
6✔
181
            stream: Box::new(stream),
6✔
182
        }
6✔
183
    }
6✔
184
}
185

186
impl From<VecDeque<Item>> for ProcessStream {
187
    fn from(items: VecDeque<Item>) -> Self {
3✔
188
        ProcessStream::Virtual { items }
3✔
189
    }
3✔
190
}
191

192
impl Stream for ProcessStream {
193
    type Item = Item;
194

195
    #[instrument(level = "debug", ret, skip(cx))]
196
    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
32✔
197
        let this = self.get_mut();
198
        match this {
199
            ProcessStream::Real { stream } => {
200
                let next = Pin::new(stream).poll_next(cx);
201
                match next {
202
                    Poll::Ready(opt) => Poll::Ready(opt.map(|i| i.into())),
8✔
203
                    Poll::Pending => Poll::Pending,
204
                }
205
            }
206
            ProcessStream::Virtual { items } => Poll::Ready(items.pop_front()),
207
        }
208
    }
32✔
209
}
210

211
// Tests /////////////////////////////////////////////////////////////
212

213
#[cfg(test)]
214
pub mod test {
215
    use color_eyre::Result;
216
    use color_eyre::eyre::eyre;
217
    use tokio_stream::StreamExt;
218

219
    use super::*;
220

221
    async fn stream_cmd(cmdstr: &[&str]) -> Result<ProcessStream> {
5✔
222
        let cmd = Cmd::from(cmdstr);
5✔
223
        let process_stream = tps::ProcessLineStream::try_from(Command::from(&cmd))?;
5✔
224
        Ok(ProcessStream::from(process_stream))
5✔
225
    }
5✔
226

227
    async fn stream_next<T>(stream: &mut T) -> Result<Item>
7✔
228
    where
7✔
229
        T: StreamExt<Item = Item> + std::marker::Unpin + Send + 'static,
7✔
230
    {
7✔
231
        stream.next().await.ok_or(eyre!("no item received"))
7✔
232
    }
7✔
233

234
    async fn assert_closed<T>(stream: &mut T)
5✔
235
    where
5✔
236
        T: StreamExt<Item = Item> + std::marker::Unpin + Send + 'static,
5✔
237
    {
5✔
238
        assert_eq!(stream.next().await, None);
5✔
239
    }
5✔
240

241
    #[tokio::test]
242
    async fn test_true() -> Result<()> {
1✔
243
        let mut stream = stream_cmd(&["true"]).await?;
1✔
244
        let item = stream_next(&mut stream).await?;
1✔
245
        let Item::Done(sts) = item else {
1✔
246
            return Err(eyre!("unexpected stream item {:?}", item));
×
247
        };
248
        assert!(sts.unwrap().success());
1✔
249
        assert!(stream.next().await.is_none());
1✔
250
        assert_closed(&mut stream).await;
1✔
251
        Ok(())
2✔
252
    }
1✔
253

254
    #[tokio::test]
255
    async fn test_false() -> Result<()> {
1✔
256
        let mut stream = stream_cmd(&["false"]).await?;
1✔
257
        let item = stream_next(&mut stream).await?;
1✔
258
        let Item::Done(sts) = item else {
1✔
259
            return Err(eyre!("unexpected stream item {:?}", item));
×
260
        };
261
        assert!(!sts.unwrap().success());
1✔
262
        assert_closed(&mut stream).await;
1✔
263
        Ok(())
2✔
264
    }
1✔
265

266
    #[tokio::test]
267
    async fn test_echo() -> Result<()> {
1✔
268
        let mut stream = stream_cmd(&["echo", "test"]).await?;
1✔
269
        let item = stream_next(&mut stream).await?;
1✔
270
        let Item::Stdout(s) = item else {
1✔
271
            return Err(eyre!("unexpected stream item {:?}", item));
×
272
        };
273
        assert_eq!(s, "test");
1✔
274
        let item = stream_next(&mut stream).await?;
1✔
275
        let Item::Done(sts) = item else {
1✔
276
            return Err(eyre!("unexpected stream item {:?}", item));
×
277
        };
278
        assert!(sts.unwrap().success());
1✔
279
        assert_closed(&mut stream).await;
1✔
280
        Ok(())
2✔
281
    }
1✔
282

283
    #[tokio::test]
284
    async fn test_stderr() -> Result<()> {
1✔
285
        let mut stream = stream_cmd(&["/bin/sh", "-c", "echo test >&2"]).await?;
1✔
286
        let item = stream_next(&mut stream).await?;
1✔
287
        let Item::Stderr(s) = item else {
1✔
288
            return Err(eyre!("unexpected stream item {:?}", item));
×
289
        };
290
        assert_eq!(s, "test");
1✔
291
        let item = stream_next(&mut stream).await?;
1✔
292
        let Item::Done(sts) = item else {
1✔
293
            return Err(eyre!("unexpected stream item {:?}", item));
×
294
        };
295
        assert!(sts.unwrap().success());
1✔
296
        assert_closed(&mut stream).await;
1✔
297
        Ok(())
2✔
298
    }
1✔
299

300
    #[tokio::test]
301
    async fn test_kill() -> Result<()> {
1✔
302
        let mut stream = stream_cmd(&["/bin/sh", "-c", "sleep 60"]).await?;
1✔
303
        if let Some(child) = stream.child_mut() {
1✔
304
            let _ = child.start_kill();
1✔
305
        }
1✔
306
        let item = stream_next(&mut stream).await?;
1✔
307
        assert_eq!(item, Item::Done(Ok(ExitSts::Signal(9))));
1✔
308
        assert_closed(&mut stream).await;
1✔
309
        Ok(())
2✔
310
    }
1✔
311

312
    #[test]
313
    fn test_exitsts_display() {
1✔
314
        assert_eq!(format!("{}", ExitSts::Success), "success");
1✔
315
        assert_eq!(format!("{}", ExitSts::Code(42)), "code 42");
1✔
316
        assert_eq!(format!("{}", ExitSts::Signal(1)), "signal 1 (SIGHUP)");
1✔
317
        assert_eq!(format!("{}", ExitSts::Signal(12345)), "signal 12345");
1✔
318
    }
1✔
319
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc