From 30091a5f16d8f9af62b328c80e14194bd5e3c66e Mon Sep 17 00:00:00 2001 From: Ayman Bagabas Date: Tue, 17 Nov 2020 14:04:16 -0500 Subject: [PATCH] Implement pipe handling Ref: https://github.com/rust-lang/rust/issues/46016#issuecomment-605624865 Fixes: https://github.com/clearloop/leetcode-cli/issues/21 --- Cargo.toml | 3 +++ src/cli.rs | 16 ++++++++++++++++ src/cmds/list.rs | 6 +++--- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 61ad8f6..4f8f9c6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,3 +48,6 @@ features = ["precommit-hook", "user-hooks"] [features] pym = ["pyo3"] + +[target.'cfg(target_family = "unix")'.dependencies] +nix = "0.17.0" diff --git a/src/cli.rs b/src/cli.rs index b145b68..f47cbca 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -9,8 +9,24 @@ use crate::{ }; use clap::{crate_name, crate_version, App, AppSettings}; +/// This should be called before calling any cli method or printing any output. +pub fn reset_signal_pipe_handler() -> Result<(), ()> { + #[cfg(target_family = "unix")] + { + use nix::sys::signal; + + unsafe { + signal::signal(signal::Signal::SIGPIPE, signal::SigHandler::SigDfl) + .map_err(|e| println!("{:?}", e))?; + } + } + + Ok(()) +} + /// Get maches pub async fn main() -> Result<(), Error> { + let _ = reset_signal_pipe_handler(); let m = App::new(crate_name!()) .version(crate_version!()) .about("May the Code be with You 👻") diff --git a/src/cmds/list.rs b/src/cmds/list.rs index 212fa1e..b390d7b 100644 --- a/src/cmds/list.rs +++ b/src/cmds/list.rs @@ -37,6 +37,7 @@ use super::Command; use crate::{cache::Cache, err::Error, helper::Digit}; use async_trait::async_trait; use clap::{App, Arg, ArgMatches, SubCommand}; +use std::io::{self, Write}; /// Abstract `list` command /// /// ## handler @@ -168,9 +169,8 @@ impl Command for ListCommand { ps.retain(|x| x.name.contains(&keyword)); } - for p in &ps { - println!("{}", p); - } + let out: Vec = ps.iter().map(ToString::to_string).collect(); + io::stdout().write_all(out.join("\n").as_bytes())?; // one more thing, filter stat if m.is_present("stat") {