Reorganizing src/utils, by renaming submodules

And moving formatting stuff out of fs.rs
This commit is contained in:
João M. Bezerra 2021-11-10 09:51:26 -03:00
parent 7a4dcb2074
commit d27e259b26
5 changed files with 65 additions and 57 deletions

View File

@ -22,7 +22,7 @@ use crate::{
info,
list::{self, ListOptions},
utils::{
self, concatenate_list_of_os_str, dir_is_empty, nice_directory_display, to_utf, try_infer_extension,
self, concatenate_os_str_list, dir_is_empty, nice_directory_display, to_utf, try_infer_extension,
user_wants_to_continue_decompressing,
},
warning, Opts, QuestionPolicy, Subcommand,
@ -189,7 +189,7 @@ pub fn run(args: Opts, question_policy: QuestionPolicy) -> crate::Result<()> {
let error = FinalError::with_title("Cannot decompress files without extensions")
.detail(format!(
"Files without supported extensions: {}",
concatenate_list_of_os_str(&files_missing_format)
concatenate_os_str_list(&files_missing_format)
))
.detail("Decompression formats are detected automatically by the file extension")
.hint("Provide a file with a supported extension:")

View File

@ -1,4 +1,51 @@
use std::cmp;
use std::{
borrow::Cow,
cmp,
ffi::OsStr,
path::{Component, Path},
};
/// Converts an OsStr to utf8 with custom formatting.
///
/// This is different from [`Path::display`].
///
/// See for a comparison.
pub fn to_utf(os_str: impl AsRef<OsStr>) -> String {
let text = format!("{:?}", os_str.as_ref());
text.trim_matches('"').to_string()
}
/// Removes the current dir from the beginning of a path
/// normally used for presentation sake.
/// If this function fails, it will return source path as a PathBuf.
pub fn strip_cur_dir(source_path: &Path) -> &Path {
source_path.strip_prefix(Component::CurDir).unwrap_or(source_path)
}
/// Converts a slice of AsRef<OsStr> to comma separated String
///
/// Panics if the slice is empty.
pub fn concatenate_os_str_list(os_strs: &[impl AsRef<OsStr>]) -> String {
let mut iter = os_strs.iter().map(AsRef::as_ref);
let mut string = to_utf(iter.next().unwrap()); // May panic
for os_str in iter {
string += ", ";
string += &to_utf(os_str);
}
string
}
/// Display the directory name, but change to "current directory" when necessary.
pub fn nice_directory_display(os_str: impl AsRef<OsStr>) -> Cow<'static, str> {
if os_str.as_ref() == "." {
Cow::Borrowed("current directory")
} else {
let text = to_utf(os_str);
Cow::Owned(format!("'{}'", text))
}
}
/// Struct useful to printing bytes as kB, MB, GB, etc.
pub struct Bytes {

View File

@ -1,26 +1,25 @@
//! Random filesystem-related stuff used on ouch.
//! Filesystem utility functions.
use std::{
borrow::Cow,
env,
ffi::OsStr,
fs::ReadDir,
io::Read,
path::{Component, Path, PathBuf},
path::{Path, PathBuf},
};
use fs_err as fs;
use super::to_utf;
use crate::{extension::Extension, info};
/// Checks given path points to an empty directory.
/// Checks if given path points to an empty directory.
pub fn dir_is_empty(dir_path: &Path) -> bool {
let is_empty = |mut rd: ReadDir| rd.next().is_none();
dir_path.read_dir().map(is_empty).unwrap_or_default()
}
/// Creates the dir if non existent.
/// Creates a directory at the path, if there is nothing there.
pub fn create_dir_if_non_existent(path: &Path) -> crate::Result<()> {
if !path.exists() {
fs::create_dir_all(path)?;
@ -29,13 +28,6 @@ pub fn create_dir_if_non_existent(path: &Path) -> crate::Result<()> {
Ok(())
}
/// Removes the current dir from the beginning of a path
/// normally used for presentation sake.
/// If this function fails, it will return source path as a PathBuf.
pub fn strip_cur_dir(source_path: &Path) -> &Path {
source_path.strip_prefix(Component::CurDir).unwrap_or(source_path)
}
/// Returns current directory, but before change the process' directory to the
/// one that contains the file pointed to by `filename`.
pub fn cd_into_same_dir_as(filename: &Path) -> crate::Result<PathBuf> {
@ -47,41 +39,6 @@ pub fn cd_into_same_dir_as(filename: &Path) -> crate::Result<PathBuf> {
Ok(previous_location)
}
/// Converts an OsStr to utf8 with custom formatting.
///
/// This is different from [`Path::display`].
///
/// See for a comparison.
pub fn to_utf(os_str: impl AsRef<OsStr>) -> String {
let text = format!("{:?}", os_str.as_ref());
text.trim_matches('"').to_string()
}
/// Converts a slice of AsRef<OsStr> to comma separated String
///
/// Panics if the slice is empty.
pub fn concatenate_list_of_os_str(os_strs: &[impl AsRef<OsStr>]) -> String {
let mut iter = os_strs.iter().map(AsRef::as_ref);
let mut string = to_utf(iter.next().unwrap()); // May panic
for os_str in iter {
string += ", ";
string += &to_utf(os_str);
}
string
}
/// Display the directory name, but change to "current directory" when necessary.
pub fn nice_directory_display(os_str: impl AsRef<OsStr>) -> Cow<'static, str> {
if os_str.as_ref() == "." {
Cow::Borrowed("current directory")
} else {
let text = to_utf(os_str);
Cow::Owned(format!("'{}'", text))
}
}
/// Try to detect the file extension by looking for known magic strings
/// Source: https://en.wikipedia.org/wiki/List_of_file_signatures
pub fn try_infer_extension(path: &Path) -> Option<Extension> {

View File

@ -1,9 +1,11 @@
//! Random filesystem-related stuff used on ouch.
//! Random and miscellaneous utils used in ouch.
mod bytes;
mod formatting;
mod fs;
mod question_policy;
mod question;
pub use bytes::Bytes;
pub use fs::*;
pub use question_policy::*;
pub use formatting::{concatenate_os_str_list, nice_directory_display, strip_cur_dir, to_utf, Bytes};
pub use fs::{cd_into_same_dir_as, colors, create_dir_if_non_existent, dir_is_empty, try_infer_extension};
pub use question::{
create_or_ask_overwrite, user_wants_to_continue_decompressing, user_wants_to_overwrite, QuestionPolicy,
};

View File

@ -1,3 +1,5 @@
//! Utils related to asking [Y/n] questions to the user.
use std::path::Path;
use fs_err as fs;