Skip to content

Commit b093277

Browse files
committed
Refactor FinalError::display_and_crash into Error::Custom
1 parent 4041084 commit b093277

File tree

2 files changed

+30
-25
lines changed

2 files changed

+30
-25
lines changed

src/commands.rs

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use crate::{
2020
},
2121
info, oof, utils,
2222
utils::to_utf,
23+
Error,
2324
};
2425

2526
// Used in BufReader and BufWriter to perform less syscalls
@@ -32,14 +33,16 @@ pub fn run(command: Command, flags: &oof::Flags) -> crate::Result<()> {
3233
let formats = extension::extensions_from_path(&output_path);
3334

3435
if formats.is_empty() {
35-
FinalError::with_title(format!("Cannot compress to '{}'.", to_utf(&output_path)))
36+
let reason = FinalError::with_title(format!("Cannot compress to '{}'.", to_utf(&output_path)))
3637
.detail("You shall supply the compression format via the extension.")
3738
.hint("Try adding something like .tar.gz or .zip to the output file.")
3839
.hint("")
3940
.hint("Examples:")
4041
.hint(format!(" ouch compress ... {}.tar.gz", to_utf(&output_path)))
4142
.hint(format!(" ouch compress ... {}.zip", to_utf(&output_path)))
42-
.display_and_crash();
43+
.into_owned();
44+
45+
return Err(Error::with_reason(reason));
4346
}
4447

4548
if matches!(&formats[0], Bzip | Gzip | Lzma) && files.len() > 1 {
@@ -59,35 +62,35 @@ pub fn run(command: Command, flags: &oof::Flags) -> crate::Result<()> {
5962
let mut suggested_output_path = output_path.clone();
6063
suggested_output_path.replace_range(empty_range, ".tar");
6164

62-
FinalError::with_title(format!("Cannot compress to '{}'.", to_utf(&output_path)))
65+
let reason = FinalError::with_title(format!("Cannot compress to '{}'.", to_utf(&output_path)))
6366
.detail("You are trying to compress multiple files.")
6467
.detail(format!("The compression format '{}' cannot receive multiple files.", &formats[0]))
6568
.detail("The only supported formats that bundle files into an archive are .tar and .zip.")
6669
.hint(format!("Try inserting '.tar' or '.zip' before '{}'.", &formats[0]))
6770
.hint(format!("From: {}", output_path))
6871
.hint(format!(" To : {}", suggested_output_path))
69-
.display_and_crash();
72+
.into_owned();
73+
74+
return Err(Error::with_reason(reason));
7075
}
7176

7277
if let Some(format) = formats.iter().skip(1).position(|format| matches!(format, Tar | Zip)) {
73-
FinalError::with_title(format!("Cannot compress to '{}'.", to_utf(&output_path)))
78+
let reason = FinalError::with_title(format!("Cannot compress to '{}'.", to_utf(&output_path)))
7479
.detail(format!("Found the format '{}' in an incorrect position.", format))
7580
.detail(format!("{} can only be used at the start of the file extension.", format))
7681
.hint(format!("If you wish to compress multiple files, start the extension with {}.", format))
7782
.hint(format!("Otherwise, remove {} from '{}'.", format, to_utf(&output_path)))
78-
.display_and_crash();
83+
.into_owned();
84+
85+
return Err(Error::with_reason(reason));
7986
}
8087

8188
if output_path.exists() && !utils::user_wants_to_overwrite(&output_path, flags)? {
89+
// User does not want to overwrite this file
8290
return Ok(());
8391
}
8492

85-
let output_file = fs::File::create(&output_path).unwrap_or_else(|err| {
86-
FinalError::with_title(format!("Cannot compress to '{}'.", to_utf(&output_path)))
87-
.detail(format!("Could not open file '{}' for writing.", to_utf(&output_path)))
88-
.detail(format!("Error: {}.", err))
89-
.display_and_crash()
90-
});
93+
let output_file = fs::File::create(&output_path)?;
9194
let compress_result = compress_files(files, formats, output_file, flags);
9295

9396
// If any error occurred, delete incomplete file

src/error.rs

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,12 @@ pub enum Error {
3030
MissingArgumentsForDecompression,
3131
CompressionTypo,
3232
WalkdirError { reason: String },
33+
Custom { reason: FinalError },
3334
}
3435

3536
pub type Result<T> = std::result::Result<T, Error>;
3637

37-
#[derive(Default)]
38+
#[derive(Debug, Default, PartialEq)]
3839
pub struct FinalError {
3940
title: String,
4041
details: Vec<String>,
@@ -79,14 +80,9 @@ impl FinalError {
7980
self
8081
}
8182

82-
pub fn to_owned(&mut self) -> Self {
83+
pub fn into_owned(&mut self) -> Self {
8384
std::mem::take(self)
8485
}
85-
86-
pub fn display_and_crash(&self) -> ! {
87-
eprintln!("{}", self);
88-
std::process::exit(crate::EXIT_FAILURE)
89-
}
9086
}
9187

9288
impl fmt::Display for Error {
@@ -97,7 +93,7 @@ impl fmt::Display for Error {
9793
.detail("Ouch could not detect the compression format")
9894
.hint("Use a supported format extension, like '.zip' or '.tar.gz'")
9995
.hint("Check https://github.com/vrmiguel/ouch for a full list of supported formats")
100-
.to_owned();
96+
.into_owned();
10197

10298
error
10399
}
@@ -115,7 +111,7 @@ impl fmt::Display for Error {
115111
let error = FinalError::with_title("It seems you're trying to compress the root folder.")
116112
.detail("This is unadvisable since ouch does compressions in-memory.")
117113
.hint("Use a more appropriate tool for this, such as rsync.")
118-
.to_owned();
114+
.into_owned();
119115

120116
error
121117
}
@@ -127,7 +123,7 @@ impl fmt::Display for Error {
127123
.hint(" - The output argument.")
128124
.hint("")
129125
.hint("Example: `ouch compress image.png img.zip`")
130-
.to_owned();
126+
.into_owned();
131127

132128
error
133129
}
@@ -138,7 +134,7 @@ impl fmt::Display for Error {
138134
.hint(" - At least one input argument.")
139135
.hint("")
140136
.hint("Example: `ouch decompress imgs.tar.gz`")
141-
.to_owned();
137+
.into_owned();
142138

143139
error
144140
}
@@ -148,15 +144,15 @@ impl fmt::Display for Error {
148144
.detail("It's probably our fault")
149145
.detail("Please help us improve by reporting the issue at:")
150146
.detail(format!(" {}https://github.com/vrmiguel/ouch/issues ", cyan()))
151-
.to_owned();
147+
.into_owned();
152148

153149
error
154150
}
155151
Error::OofError(err) => FinalError::with_title(err),
156152
Error::IoError { reason } => FinalError::with_title(reason),
157153
Error::CompressionTypo => FinalError::with_title("Possible typo detected")
158154
.hint(format!("Did you mean '{}ouch compress{}'?", magenta(), reset()))
159-
.to_owned(),
155+
.into_owned(),
160156
_err => {
161157
todo!();
162158
}
@@ -166,6 +162,12 @@ impl fmt::Display for Error {
166162
}
167163
}
168164

165+
impl Error {
166+
pub fn with_reason(reason: FinalError) -> Self {
167+
Self::Custom { reason }
168+
}
169+
}
170+
169171
impl From<std::io::Error> for Error {
170172
fn from(err: std::io::Error) -> Self {
171173
match err.kind() {

0 commit comments

Comments
 (0)