uucore/mods/
panic.rs

1// This file is part of the uutils coreutils package.
2//
3// For the full copyright and license information, please view the LICENSE
4// file that was distributed with this source code.
5//! Custom panic hooks that allow silencing certain types of errors.
6//!
7//! Use the [`mute_sigpipe_panic`] function to silence panics caused by
8//! broken pipe errors. This can happen when a process is still
9//! producing data when the consuming process terminates and closes the
10//! pipe. For example,
11//!
12//! ```sh
13//! $ seq inf | head -n 1
14//! ```
15//!
16use std::panic::{self, PanicHookInfo};
17
18/// Decide whether a panic was caused by a broken pipe (SIGPIPE) error.
19fn is_broken_pipe(info: &PanicHookInfo) -> bool {
20    if let Some(res) = info.payload().downcast_ref::<String>() {
21        if res.contains("BrokenPipe") || res.contains("Broken pipe") {
22            return true;
23        }
24    }
25    false
26}
27
28/// Terminate without error on panics that occur due to broken pipe errors.
29///
30/// For background discussions on `SIGPIPE` handling, see
31///
32/// * `<https://github.com/uutils/coreutils/issues/374>`
33/// * `<https://github.com/uutils/coreutils/pull/1106>`
34/// * `<https://github.com/rust-lang/rust/issues/62569>`
35/// * `<https://github.com/BurntSushi/ripgrep/issues/200>`
36/// * `<https://github.com/crev-dev/cargo-crev/issues/287>`
37///
38pub fn mute_sigpipe_panic() {
39    let hook = panic::take_hook();
40    panic::set_hook(Box::new(move |info| {
41        if !is_broken_pipe(info) {
42            hook(info);
43        }
44    }));
45}