Skip to content

Commit b556b9e

Browse files
authored
Merge pull request #1120 from offscale/error-handling-improvements
[src/lib/error.rs] Support `T=std::process::ExitCode`, `CargoMakeError::ExitCode`, and DRY the else conditions
2 parents d00d2f1 + 4e6e650 commit b556b9e

File tree

1 file changed

+29
-15
lines changed

1 file changed

+29
-15
lines changed

src/lib/error.rs

+29-15
Original file line numberDiff line numberDiff line change
@@ -146,25 +146,39 @@ impl<T> From<Result<T, CargoMakeError>> for SuccessOrCargoMakeError<T> {
146146

147147
// Can't use `Result` because
148148
// [E0117] Only traits defined in the current crate can be implemented for arbitrary types
149-
impl<T> std::process::Termination for SuccessOrCargoMakeError<T> {
149+
impl<T: std::any::Any> std::process::Termination for SuccessOrCargoMakeError<T> {
150150
fn report(self) -> std::process::ExitCode {
151+
const PROCESS_EXIT_CODE: fn(i32) -> std::process::ExitCode = |e: i32| {
152+
if e > u8::MAX as i32 {
153+
eprintln!("exit code {}", e);
154+
std::process::ExitCode::FAILURE
155+
} else {
156+
std::process::ExitCode::from(e as u8)
157+
}
158+
};
159+
151160
match self {
161+
SuccessOrCargoMakeError::Ok(e)
162+
if std::any::TypeId::of::<T>()
163+
== std::any::TypeId::of::<std::process::ExitCode>() =>
164+
{
165+
*(&e as &dyn std::any::Any)
166+
.downcast_ref::<std::process::ExitCode>()
167+
.unwrap()
168+
}
152169
SuccessOrCargoMakeError::Ok(_) => std::process::ExitCode::SUCCESS,
153-
SuccessOrCargoMakeError::Err(error) => {
154-
if let CargoMakeError::StdIoError { ref error } = error {
155-
if let Some(e) = error.raw_os_error() {
156-
eprintln!("{}", e.to_string());
157-
return if e > u8::MAX as i32 {
158-
eprintln!("exit code {}", e);
159-
std::process::ExitCode::FAILURE
160-
} else {
161-
std::process::ExitCode::from(e as u8)
162-
};
163-
}
170+
SuccessOrCargoMakeError::Err(err) => match err {
171+
CargoMakeError::StdIoError { error } if error.raw_os_error().is_some() => {
172+
let e = unsafe { error.raw_os_error().unwrap_unchecked() };
173+
eprintln!("{}", e.to_string());
174+
PROCESS_EXIT_CODE(e)
164175
}
165-
eprintln!("{}", error.to_string());
166-
error.report()
167-
}
176+
CargoMakeError::ExitCode(error) => error,
177+
_ => {
178+
eprintln!("{}", err.to_string());
179+
PROCESS_EXIT_CODE(err.discriminant() as i32)
180+
}
181+
},
168182
}
169183
}
170184
}

0 commit comments

Comments
 (0)