Extract function

This commit is contained in:
Spyros Roum 2021-11-02 13:34:04 +02:00
parent 8ef1b25b12
commit 547b8c91e5
2 changed files with 29 additions and 17 deletions

View File

@ -326,22 +326,12 @@ fn decompress_file(
Gzip | Bzip | Lzma | Zstd => { Gzip | Bzip | Lzma | Zstd => {
reader = chain_reader_decoder(&formats[0].compression_formats[0], reader)?; reader = chain_reader_decoder(&formats[0].compression_formats[0], reader)?;
let mut writer = match fs::OpenOptions::new().write(true).create_new(true).open(&output_path) { let writer = utils::create_or_ask_overwrite(&output_path, question_policy)?;
Ok(w) => w, if writer.is_none() {
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { // Means that the user doesn't want to overwrite
if utils::user_wants_to_overwrite(&output_path, question_policy)? {
if output_path.is_dir() {
// We can't just use `fs::File::create(&output_path)` because it would return io::ErrorKind::IsADirectory
// ToDo: Maybe we should emphasise that `output_path` is a directory and everything inside it will be gone?
fs::remove_dir_all(&output_path)?;
}
fs::File::create(&output_path)?
} else {
return Ok(()); return Ok(());
} }
} let mut writer = writer.unwrap();
Err(e) => return Err(Error::from(e)),
};
io::copy(&mut reader, &mut writer)?; io::copy(&mut reader, &mut writer)?;
files_unpacked = vec![output_path]; files_unpacked = vec![output_path];

View File

@ -3,13 +3,35 @@
use std::{ use std::{
cmp, env, cmp, env,
ffi::OsStr, ffi::OsStr,
io,
path::Component, path::Component,
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use fs_err as fs; use fs_err as fs;
use crate::{dialogs::Confirmation, info}; use crate::{dialogs::Confirmation, info, Error};
/// Create the file if it doesn't exist and if it does then ask to overwrite it.
/// If the user doesn't want to overwrite then we return [`Ok(None)`]
pub fn create_or_ask_overwrite(path: &Path, question_policy: QuestionPolicy) -> Result<Option<fs::File>, Error> {
match fs::OpenOptions::new().write(true).create_new(true).open(path) {
Ok(w) => Ok(Some(w)),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
if user_wants_to_overwrite(path, question_policy)? {
if path.is_dir() {
// We can't just use `fs::File::create(&path)` because it would return io::ErrorKind::IsADirectory
// ToDo: Maybe we should emphasise that `path` is a directory and everything inside it will be gone?
fs::remove_dir_all(path)?;
}
Ok(Some(fs::File::create(path)?))
} else {
Ok(None)
}
}
Err(e) => Err(Error::from(e)),
}
}
/// Checks if the given path represents an empty directory. /// Checks if the given path represents an empty directory.
pub fn dir_is_empty(dir_path: &Path) -> bool { pub fn dir_is_empty(dir_path: &Path) -> bool {