libcoreinst/
util.rs

1// Copyright 2020 CoreOS, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use anyhow::{bail, Context, Result};
16use std::process::Command;
17
18/// Runs the provided command. The first macro argument is the executable, and following arguments
19/// are passed to the command. Returns a Result<()> describing whether the command failed. Errors
20/// are adequately prefixed with the full command.
21#[macro_export]
22macro_rules! runcmd {
23    ($cmd:expr) => (runcmd!($cmd,));
24    ($cmd:expr, $($args:expr),*) => {{
25        let mut cmd = Command::new($cmd);
26        $( cmd.arg($args); )*
27        let status = cmd.status().with_context(|| format!("running {:#?}", cmd))?;
28        if !status.success() {
29            Result::Err(anyhow!("{:#?} failed with {}", cmd, status))
30        } else {
31            Result::Ok(())
32        }
33    }}
34}
35
36/// Runs the provided command, captures its stdout, and swallows its stderr except on failure.
37/// The first macro argument is the executable, and following arguments are passed to the command.
38/// Returns a Result<String> describing whether the command failed, and if not, its standard
39/// output. Output is assumed to be UTF-8. Errors are adequately prefixed with the full command.
40#[macro_export]
41macro_rules! runcmd_output {
42    ($cmd:expr) => (runcmd_output!($cmd,));
43    ($cmd:expr, $($args:expr),*) => {{
44        let mut cmd = Command::new($cmd);
45        $( cmd.arg($args); )*
46        // NB: cmd_output already prefixes with cmd in all error paths
47        cmd_output(&mut cmd)
48    }}
49}
50
51/// Runs the provided Command object, captures its stdout, and swallows its stderr except on
52/// failure. Returns a Result<String> describing whether the command failed, and if not, its
53/// standard output. Output is assumed to be UTF-8. Errors are adequately prefixed with the full
54/// command.
55pub fn cmd_output(cmd: &mut Command) -> Result<String> {
56    let result = cmd.output().with_context(|| format!("running {cmd:#?}"))?;
57    if !result.status.success() {
58        eprint!("{}", String::from_utf8_lossy(&result.stderr));
59        bail!("{:#?} failed with {}", cmd, result.status);
60    }
61    String::from_utf8(result.stdout)
62        .with_context(|| format!("decoding as UTF-8 output of `{cmd:#?}`"))
63}
64
65/// Rust ignores SIGPIPE by default, which causes verbose failures when
66/// our output is piped to a program that exits.  Unignore SIGPIPE to avoid
67/// this.  This will give the program no chance to clean up, so is only
68/// appropriate for simple reporting/debugging commands.
69// https://github.com/rust-lang/rust/issues/46016
70pub fn set_die_on_sigpipe() -> Result<()> {
71    use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};
72    unsafe {
73        sigaction(
74            Signal::SIGPIPE,
75            &SigAction::new(SigHandler::SigDfl, SaFlags::empty(), SigSet::empty()),
76        )
77    }
78    .map(|_| ())
79    .context("resetting SIGPIPE handler")
80}