Abstract exit code as a type
This commit is contained in:
parent
eb2f6fbbe2
commit
6a341d3723
3 changed files with 18 additions and 7 deletions
|
@ -140,7 +140,7 @@ fn show(rt: &Runtime) {
|
|||
text = e.get_content())
|
||||
.to_exit_code()
|
||||
})
|
||||
.collect::<Result<(), i32>>()
|
||||
.collect::<Result<Vec<()>, _>>()
|
||||
.unwrap_or_exit();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -17,13 +17,21 @@
|
|||
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
//
|
||||
|
||||
pub struct ExitCode(i32);
|
||||
|
||||
impl From<i32> for ExitCode {
|
||||
fn from(i: i32) -> ExitCode {
|
||||
ExitCode(i)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ExitUnwrap<T> {
|
||||
fn unwrap_or_exit(self) -> T;
|
||||
}
|
||||
|
||||
impl<T> ExitUnwrap<T> for Result<T, i32> {
|
||||
impl<T, E: Into<ExitCode>> ExitUnwrap<T> for Result<T, E> {
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -19,20 +19,22 @@
|
|||
|
||||
use std::io::ErrorKind;
|
||||
|
||||
use exit::ExitCode;
|
||||
|
||||
pub enum Settings {
|
||||
Ignore(ErrorKind),
|
||||
IgnoreAny(Vec<ErrorKind>),
|
||||
}
|
||||
|
||||
pub trait ToExitCode<T> {
|
||||
fn to_exit_code(self) -> Result<T, i32>;
|
||||
fn to_exit_code_with(self, Settings) -> Result<T, i32>;
|
||||
fn to_exit_code(self) -> Result<T, ExitCode>;
|
||||
fn to_exit_code_with(self, Settings) -> Result<T, ExitCode>;
|
||||
}
|
||||
|
||||
impl<T> ToExitCode<T> for Result<T, ::std::io::Error> {
|
||||
|
||||
/// Returns an exit code of 0 if the error was a broken pipe, else 1
|
||||
fn to_exit_code(self) -> Result<T, i32> {
|
||||
fn to_exit_code(self) -> Result<T, ExitCode> {
|
||||
self.to_exit_code_with(Settings::Ignore(ErrorKind::BrokenPipe))
|
||||
}
|
||||
|
||||
|
@ -41,7 +43,7 @@ impl<T> ToExitCode<T> for Result<T, ::std::io::Error> {
|
|||
/// 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<T, i32> {
|
||||
fn to_exit_code_with(self, settings: Settings) -> Result<T, ExitCode> {
|
||||
self.map_err(move |e| match settings {
|
||||
Settings::Ignore(kind) => if e.kind() == kind {
|
||||
0
|
||||
|
@ -54,6 +56,7 @@ impl<T> ToExitCode<T> for Result<T, ::std::io::Error> {
|
|||
1
|
||||
},
|
||||
})
|
||||
.map_err(ExitCode::from)
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue