anyhow_std/process/
command.rs

1use crate::process::{Child, ExitStatus, Output};
2use anyhow::Context;
3use std::process::Command;
4
5/// Extend [std::process::Command] with [anyhow] methods
6pub trait CommandAnyhow {
7    /// Wrap [Command::spawn](std::process::Command::spawn), providing the command as error context
8    fn spawn_anyhow(&mut self) -> anyhow::Result<Child>;
9
10    /// Wrap [Command::output](std::process::Command::output), providing the command as error context
11    fn output_anyhow(&mut self) -> anyhow::Result<Output>;
12
13    /// Wrap [Command::status](std::process::Command::status), providing the command as error context
14    fn status_anyhow(&mut self) -> anyhow::Result<ExitStatus>;
15
16    /// Describe the command for error contexts
17    fn anyhow_context(&self) -> String;
18}
19
20impl CommandAnyhow for Command {
21    fn spawn_anyhow(&mut self) -> anyhow::Result<Child> {
22        self.spawn()
23            .map(|c| Child::from((c, self.anyhow_context())))
24            .context(self.anyhow_context())
25    }
26
27    fn output_anyhow(&mut self) -> anyhow::Result<Output> {
28        self.output()
29            .map(|o| Output::wrap(o, self.anyhow_context()))
30            .context(self.anyhow_context())
31    }
32
33    fn status_anyhow(&mut self) -> anyhow::Result<ExitStatus> {
34        self.status()
35            .map(|c| ExitStatus::from((c, self.anyhow_context())))
36            .context(self.anyhow_context())
37    }
38
39    fn anyhow_context(&self) -> String {
40        format!("command: {:?}", self)
41    }
42}