From 6a341d37238b7a0529f290fd2f7624ae470fedf4 Mon Sep 17 00:00:00 2001 From: Matthias Beyer Date: Wed, 14 Feb 2018 18:07:11 +0100 Subject: [PATCH] Abstract exit code as a type --- bin/domain/imag-log/src/main.rs | 2 +- lib/core/libimagerror/src/exit.rs | 12 ++++++++++-- lib/core/libimagerror/src/io.rs | 11 +++++++---- 3 files changed, 18 insertions(+), 7 deletions(-) diff --git a/bin/domain/imag-log/src/main.rs b/bin/domain/imag-log/src/main.rs index c3f80017..b6744831 100644 --- a/bin/domain/imag-log/src/main.rs +++ b/bin/domain/imag-log/src/main.rs @@ -140,7 +140,7 @@ fn show(rt: &Runtime) { text = e.get_content()) .to_exit_code() }) - .collect::>() + .collect::, _>>() .unwrap_or_exit(); } } diff --git a/lib/core/libimagerror/src/exit.rs b/lib/core/libimagerror/src/exit.rs index 6af8773d..777fe684 100644 --- a/lib/core/libimagerror/src/exit.rs +++ b/lib/core/libimagerror/src/exit.rs @@ -17,13 +17,21 @@ // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // +pub struct ExitCode(i32); + +impl From for ExitCode { + fn from(i: i32) -> ExitCode { + ExitCode(i) + } +} + pub trait ExitUnwrap { fn unwrap_or_exit(self) -> T; } -impl ExitUnwrap for Result { +impl> ExitUnwrap for Result { fn unwrap_or_exit(self) -> T { - self.unwrap_or_else(|e| ::std::process::exit(e)) + self.map_err(Into::into).unwrap_or_else(|e| ::std::process::exit(e.0)) } } diff --git a/lib/core/libimagerror/src/io.rs b/lib/core/libimagerror/src/io.rs index ac648427..fff73a61 100644 --- a/lib/core/libimagerror/src/io.rs +++ b/lib/core/libimagerror/src/io.rs @@ -19,20 +19,22 @@ use std::io::ErrorKind; +use exit::ExitCode; + pub enum Settings { Ignore(ErrorKind), IgnoreAny(Vec), } pub trait ToExitCode { - fn to_exit_code(self) -> Result; - fn to_exit_code_with(self, Settings) -> Result; + fn to_exit_code(self) -> Result; + fn to_exit_code_with(self, Settings) -> Result; } impl ToExitCode for Result { /// Returns an exit code of 0 if the error was a broken pipe, else 1 - fn to_exit_code(self) -> Result { + fn to_exit_code(self) -> Result { self.to_exit_code_with(Settings::Ignore(ErrorKind::BrokenPipe)) } @@ -41,7 +43,7 @@ impl ToExitCode for Result { /// Via the settings, errors can be ignores (translates to exit code zero). All other errors /// are translated into exit code 1 /// - fn to_exit_code_with(self, settings: Settings) -> Result { + fn to_exit_code_with(self, settings: Settings) -> Result { self.map_err(move |e| match settings { Settings::Ignore(kind) => if e.kind() == kind { 0 @@ -54,6 +56,7 @@ impl ToExitCode for Result { 1 }, }) + .map_err(ExitCode::from) } }