processkit 0.9.1

Child-process management: kill-on-drop process trees and async run-and-capture
Documentation
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! The captured outcome of a finished process run.

use std::time::Duration;

use crate::error::Error;

/// How a run ended — the explicit form of the `code()`/`timed_out()` pair.
///
/// Non-exhaustive: a future disposition (e.g. a richer platform-specific
/// termination) can be added without a breaking change. The convenience
/// accessors [`ProcessResult::code`] / [`ProcessResult::timed_out`] /
/// [`ProcessResult::is_success`] derive from this and remain the everyday
/// surface; match on `Outcome` when the three-way distinction matters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Outcome {
    /// The process exited on its own with this code.
    Exited(i32),
    /// Terminated by a signal (Unix) — no exit code exists.
    Signalled,
    /// Killed because it exceeded its configured timeout.
    TimedOut,
}

/// The captured result of running a process to completion.
///
/// `T` is the standard-output payload: [`String`] for the text helpers
/// (`output_string`) or [`Vec<u8>`] for the raw-bytes helper (`output_bytes`).
/// Standard error is always captured as text. A non-zero exit code is **not**
/// treated as an error on its own — inspect [`code`](Self::code) or call
/// [`ensure_success`](Self::ensure_success).
#[derive(Debug, Clone)]
pub struct ProcessResult<T> {
    program: String,
    stdout: T,
    stderr: String,
    /// How the run ended (see [`Outcome`]); `code()`/`timed_out()` derive
    /// from it.
    outcome: Outcome,
    /// The deadline that elapsed, when timed out — carried so the
    /// success-checking helpers can build a faithful [`Error::Timeout`].
    timeout: Option<Duration>,
    /// Wall-clock duration of the run; `Duration::ZERO` for synthetic results
    /// (a scripted/replayed bulk `output` that didn't time a real process).
    duration: Duration,
    /// Whether a bounded [`OutputBufferPolicy`](crate::OutputBufferPolicy)
    /// dropped captured output lines.
    truncated: bool,
    /// Exit codes treated as success by [`is_success`](Self::is_success) /
    /// [`ensure_success`](Self::ensure_success). Default `[0]`; widened via
    /// [`Command::ok_codes`](crate::Command::ok_codes).
    ok_codes: Vec<i32>,
}

// Equality is over the *logical* outcome, not incidental measurement: `duration`
// (wall-clock timing) and `truncated` (buffer state) are deliberately excluded.
// This keeps the cassette's round-trip contract — a result and its replay compare
// equal — true even when the recording ran on a real runner (non-zero duration)
// while replay rebuilds it as `Duration::ZERO`. See `cassette.rs`.
impl<T: PartialEq> PartialEq for ProcessResult<T> {
    fn eq(&self, other: &Self) -> bool {
        self.program == other.program
            && self.stdout == other.stdout
            && self.stderr == other.stderr
            && self.outcome == other.outcome
            && self.timeout == other.timeout
            && self.ok_codes == other.ok_codes
    }
}

impl<T: Eq> Eq for ProcessResult<T> {}

impl<T> ProcessResult<T> {
    /// Build a result from the raw `code`/`timed_out` pair every producing
    /// path naturally has in hand. The pair folds into an [`Outcome`]
    /// (timeout wins, matching the check order in
    /// [`ensure_success`](Self::ensure_success)).
    pub(crate) fn new(
        program: String,
        stdout: T,
        stderr: String,
        code: Option<i32>,
        timed_out: bool,
        timeout: Option<Duration>,
    ) -> Self {
        let outcome = match (code, timed_out) {
            (_, true) => Outcome::TimedOut,
            (Some(code), false) => Outcome::Exited(code),
            (None, false) => Outcome::Signalled,
        };
        Self {
            program,
            stdout,
            stderr,
            outcome,
            timeout,
            // Producer-only setters fill these on the real run paths; the
            // defaults keep synthetic results (doubles, pipeline, tests) correct.
            duration: Duration::ZERO,
            truncated: false,
            ok_codes: vec![0],
        }
    }

    /// The program this result is attributed to (lossy UTF-8 of the program
    /// name) — the same value the error variants carry. For a
    /// [`Pipeline`](crate::Pipeline) outcome this is the pipefail-attributed
    /// stage: the first stage that didn't exit cleanly, or the last stage
    /// when every stage succeeded.
    pub fn program(&self) -> &str {
        &self.program
    }

    /// The captured standard output (text or bytes depending on `T`).
    pub fn stdout(&self) -> &T {
        &self.stdout
    }

    /// Consume the result and return just the captured standard output.
    pub fn into_stdout(self) -> T {
        self.stdout
    }

    /// The captured standard error.
    pub fn stderr(&self) -> &str {
        &self.stderr
    }

    /// How the run ended, as the explicit three-way [`Outcome`].
    pub fn outcome(&self) -> Outcome {
        self.outcome
    }

    /// The process exit code, or `None` when the run yielded no code — killed by
    /// its timeout ([`timed_out`](Self::timed_out) is then `true`) or terminated
    /// by a signal on Unix (`timed_out` is `false`). There is no synthetic
    /// sentinel: a missing code is `None`, never `-1`. Derived from
    /// [`outcome`](Self::outcome).
    pub fn code(&self) -> Option<i32> {
        match self.outcome {
            Outcome::Exited(code) => Some(code),
            _ => None,
        }
    }

    /// Whether the run was killed because it exceeded its timeout. Derived
    /// from [`outcome`](Self::outcome).
    pub fn timed_out(&self) -> bool {
        matches!(self.outcome, Outcome::TimedOut)
    }

    /// Whether the process exited with an **accepted** code — `0` by default, or
    /// any code in the set configured via
    /// [`Command::ok_codes`](crate::Command::ok_codes).
    pub fn is_success(&self) -> bool {
        matches!(self.outcome, Outcome::Exited(code) if self.ok_codes.contains(&code))
    }

    /// Return `self` unchanged when the run succeeded, otherwise the matching
    /// error: [`Error::Timeout`] if the run was killed by its deadline (checked
    /// first), an IO error if it was killed by a signal (no exit code), else
    /// [`Error::Exit`] for an exit code outside the accepted set (code `0` by
    /// default — see [`Command::ok_codes`](crate::Command::ok_codes)), carrying
    /// the code and both captured streams in full (the [`Display`](std::fmt::Display)
    /// impl bounds what it prints; the fields stay complete for classification).
    pub fn ensure_success(self) -> Result<Self, Error>
    where
        T: StdoutText,
    {
        match self.outcome {
            Outcome::Exited(code) if self.ok_codes.contains(&code) => Ok(self),
            Outcome::TimedOut => Err(Error::Timeout {
                program: self.program.clone(),
                timeout: self.timeout.unwrap_or_default(),
            }),
            // Terminated by a signal. Surface it as an IO error (consistent
            // with `require_code`) rather than a synthetic
            // `Error::Exit { code: -1 }`.
            Outcome::Signalled => Err(self.signal_error()),
            Outcome::Exited(code) => Err(Error::Exit {
                program: self.program.clone(),
                code,
                stdout: self.stdout.as_text(),
                stderr: self.stderr.clone(),
            }),
        }
    }

    /// The error for a run that was killed by a signal and so produced no exit
    /// code (a non-timeout `None` code).
    fn signal_error(&self) -> Error {
        Error::Io(std::io::Error::other(format!(
            "`{}` was terminated by a signal without an exit code",
            self.program
        )))
    }

    /// The exit code for the code-returning convenience helpers
    /// (`Command::exit_code`, `ProcessRunnerExt::exit_code`, `CliClient::exit_code`):
    /// a timeout surfaces as [`Error::Timeout`], a signal-kill (no code) as an
    /// IO error, otherwise the code.
    pub(crate) fn require_code(&self) -> Result<i32, Error> {
        match self.outcome {
            Outcome::Exited(code) => Ok(code),
            Outcome::TimedOut => Err(Error::Timeout {
                program: self.program.clone(),
                timeout: self.timeout.unwrap_or_default(),
            }),
            Outcome::Signalled => Err(self.signal_error()),
        }
    }

    /// The wall-clock duration of the run — spawn to exit (or kill). It is
    /// `Duration::ZERO` for synthetic results that didn't time a real process
    /// (a scripted/replayed bulk `output`).
    pub fn duration(&self) -> Duration {
        self.duration
    }

    /// Whether a bounded [`OutputBufferPolicy`](crate::OutputBufferPolicy) dropped
    /// captured output lines (the line counter exceeded what the buffer retained).
    /// Always `false` under the default unbounded policy, and for the raw stdout
    /// of [`output_bytes`](crate::Command::output_bytes) (not line-buffered).
    pub fn truncated(&self) -> bool {
        self.truncated
    }

    /// Stamp the run's wall-clock duration (producer-only).
    pub(crate) fn with_duration(mut self, duration: Duration) -> Self {
        self.duration = duration;
        self
    }

    /// Record that a bounded buffer dropped captured lines (producer-only).
    pub(crate) fn with_truncated(mut self, truncated: bool) -> Self {
        self.truncated = truncated;
        self
    }

    /// Set the exit codes treated as success (producer-only). An empty set is
    /// ignored — it would make every exit a failure — so the default `[0]` stands.
    pub(crate) fn with_ok_codes(mut self, ok_codes: Vec<i32>) -> Self {
        if !ok_codes.is_empty() {
            self.ok_codes = ok_codes;
        }
        self
    }
}

impl ProcessResult<String> {
    /// Standard output followed by standard error, concatenated — handy when a
    /// tool interleaves diagnostics across both streams.
    pub fn combined(&self) -> String {
        format!("{}{}", self.stdout(), self.stderr())
    }

    /// The best human-facing message from a captured run, trimmed of surrounding
    /// whitespace: standard error if it carries text, otherwise standard output —
    /// `git`/`jj` put `CONFLICT …` and `nothing to commit` on stdout, so a probe
    /// that captured the result (rather than erroring) can build the same friendly
    /// message [`Error::diagnostic`](crate::Error::diagnostic) gives the erroring
    /// path. For the raw, untrimmed streams use [`stdout`](Self::stdout) /
    /// [`stderr`](Self::stderr).
    pub fn diagnostic(&self) -> &str {
        if self.stderr.trim().is_empty() {
            self.stdout.trim()
        } else {
            self.stderr.trim()
        }
    }
}

/// Render captured stdout as text for [`Error::Exit`], whatever the payload type:
/// a [`String`] is taken as-is; raw bytes are decoded lossily.
///
/// An implementation detail of [`ensure_success`](ProcessResult::ensure_success):
/// `pub` only to satisfy the bound's visibility (the `result` module is private,
/// so it is unnameable outside the crate) and `#[doc(hidden)]` so it stays off
/// the public docs.
#[doc(hidden)]
pub trait StdoutText {
    fn as_text(&self) -> String;
}

impl StdoutText for String {
    fn as_text(&self) -> String {
        self.clone()
    }
}

impl StdoutText for Vec<u8> {
    fn as_text(&self) -> String {
        String::from_utf8_lossy(self).into_owned()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn outcome_reflects_the_three_terminal_states() {
        let exited = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Some(3),
            false,
            None,
        );
        assert_eq!(exited.outcome(), Outcome::Exited(3));

        let signalled =
            ProcessResult::new("x".into(), String::new(), String::new(), None, false, None);
        assert_eq!(signalled.outcome(), Outcome::Signalled);

        let timed_out =
            ProcessResult::new("x".into(), String::new(), String::new(), None, true, None);
        assert_eq!(timed_out.outcome(), Outcome::TimedOut);

        // A code alongside `timed_out` folds to TimedOut — the same precedence
        // ensure_success has always applied.
        let both = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Some(0),
            true,
            None,
        );
        assert_eq!(both.outcome(), Outcome::TimedOut);
    }

    #[test]
    fn derived_accessors_agree_with_outcome() {
        for (code, timed_out) in [
            (Some(0), false),
            (Some(7), false),
            (None, false),
            (None, true),
        ] {
            let r = ProcessResult::new(
                "x".into(),
                String::new(),
                String::new(),
                code,
                timed_out,
                None,
            );
            match r.outcome() {
                Outcome::Exited(c) => {
                    assert_eq!(r.code(), Some(c));
                    assert!(!r.timed_out());
                    assert_eq!(r.is_success(), c == 0);
                }
                Outcome::Signalled => {
                    assert_eq!(r.code(), None);
                    assert!(!r.timed_out());
                    assert!(!r.is_success());
                }
                Outcome::TimedOut => {
                    assert_eq!(r.code(), None);
                    assert!(r.timed_out());
                    assert!(!r.is_success());
                }
            }
        }
    }

    #[test]
    fn success_is_code_zero() {
        let ok = ProcessResult::new(
            "git".into(),
            "out".to_owned(),
            String::new(),
            Some(0),
            false,
            None,
        );
        assert!(ok.is_success());
        assert_eq!(ok.code(), Some(0));
        assert!(ok.ensure_success().is_ok());
    }

    #[test]
    fn nonzero_exit_carries_both_streams() {
        let bad = ProcessResult::new(
            "git".into(),
            "CONFLICT (content): merge conflict in a.rs".to_owned(),
            "boom".to_owned(),
            Some(2),
            false,
            None,
        );
        assert!(!bad.is_success());
        assert_eq!(bad.code(), Some(2));
        let err = bad.ensure_success().unwrap_err();
        match err {
            Error::Exit {
                program,
                code,
                stdout,
                stderr,
            } => {
                assert_eq!(program, "git");
                assert_eq!(code, 2);
                assert_eq!(stdout, "CONFLICT (content): merge conflict in a.rs");
                assert_eq!(stderr, "boom");
            }
            other => panic!("expected Exit, got {other:?}"),
        }
    }

    #[test]
    fn diagnostic_prefers_stderr_then_falls_back_to_stdout() {
        // stderr present → stderr wins, trimmed of surrounding whitespace.
        let with_stderr = ProcessResult::new(
            "git".into(),
            "on stdout".into(),
            "  on stderr \n".into(),
            Some(1),
            false,
            None,
        );
        assert_eq!(with_stderr.diagnostic(), "on stderr");
        assert_eq!(
            with_stderr.ensure_success().unwrap_err().diagnostic(),
            Some("on stderr")
        );

        // stderr blank → stdout (where `git merge` writes CONFLICT) is the message.
        let conflict = ProcessResult::new(
            "git".into(),
            "CONFLICT (content): merge conflict in a.rs".into(),
            "   \n".into(),
            Some(1),
            false,
            None,
        );
        assert_eq!(
            conflict.diagnostic(),
            "CONFLICT (content): merge conflict in a.rs"
        );
        // The erroring path exposes the same rule via Error::diagnostic.
        let Error::Exit { .. } = conflict.clone().ensure_success().unwrap_err() else {
            panic!("expected Exit");
        };
        assert_eq!(
            conflict.ensure_success().unwrap_err().diagnostic(),
            Some("CONFLICT (content): merge conflict in a.rs")
        );

        // Both streams blank → no captured message; the caller falls back to the
        // Display text rather than getting an empty string.
        let silent = ProcessResult::new(
            "git".into(),
            String::new(),
            "  \n".into(),
            Some(1),
            false,
            None,
        );
        assert_eq!(silent.ensure_success().unwrap_err().diagnostic(), None);
    }

    #[test]
    fn timed_out_takes_precedence_over_exit_code() {
        // A timed-out run has no code (None), and ensure_success must report it
        // as a distinct Timeout, not a non-zero Exit.
        let timed = ProcessResult::new(
            "git".into(),
            "out".to_owned(),
            String::new(),
            None,
            true,
            Some(Duration::from_millis(500)),
        );
        assert!(timed.timed_out());
        assert_eq!(timed.code(), None);
        match timed.ensure_success().unwrap_err() {
            Error::Timeout { program, timeout } => {
                assert_eq!(program, "git");
                assert_eq!(timeout, Duration::from_millis(500));
            }
            other => panic!("expected Timeout, got {other:?}"),
        }
    }

    #[test]
    fn signal_kill_has_no_code_and_never_yields_minus_one() {
        // A signal-terminated run (no code, not a timeout) reports `None`. Both
        // `require_code` and `ensure_success` must surface an IO error — never a
        // synthetic `Error::Exit { code: -1 }`, which would resurrect the sentinel.
        let killed = ProcessResult::new(
            "git".into(),
            "out".to_owned(),
            String::new(),
            None,
            false,
            None,
        );
        assert_eq!(killed.code(), None);
        assert!(!killed.is_success());
        assert!(matches!(killed.require_code().unwrap_err(), Error::Io(_)));
        match killed.ensure_success().unwrap_err() {
            Error::Io(_) => {}
            other => panic!("expected Io for a signal-kill, got {other:?}"),
        }
    }

    #[test]
    fn combined_concatenates_stdout_then_stderr() {
        let r = ProcessResult::new(
            "p".into(),
            "out".to_owned(),
            "err".to_owned(),
            Some(0),
            false,
            None,
        );
        assert_eq!(r.combined(), "outerr");
    }

    #[test]
    fn error_exit_carries_full_streams() {
        // The error fields must carry the complete captured streams — consumers
        // classify on them (grep for a marker, parse a code), and truncating
        // before classification destroyed data. The `Display` impl bounds what
        // it *prints*; the fields stay whole.
        let big = "x".repeat(10_000);
        let bad = ProcessResult::new(
            "p".into(),
            big.clone().into_bytes(),
            big.clone(),
            Some(1),
            false,
            None,
        );
        assert_eq!(bad.stderr().len(), 10_000);
        let Error::Exit { stdout, stderr, .. } = bad.ensure_success().unwrap_err() else {
            panic!("expected Exit");
        };
        assert_eq!(stdout.len(), 10_000, "full stdout carried, untruncated");
        assert_eq!(stderr.len(), 10_000, "full stderr carried, untruncated");
        assert!(stdout.chars().all(|c| c == 'x'));
        assert!(stderr.chars().all(|c| c == 'x'));
    }

    #[test]
    fn ok_codes_widen_success_without_masking_other_failures() {
        let one = ProcessResult::new(
            "grep".into(),
            "out".to_owned(),
            String::new(),
            Some(1),
            false,
            None,
        )
        .with_ok_codes(vec![0, 1]);
        assert!(one.is_success(), "exit 1 is success when accepted");
        assert!(one.ensure_success().is_ok());

        let two = ProcessResult::new(
            "grep".into(),
            "out".to_owned(),
            String::new(),
            Some(2),
            false,
            None,
        )
        .with_ok_codes(vec![0, 1]);
        assert!(!two.is_success(), "an unaccepted code is still a failure");
        assert!(matches!(
            two.ensure_success().unwrap_err(),
            Error::Exit { code: 2, .. }
        ));
    }

    #[test]
    fn new_defaults_zero_duration_untruncated_and_zero_only_success() {
        let r = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Some(1),
            false,
            None,
        );
        assert_eq!(r.duration(), Duration::ZERO);
        assert!(!r.truncated());
        assert!(!r.is_success(), "the default accepts only code 0");

        let stamped = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Some(0),
            false,
            None,
        )
        .with_duration(Duration::from_millis(5))
        .with_truncated(true);
        assert_eq!(stamped.duration(), Duration::from_millis(5));
        assert!(stamped.truncated());
        assert!(stamped.is_success());
    }

    #[test]
    fn empty_ok_codes_is_ignored() {
        let r = ProcessResult::new(
            "x".into(),
            String::new(),
            String::new(),
            Some(0),
            false,
            None,
        )
        .with_ok_codes(vec![]);
        assert!(
            r.is_success(),
            "an empty accepted set falls back to the default [0]"
        );
    }

    #[test]
    fn equality_ignores_duration_and_truncation() {
        // The cassette round-trip relies on this: a recorded result (real,
        // non-zero duration) must compare equal to its replay (Duration::ZERO).
        let base = ProcessResult::new(
            "p".into(),
            "out".to_owned(),
            String::new(),
            Some(0),
            false,
            None,
        );
        let measured = base
            .clone()
            .with_duration(Duration::from_secs(5))
            .with_truncated(true);
        assert_eq!(
            base, measured,
            "duration and truncation are not part of identity"
        );

        // …but the logical fields still distinguish results.
        let different = ProcessResult::new(
            "p".into(),
            "DIFF".to_owned(),
            String::new(),
            Some(0),
            false,
            None,
        );
        assert_ne!(base, different);
        let widened = base.clone().with_ok_codes(vec![0, 1]);
        assert_ne!(base, widened, "ok_codes is part of identity");
    }
}