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
use crate::process::{ExitStatus, Output};
use anyhow::Context;
use std::ops::Deref;
use std::process::{ChildStderr, ChildStdin, ChildStdout};

/// Wrap [std::process::Child] to provide the command as error context
#[derive(Debug)]
pub struct Child {
    pub stdin: Option<ChildStdin>,
    pub stdout: Option<ChildStdout>,
    pub stderr: Option<ChildStderr>,
    child: std::process::Child,
    cmddesc: String,
}

impl From<(std::process::Child, String)> for Child {
    fn from((mut child, cmddesc): (std::process::Child, String)) -> Self {
        Child {
            stdin: child.stdin.take(),
            stdout: child.stdout.take(),
            stderr: child.stderr.take(),
            child,
            cmddesc,
        }
    }
}

impl Deref for Child {
    type Target = std::process::Child;

    fn deref(&self) -> &Self::Target {
        &self.child
    }
}

impl Child {
    /// Override [std::process::Child::kill] with the command as error context
    pub fn kill(&mut self) -> anyhow::Result<()> {
        self.child.kill().context(self.cmddesc.clone())
    }

    /// Override [std::process::Child::wait] with the command as error context
    pub fn wait(&mut self) -> anyhow::Result<ExitStatus> {
        self.child
            .wait()
            .map(|es| ExitStatus::from((es, self.cmddesc.clone())))
            .context(self.cmddesc.clone())
    }

    /// Override [std::process::Child::try_wait] with the command as error context
    pub fn try_wait(&mut self) -> anyhow::Result<Option<ExitStatus>> {
        self.child
            .try_wait()
            .map(|optes| optes.map(|es| ExitStatus::from((es, self.cmddesc.clone()))))
            .context(self.cmddesc.clone())
    }

    /// Override [std::process::Child::wait_with_output] with the command as error context
    pub fn wait_with_output(self) -> anyhow::Result<Output> {
        self.child
            .wait_with_output()
            .map(|o| Output::wrap(o, self.cmddesc.clone()))
            .context(self.cmddesc)
    }
}