minor simplifications and renamings

This commit is contained in:
João M. Bezerra 2022-06-04 14:03:33 -03:00
parent 14025c6816
commit 97c4387fcf
7 changed files with 32 additions and 32 deletions

View File

@ -16,7 +16,7 @@ use crate::{
info, info,
list::FileInArchive, list::FileInArchive,
utils::{ utils::{
self, cd_into_same_dir_as, concatenate_os_str_list, get_invalid_utf8_paths, strip_cur_dir, to_utf, Bytes, self, cd_into_same_dir_as, get_invalid_utf8_paths, pretty_format_list_of_paths, strip_cur_dir, to_utf, Bytes,
FileVisibilityPolicy, FileVisibilityPolicy,
}, },
}; };
@ -47,7 +47,7 @@ where
display_zip_comment_if_exists(&file); display_zip_comment_if_exists(&file);
match (&*file.name()).ends_with('/') { match file.name().ends_with('/') {
_is_dir @ true => { _is_dir @ true => {
// This is printed for every file in the archive and has little // This is printed for every file in the archive and has little
// importance for most users, but would generate lots of // importance for most users, but would generate lots of
@ -146,7 +146,7 @@ where
.detail("Zip archives require files to have valid UTF-8 paths") .detail("Zip archives require files to have valid UTF-8 paths")
.detail(format!( .detail(format!(
"Files with invalid paths: {}", "Files with invalid paths: {}",
concatenate_os_str_list(&invalid_unicode_filenames) pretty_format_list_of_paths(&invalid_unicode_filenames)
)); ));
return Err(error.into()); return Err(error.into());
@ -183,7 +183,7 @@ where
return Err(e.into()); return Err(e.into());
} }
}; };
writer.write_all(&*file_bytes)?; writer.write_all(&file_bytes)?;
} }
} }

View File

@ -203,7 +203,8 @@ pub fn decompress_file(
/// Unpacks an archive with some heuristics /// Unpacks an archive with some heuristics
/// - If the archive contains only one file, it will be extracted to the `output_dir` /// - If the archive contains only one file, it will be extracted to the `output_dir`
/// - If the archive contains multiple files, it will be extracted to a subdirectory of the output_dir named after the archive (given by `output_file_path`) /// - If the archive contains multiple files, it will be extracted to a subdirectory of the
/// output_dir named after the archive (given by `output_file_path`)
/// Note: This functions assumes that `output_dir` exists /// Note: This functions assumes that `output_dir` exists
fn smart_unpack( fn smart_unpack(
unpack_fn: Box<dyn FnOnce(&Path) -> crate::Result<Vec<PathBuf>>>, unpack_fn: Box<dyn FnOnce(&Path) -> crate::Result<Vec<PathBuf>>>,

View File

@ -22,7 +22,7 @@ use crate::{
info, info,
list::ListOptions, list::ListOptions,
utils::{ utils::{
self, concatenate_os_str_list, dir_is_empty, to_utf, try_infer_extension, user_wants_to_continue, self, dir_is_empty, pretty_format_list_of_paths, to_utf, try_infer_extension, user_wants_to_continue,
FileVisibilityPolicy, FileVisibilityPolicy,
}, },
warning, Opts, QuestionAction, QuestionPolicy, Subcommand, warning, Opts, QuestionAction, QuestionPolicy, Subcommand,
@ -266,7 +266,7 @@ pub fn run(
let error = FinalError::with_title("Cannot decompress files without extensions") let error = FinalError::with_title("Cannot decompress files without extensions")
.detail(format!( .detail(format!(
"Files without supported extensions: {}", "Files without supported extensions: {}",
concatenate_os_str_list(&files_missing_format) pretty_format_list_of_paths(&files_missing_format)
)) ))
.detail("Decompression formats are detected automatically by the file extension") .detail("Decompression formats are detected automatically by the file extension")
.hint("Provide a file with a supported extension:") .hint("Provide a file with a supported extension:")
@ -323,7 +323,7 @@ pub fn run(
.detail("Only archives can have their contents listed") .detail("Only archives can have their contents listed")
.detail(format!( .detail(format!(
"Files are not archives: {}", "Files are not archives: {}",
concatenate_os_str_list(&not_archives) pretty_format_list_of_paths(&not_archives)
)); ));
return Err(error.into()); return Err(error.into());

View File

@ -9,7 +9,6 @@ use std::{
use crate::utils::colors::*; use crate::utils::colors::*;
#[allow(missing_docs)]
/// All errors that can be generated by `ouch` /// All errors that can be generated by `ouch`
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub enum Error { pub enum Error {
@ -53,7 +52,7 @@ pub struct FinalError {
} }
impl Display for FinalError { impl Display for FinalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Title // Title
// //
// When in ACCESSIBLE mode, the square brackets are suppressed // When in ACCESSIBLE mode, the square brackets are suppressed

View File

@ -39,7 +39,7 @@ impl Extension {
} }
impl fmt::Display for Extension { impl fmt::Display for Extension {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.display_text.fmt(f) self.display_text.fmt(f)
} }
} }
@ -174,7 +174,7 @@ mod tests {
// Panics if formats has an empty list of compression formats // Panics if formats has an empty list of compression formats
pub fn split_first_compression_format(formats: &[Extension]) -> (CompressionFormat, Vec<CompressionFormat>) { pub fn split_first_compression_format(formats: &[Extension]) -> (CompressionFormat, Vec<CompressionFormat>) {
let mut extensions: Vec<CompressionFormat> = flatten_compression_formats(&formats); let mut extensions: Vec<CompressionFormat> = flatten_compression_formats(formats);
let first_extension = extensions.remove(0); let first_extension = extensions.remove(0);
(first_extension, extensions) (first_extension, extensions)
} }

View File

@ -1,14 +1,11 @@
use std::{borrow::Cow, cmp, path::Path}; use std::{borrow::Cow, cmp, env, path::Path};
// The lifetimes here could elided but I think they help
// comprehension in this case
#[allow(clippy::needless_lifetimes)]
/// Converts an OsStr to utf8 with custom formatting. /// Converts an OsStr to utf8 with custom formatting.
/// ///
/// This is different from [`Path::display`]. /// This is different from [`Path::display`].
/// ///
/// See <https://gist.github.com/marcospb19/ebce5572be26397cf08bbd0fd3b65ac1> for a comparison. /// See <https://gist.github.com/marcospb19/ebce5572be26397cf08bbd0fd3b65ac1> for a comparison.
pub fn to_utf<'a>(os_str: &'a Path) -> Cow<'a, str> { pub fn to_utf(os_str: &Path) -> Cow<str> {
let format = || { let format = || {
let text = format!("{:?}", os_str); let text = format!("{:?}", os_str);
Cow::Owned(text.trim_matches('"').to_string()) Cow::Owned(text.trim_matches('"').to_string())
@ -17,34 +14,37 @@ pub fn to_utf<'a>(os_str: &'a Path) -> Cow<'a, str> {
os_str.to_str().map_or_else(format, Cow::Borrowed) os_str.to_str().map_or_else(format, Cow::Borrowed)
} }
/// Removes the current dir from the beginning of a path /// Removes the current dir from the beginning of a path as it's redundant information,
/// normally used for presentation sake. /// useful for presentation sake.
/// If this function fails, it will return source path as a PathBuf.
pub fn strip_cur_dir(source_path: &Path) -> &Path { pub fn strip_cur_dir(source_path: &Path) -> &Path {
let cwd = std::env::current_dir().unwrap_or_else(|_| Path::new(".").to_path_buf()); let current_dir = env::current_dir();
source_path.strip_prefix(cwd).unwrap_or(source_path)
let current_dir = match &current_dir {
Ok(inner) => inner.as_path(),
Err(_) => Path::new(""),
};
source_path.strip_prefix(current_dir).unwrap_or(source_path)
} }
/// Converts a slice of AsRef<OsStr> to comma separated String /// Converts a slice of AsRef<OsStr> to comma separated String
/// ///
/// Panics if the slice is empty. /// Panics if the slice is empty.
pub fn concatenate_os_str_list(os_strs: &[impl AsRef<Path>]) -> String { pub fn pretty_format_list_of_paths(os_strs: &[impl AsRef<Path>]) -> String {
let mut iter = os_strs.iter().map(AsRef::as_ref); let mut iter = os_strs.iter().map(AsRef::as_ref);
let mut string = to_utf(iter.next().unwrap()).to_string(); // May panic let first_element = iter.next().unwrap();
let mut string = to_utf(first_element).into_owned();
for os_str in iter { for os_str in iter {
string += ", "; string += ", ";
string += &*to_utf(os_str); string += &to_utf(os_str);
} }
string string
} }
// The lifetimes here could elided but I think they help /// Display the directory name, but use "current directory" when necessary.
// comprehension in this case pub fn nice_directory_display(path: &Path) -> Cow<str> {
#[allow(clippy::needless_lifetimes)]
/// Display the directory name, but change to "current directory" when necessary.
pub fn nice_directory_display<'a>(path: &'a Path) -> Cow<'a, str> {
if path == Path::new(".") { if path == Path::new(".") {
Cow::Borrowed("current directory") Cow::Borrowed("current directory")
} else { } else {
@ -67,7 +67,7 @@ impl Bytes {
} }
impl std::fmt::Display for Bytes { impl std::fmt::Display for Bytes {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let num = self.bytes; let num = self.bytes;
debug_assert!(num >= 0.0); debug_assert!(num >= 0.0);
if num < 1_f64 { if num < 1_f64 {

View File

@ -10,7 +10,7 @@ mod fs;
mod question; mod question;
pub use file_visibility::FileVisibilityPolicy; pub use file_visibility::FileVisibilityPolicy;
pub use formatting::{concatenate_os_str_list, nice_directory_display, strip_cur_dir, to_utf, Bytes}; pub use formatting::{nice_directory_display, pretty_format_list_of_paths, strip_cur_dir, to_utf, Bytes};
pub use fs::{ pub use fs::{
cd_into_same_dir_as, clear_path, create_dir_if_non_existent, dir_is_empty, is_symlink, try_infer_extension, cd_into_same_dir_as, clear_path, create_dir_if_non_existent, dir_is_empty, is_symlink, try_infer_extension,
}; };