mirror of
https://github.com/ouch-org/ouch.git
synced 2025-06-07 12:05:46 +00:00
Merge branch 'main' into feat/add_ls_alias
This commit is contained in:
commit
a2c894d935
4
build.rs
4
build.rs
@ -27,7 +27,7 @@ use clap::{CommandFactory, ValueEnum};
|
|||||||
use clap_complete::{generate_to, Shell};
|
use clap_complete::{generate_to, Shell};
|
||||||
use clap_mangen::Man;
|
use clap_mangen::Man;
|
||||||
|
|
||||||
include!("src/opts.rs");
|
include!("src/cli/args.rs");
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
println!("cargo:rerun-if-env-changed=OUCH_ARTIFACTS_FOLDER");
|
println!("cargo:rerun-if-env-changed=OUCH_ARTIFACTS_FOLDER");
|
||||||
@ -35,7 +35,7 @@ fn main() {
|
|||||||
if let Some(dir) = env::var_os("OUCH_ARTIFACTS_FOLDER") {
|
if let Some(dir) = env::var_os("OUCH_ARTIFACTS_FOLDER") {
|
||||||
let out = &Path::new(&dir);
|
let out = &Path::new(&dir);
|
||||||
create_dir_all(out).unwrap();
|
create_dir_all(out).unwrap();
|
||||||
let cmd = &mut Opts::command();
|
let cmd = &mut CliArgs::command();
|
||||||
|
|
||||||
Man::new(cmd.clone())
|
Man::new(cmd.clone())
|
||||||
.render(&mut File::create(out.join("ouch.1")).unwrap())
|
.render(&mut File::create(out.join("ouch.1")).unwrap())
|
||||||
|
229
src/check.rs
Normal file
229
src/check.rs
Normal file
@ -0,0 +1,229 @@
|
|||||||
|
//! Checks for errors.
|
||||||
|
|
||||||
|
#![warn(missing_docs)]
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
ffi::OsString,
|
||||||
|
ops::ControlFlow,
|
||||||
|
path::{Path, PathBuf},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
error::FinalError,
|
||||||
|
extension::{build_archive_file_suggestion, Extension},
|
||||||
|
info,
|
||||||
|
utils::{pretty_format_list_of_paths, try_infer_extension, user_wants_to_continue, EscapedPathDisplay},
|
||||||
|
warning, QuestionAction, QuestionPolicy, Result,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Check, for each file, if the mime type matches the detected extensions.
|
||||||
|
///
|
||||||
|
/// In case the file doesn't has any extensions, try to infer the format.
|
||||||
|
///
|
||||||
|
/// TODO: maybe the name of this should be "magic numbers" or "file signature",
|
||||||
|
/// and not MIME.
|
||||||
|
pub fn check_mime_type(
|
||||||
|
files: &[PathBuf],
|
||||||
|
formats: &mut [Vec<Extension>],
|
||||||
|
question_policy: QuestionPolicy,
|
||||||
|
) -> Result<ControlFlow<()>> {
|
||||||
|
for (path, format) in files.iter().zip(formats.iter_mut()) {
|
||||||
|
if format.is_empty() {
|
||||||
|
// File with no extension
|
||||||
|
// Try to detect it automatically and prompt the user about it
|
||||||
|
if let Some(detected_format) = try_infer_extension(path) {
|
||||||
|
// Inferring the file extension can have unpredicted consequences (e.g. the user just
|
||||||
|
// mistyped, ...) which we should always inform the user about.
|
||||||
|
info!(
|
||||||
|
accessible,
|
||||||
|
"Detected file: `{}` extension as `{}`",
|
||||||
|
path.display(),
|
||||||
|
detected_format
|
||||||
|
);
|
||||||
|
if user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
|
||||||
|
format.push(detected_format);
|
||||||
|
} else {
|
||||||
|
return Ok(ControlFlow::Break(()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if let Some(detected_format) = try_infer_extension(path) {
|
||||||
|
// File ending with extension
|
||||||
|
// Try to detect the extension and warn the user if it differs from the written one
|
||||||
|
let outer_ext = format.iter().next_back().unwrap();
|
||||||
|
if !outer_ext
|
||||||
|
.compression_formats
|
||||||
|
.ends_with(detected_format.compression_formats)
|
||||||
|
{
|
||||||
|
warning!(
|
||||||
|
"The file extension: `{}` differ from the detected extension: `{}`",
|
||||||
|
outer_ext,
|
||||||
|
detected_format
|
||||||
|
);
|
||||||
|
if !user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
|
||||||
|
return Ok(ControlFlow::Break(()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// NOTE: If this actually produces no false positives, we can upgrade it in the future
|
||||||
|
// to a warning and ask the user if he wants to continue decompressing.
|
||||||
|
info!(accessible, "Could not detect the extension of `{}`", path.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(ControlFlow::Continue(()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// In the context of listing archives, this function checks if `ouch` was told to list
|
||||||
|
/// the contents of a compressed file that is not an archive
|
||||||
|
pub fn check_for_non_archive_formats(files: &[PathBuf], formats: &[Vec<Extension>]) -> Result<()> {
|
||||||
|
let mut not_archives = files
|
||||||
|
.iter()
|
||||||
|
.zip(formats)
|
||||||
|
.filter(|(_, formats)| !formats.first().map(Extension::is_archive).unwrap_or(false))
|
||||||
|
.map(|(path, _)| path)
|
||||||
|
.peekable();
|
||||||
|
|
||||||
|
if not_archives.peek().is_some() {
|
||||||
|
let not_archives: Vec<_> = not_archives.collect();
|
||||||
|
let error = FinalError::with_title("Cannot list archive contents")
|
||||||
|
.detail("Only archives can have their contents listed")
|
||||||
|
.detail(format!(
|
||||||
|
"Files are not archives: {}",
|
||||||
|
pretty_format_list_of_paths(¬_archives)
|
||||||
|
));
|
||||||
|
|
||||||
|
return Err(error.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show error if archive format is not the first format in the chain.
|
||||||
|
pub fn check_archive_formats_position(formats: &[Extension], output_path: &Path) -> Result<()> {
|
||||||
|
if let Some(format) = formats.iter().skip(1).find(|format| format.is_archive()) {
|
||||||
|
let error = FinalError::with_title(format!(
|
||||||
|
"Cannot compress to '{}'.",
|
||||||
|
EscapedPathDisplay::new(output_path)
|
||||||
|
))
|
||||||
|
.detail(format!("Found the format '{format}' in an incorrect position."))
|
||||||
|
.detail(format!(
|
||||||
|
"'{format}' can only be used at the start of the file extension."
|
||||||
|
))
|
||||||
|
.hint(format!(
|
||||||
|
"If you wish to compress multiple files, start the extension with '{format}'."
|
||||||
|
))
|
||||||
|
.hint(format!(
|
||||||
|
"Otherwise, remove the last '{}' from '{}'.",
|
||||||
|
format,
|
||||||
|
EscapedPathDisplay::new(output_path)
|
||||||
|
));
|
||||||
|
|
||||||
|
return Err(error.into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if all provided files have formats to decompress.
|
||||||
|
pub fn check_missing_formats_when_decompressing(files: &[PathBuf], formats: &[Vec<Extension>]) -> Result<()> {
|
||||||
|
let files_missing_format: Vec<PathBuf> = files
|
||||||
|
.iter()
|
||||||
|
.zip(formats)
|
||||||
|
.filter(|(_, format)| format.is_empty())
|
||||||
|
.map(|(input_path, _)| PathBuf::from(input_path))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
if let Some(path) = files_missing_format.first() {
|
||||||
|
let error = FinalError::with_title("Cannot decompress files without extensions")
|
||||||
|
.detail(format!(
|
||||||
|
"Files without supported extensions: {}",
|
||||||
|
pretty_format_list_of_paths(&files_missing_format)
|
||||||
|
))
|
||||||
|
.detail("Decompression formats are detected automatically by the file extension")
|
||||||
|
.hint("Provide a file with a supported extension:")
|
||||||
|
.hint(" ouch decompress example.tar.gz")
|
||||||
|
.hint("")
|
||||||
|
.hint("Or overwrite this option with the '--format' flag:")
|
||||||
|
.hint(format!(
|
||||||
|
" ouch decompress {} --format tar.gz",
|
||||||
|
EscapedPathDisplay::new(path),
|
||||||
|
));
|
||||||
|
|
||||||
|
return Err(error.into());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if there is a first format when compressing, and returns it.
|
||||||
|
pub fn check_first_format_when_compressing<'a>(formats: &'a [Extension], output_path: &Path) -> Result<&'a Extension> {
|
||||||
|
formats.first().ok_or_else(|| {
|
||||||
|
let output_path = EscapedPathDisplay::new(output_path);
|
||||||
|
FinalError::with_title(format!("Cannot compress to '{output_path}'."))
|
||||||
|
.detail("You shall supply the compression format")
|
||||||
|
.hint("Try adding supported extensions (see --help):")
|
||||||
|
.hint(format!(" ouch compress <FILES>... {output_path}.tar.gz"))
|
||||||
|
.hint(format!(" ouch compress <FILES>... {output_path}.zip"))
|
||||||
|
.hint("")
|
||||||
|
.hint("Alternatively, you can overwrite this option by using the '--format' flag:")
|
||||||
|
.hint(format!(" ouch compress <FILES>... {output_path} --format tar.gz"))
|
||||||
|
.into()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if compression is invalid because an archive format is necessary.
|
||||||
|
///
|
||||||
|
/// Non-archive formats don't support multiple file compression or folder compression.
|
||||||
|
pub fn check_invalid_compression_with_non_archive_format(
|
||||||
|
formats: &[Extension],
|
||||||
|
output_path: &Path,
|
||||||
|
files: &[PathBuf],
|
||||||
|
formats_from_flag: Option<&OsString>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let first_format = check_first_format_when_compressing(formats, output_path)?;
|
||||||
|
|
||||||
|
let is_some_input_a_folder = files.iter().any(|path| path.is_dir());
|
||||||
|
let is_multiple_inputs = files.len() > 1;
|
||||||
|
|
||||||
|
// If format is archive, nothing to check
|
||||||
|
// If there's no folder or multiple inputs, non-archive formats can handle it
|
||||||
|
if first_format.is_archive() || !is_some_input_a_folder && !is_multiple_inputs {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let first_detail_message = if is_multiple_inputs {
|
||||||
|
"You are trying to compress multiple files."
|
||||||
|
} else {
|
||||||
|
"You are trying to compress a folder."
|
||||||
|
};
|
||||||
|
|
||||||
|
let (from_hint, to_hint) = if let Some(formats) = formats_from_flag {
|
||||||
|
let formats = formats.to_string_lossy();
|
||||||
|
(
|
||||||
|
format!("From: --format {formats}"),
|
||||||
|
format!("To: --format tar.{formats}"),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// This piece of code creates a suggestion for compressing multiple files
|
||||||
|
// It says:
|
||||||
|
// Change from file.bz.xz
|
||||||
|
// To file.tar.bz.xz
|
||||||
|
let suggested_output_path = build_archive_file_suggestion(output_path, ".tar")
|
||||||
|
.expect("output path should contain a compression format");
|
||||||
|
|
||||||
|
(
|
||||||
|
format!("From: {}", EscapedPathDisplay::new(output_path)),
|
||||||
|
format!("To: {suggested_output_path}"),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let output_path = EscapedPathDisplay::new(output_path);
|
||||||
|
|
||||||
|
let error = FinalError::with_title(format!("Cannot compress to '{output_path}'."))
|
||||||
|
.detail(first_detail_message)
|
||||||
|
.detail(format!(
|
||||||
|
"The compression format '{first_format}' does not accept multiple files.",
|
||||||
|
))
|
||||||
|
.detail("Formats that bundle files into an archive are tar and zip.")
|
||||||
|
.hint(format!("Try inserting 'tar.' or 'zip.' before '{first_format}'."))
|
||||||
|
.hint(from_hint)
|
||||||
|
.hint(to_hint);
|
||||||
|
|
||||||
|
Err(error.into())
|
||||||
|
}
|
@ -5,14 +5,14 @@ use clap::{Parser, ValueHint};
|
|||||||
// Ouch command line options (docstrings below are part of --help)
|
// Ouch command line options (docstrings below are part of --help)
|
||||||
/// A command-line utility for easily compressing and decompressing files and directories.
|
/// A command-line utility for easily compressing and decompressing files and directories.
|
||||||
///
|
///
|
||||||
/// Supported formats: tar, zip, bz/bz2, gz, lz4, xz/lzma, zst.
|
/// Supported formats: tar, zip, gz, xz/lzma, bz/bz2, lz4, sz, zst.
|
||||||
///
|
///
|
||||||
/// Repository: https://github.com/ouch-org/ouch
|
/// Repository: https://github.com/ouch-org/ouch
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
#[command(about, version)]
|
#[command(about, version)]
|
||||||
// Disable rustdoc::bare_urls because rustdoc parses URLs differently than Clap
|
// Disable rustdoc::bare_urls because rustdoc parses URLs differently than Clap
|
||||||
#[allow(rustdoc::bare_urls)]
|
#[allow(rustdoc::bare_urls)]
|
||||||
pub struct Opts {
|
pub struct CliArgs {
|
||||||
/// Skip [Y/n] questions positively
|
/// Skip [Y/n] questions positively
|
||||||
#[arg(short, long, conflicts_with = "no", global = true)]
|
#[arg(short, long, conflicts_with = "no", global = true)]
|
||||||
pub yes: bool,
|
pub yes: bool,
|
@ -1,4 +1,6 @@
|
|||||||
//! CLI related functions, uses the clap argparsing definitions from `opts.rs`.
|
//! CLI related functions, uses the clap argparsing definitions from `args.rs`.
|
||||||
|
|
||||||
|
mod args;
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
io,
|
io,
|
||||||
@ -9,25 +11,26 @@ use std::{
|
|||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use fs_err as fs;
|
use fs_err as fs;
|
||||||
|
|
||||||
use crate::{accessible::set_accessible, utils::FileVisibilityPolicy, Opts, QuestionPolicy, Subcommand};
|
pub use self::args::{CliArgs, Subcommand};
|
||||||
|
use crate::{accessible::set_accessible, utils::FileVisibilityPolicy, QuestionPolicy};
|
||||||
|
|
||||||
impl Opts {
|
impl CliArgs {
|
||||||
/// A helper method that calls `clap::Parser::parse`.
|
/// A helper method that calls `clap::Parser::parse`.
|
||||||
///
|
///
|
||||||
/// And:
|
/// And:
|
||||||
/// 1. Make paths absolute.
|
/// 1. Make paths absolute.
|
||||||
/// 2. Checks the QuestionPolicy.
|
/// 2. Checks the QuestionPolicy.
|
||||||
pub fn parse_args() -> crate::Result<(Self, QuestionPolicy, FileVisibilityPolicy)> {
|
pub fn parse_args() -> crate::Result<(Self, QuestionPolicy, FileVisibilityPolicy)> {
|
||||||
let mut opts = Self::parse();
|
let mut args = Self::parse();
|
||||||
|
|
||||||
set_accessible(opts.accessible);
|
set_accessible(args.accessible);
|
||||||
|
|
||||||
let (Subcommand::Compress { files, .. }
|
let (Subcommand::Compress { files, .. }
|
||||||
| Subcommand::Decompress { files, .. }
|
| Subcommand::Decompress { files, .. }
|
||||||
| Subcommand::List { archives: files, .. }) = &mut opts.cmd;
|
| Subcommand::List { archives: files, .. }) = &mut args.cmd;
|
||||||
*files = canonicalize_files(files)?;
|
*files = canonicalize_files(files)?;
|
||||||
|
|
||||||
let skip_questions_positively = match (opts.yes, opts.no) {
|
let skip_questions_positively = match (args.yes, args.no) {
|
||||||
(false, false) => QuestionPolicy::Ask,
|
(false, false) => QuestionPolicy::Ask,
|
||||||
(true, false) => QuestionPolicy::AlwaysYes,
|
(true, false) => QuestionPolicy::AlwaysYes,
|
||||||
(false, true) => QuestionPolicy::AlwaysNo,
|
(false, true) => QuestionPolicy::AlwaysNo,
|
||||||
@ -35,12 +38,12 @@ impl Opts {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let file_visibility_policy = FileVisibilityPolicy::new()
|
let file_visibility_policy = FileVisibilityPolicy::new()
|
||||||
.read_git_exclude(opts.gitignore)
|
.read_git_exclude(args.gitignore)
|
||||||
.read_ignore(opts.gitignore)
|
.read_ignore(args.gitignore)
|
||||||
.read_git_ignore(opts.gitignore)
|
.read_git_ignore(args.gitignore)
|
||||||
.read_hidden(opts.hidden);
|
.read_hidden(args.hidden);
|
||||||
|
|
||||||
Ok((opts, skip_questions_positively, file_visibility_policy))
|
Ok((args, skip_questions_positively, file_visibility_policy))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -4,25 +4,21 @@ mod compress;
|
|||||||
mod decompress;
|
mod decompress;
|
||||||
mod list;
|
mod list;
|
||||||
|
|
||||||
use std::{
|
use std::{ops::ControlFlow, path::PathBuf};
|
||||||
ops::ControlFlow,
|
|
||||||
path::{Path, PathBuf},
|
|
||||||
};
|
|
||||||
|
|
||||||
use rayon::prelude::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
|
use rayon::prelude::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
|
||||||
use utils::colors;
|
use utils::colors;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
check,
|
||||||
|
cli::Subcommand,
|
||||||
commands::{compress::compress_files, decompress::decompress_file, list::list_archive_contents},
|
commands::{compress::compress_files, decompress::decompress_file, list::list_archive_contents},
|
||||||
error::{Error, FinalError},
|
error::{Error, FinalError},
|
||||||
extension::{self, flatten_compression_formats, parse_format, Extension, SUPPORTED_EXTENSIONS},
|
extension::{self, parse_format},
|
||||||
info,
|
info,
|
||||||
list::ListOptions,
|
list::ListOptions,
|
||||||
utils::{
|
utils::{self, to_utf, EscapedPathDisplay, FileVisibilityPolicy},
|
||||||
self, pretty_format_list_of_paths, to_utf, try_infer_extension, user_wants_to_continue, EscapedPathDisplay,
|
warning, CliArgs, QuestionPolicy,
|
||||||
FileVisibilityPolicy,
|
|
||||||
},
|
|
||||||
warning, Opts, QuestionAction, QuestionPolicy, Subcommand,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Warn the user that (de)compressing this .zip archive might freeze their system.
|
/// Warn the user that (de)compressing this .zip archive might freeze their system.
|
||||||
@ -35,71 +31,12 @@ fn warn_user_about_loading_zip_in_memory() {
|
|||||||
warning!("{}", ZIP_IN_MEMORY_LIMITATION_WARNING);
|
warning!("{}", ZIP_IN_MEMORY_LIMITATION_WARNING);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds a suggested output file in scenarios where the user tried to compress
|
|
||||||
/// a folder into a non-archive compression format, for error message purposes
|
|
||||||
///
|
|
||||||
/// E.g.: `build_suggestion("file.bz.xz", ".tar")` results in `Some("file.tar.bz.xz")`
|
|
||||||
fn build_archive_file_suggestion(path: &Path, suggested_extension: &str) -> Option<String> {
|
|
||||||
let path = path.to_string_lossy();
|
|
||||||
let mut rest = &*path;
|
|
||||||
let mut position_to_insert = 0;
|
|
||||||
|
|
||||||
// Walk through the path to find the first supported compression extension
|
|
||||||
while let Some(pos) = rest.find('.') {
|
|
||||||
// Use just the text located after the dot we found
|
|
||||||
rest = &rest[pos + 1..];
|
|
||||||
position_to_insert += pos + 1;
|
|
||||||
|
|
||||||
// If the string contains more chained extensions, clip to the immediate one
|
|
||||||
let maybe_extension = {
|
|
||||||
let idx = rest.find('.').unwrap_or(rest.len());
|
|
||||||
&rest[..idx]
|
|
||||||
};
|
|
||||||
|
|
||||||
// If the extension we got is a supported extension, generate the suggestion
|
|
||||||
// at the position we found
|
|
||||||
if SUPPORTED_EXTENSIONS.contains(&maybe_extension) {
|
|
||||||
let mut path = path.to_string();
|
|
||||||
path.insert_str(position_to_insert - 1, suggested_extension);
|
|
||||||
|
|
||||||
return Some(path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
/// In the context of listing archives, this function checks if `ouch` was told to list
|
|
||||||
/// the contents of a compressed file that is not an archive
|
|
||||||
fn check_for_non_archive_formats(files: &[PathBuf], formats: &[Vec<Extension>]) -> crate::Result<()> {
|
|
||||||
let mut not_archives = files
|
|
||||||
.iter()
|
|
||||||
.zip(formats)
|
|
||||||
.filter(|(_, formats)| !formats.first().map(Extension::is_archive).unwrap_or(false))
|
|
||||||
.map(|(path, _)| path)
|
|
||||||
.peekable();
|
|
||||||
|
|
||||||
if not_archives.peek().is_some() {
|
|
||||||
let not_archives: Vec<_> = not_archives.collect();
|
|
||||||
let error = FinalError::with_title("Cannot list archive contents")
|
|
||||||
.detail("Only archives can have their contents listed")
|
|
||||||
.detail(format!(
|
|
||||||
"Files are not archives: {}",
|
|
||||||
pretty_format_list_of_paths(¬_archives)
|
|
||||||
));
|
|
||||||
|
|
||||||
return Err(error.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This function checks what command needs to be run and performs A LOT of ahead-of-time checks
|
/// This function checks what command needs to be run and performs A LOT of ahead-of-time checks
|
||||||
/// to assume everything is OK.
|
/// to assume everything is OK.
|
||||||
///
|
///
|
||||||
/// There are a lot of custom errors to give enough error description and explanation.
|
/// There are a lot of custom errors to give enough error description and explanation.
|
||||||
pub fn run(
|
pub fn run(
|
||||||
args: Opts,
|
args: CliArgs,
|
||||||
question_policy: QuestionPolicy,
|
question_policy: QuestionPolicy,
|
||||||
file_visibility_policy: FileVisibilityPolicy,
|
file_visibility_policy: FileVisibilityPolicy,
|
||||||
) -> crate::Result<()> {
|
) -> crate::Result<()> {
|
||||||
@ -122,84 +59,13 @@ pub fn run(
|
|||||||
None => (None, extension::extensions_from_path(&output_path)),
|
None => (None, extension::extensions_from_path(&output_path)),
|
||||||
};
|
};
|
||||||
|
|
||||||
let first_format = formats.first().ok_or_else(|| {
|
check::check_invalid_compression_with_non_archive_format(
|
||||||
let output_path = EscapedPathDisplay::new(&output_path);
|
&formats,
|
||||||
FinalError::with_title(format!("Cannot compress to '{output_path}'."))
|
&output_path,
|
||||||
.detail("You shall supply the compression format")
|
&files,
|
||||||
.hint("Try adding supported extensions (see --help):")
|
formats_from_flag.as_ref(),
|
||||||
.hint(format!(" ouch compress <FILES>... {output_path}.tar.gz"))
|
)?;
|
||||||
.hint(format!(" ouch compress <FILES>... {output_path}.zip"))
|
check::check_archive_formats_position(&formats, &output_path)?;
|
||||||
.hint("")
|
|
||||||
.hint("Alternatively, you can overwrite this option by using the '--format' flag:")
|
|
||||||
.hint(format!(" ouch compress <FILES>... {output_path} --format tar.gz"))
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let is_some_input_a_folder = files.iter().any(|path| path.is_dir());
|
|
||||||
let is_multiple_inputs = files.len() > 1;
|
|
||||||
|
|
||||||
// If first format is not archive, can't compress folder, or multiple files
|
|
||||||
// Index safety: empty formats should be checked above.
|
|
||||||
if !first_format.is_archive() && (is_some_input_a_folder || is_multiple_inputs) {
|
|
||||||
let first_detail_message = if is_multiple_inputs {
|
|
||||||
"You are trying to compress multiple files."
|
|
||||||
} else {
|
|
||||||
"You are trying to compress a folder."
|
|
||||||
};
|
|
||||||
|
|
||||||
let (from_hint, to_hint) = if let Some(formats) = formats_from_flag {
|
|
||||||
let formats = formats.to_string_lossy();
|
|
||||||
(
|
|
||||||
format!("From: --format {formats}"),
|
|
||||||
format!("To: --format tar.{formats}"),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
// This piece of code creates a suggestion for compressing multiple files
|
|
||||||
// It says:
|
|
||||||
// Change from file.bz.xz
|
|
||||||
// To file.tar.bz.xz
|
|
||||||
let suggested_output_path = build_archive_file_suggestion(&output_path, ".tar")
|
|
||||||
.expect("output path should contain a compression format");
|
|
||||||
|
|
||||||
(
|
|
||||||
format!("From: {}", EscapedPathDisplay::new(&output_path)),
|
|
||||||
format!("To: {suggested_output_path}"),
|
|
||||||
)
|
|
||||||
};
|
|
||||||
let output_path = EscapedPathDisplay::new(&output_path);
|
|
||||||
|
|
||||||
let error = FinalError::with_title(format!("Cannot compress to '{output_path}'."))
|
|
||||||
.detail(first_detail_message)
|
|
||||||
.detail(format!(
|
|
||||||
"The compression format '{first_format}' does not accept multiple files.",
|
|
||||||
))
|
|
||||||
.detail("Formats that bundle files into an archive are tar and zip.")
|
|
||||||
.hint(format!("Try inserting 'tar.' or 'zip.' before '{first_format}'."))
|
|
||||||
.hint(from_hint)
|
|
||||||
.hint(to_hint);
|
|
||||||
|
|
||||||
return Err(error.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(format) = formats.iter().skip(1).find(|format| format.is_archive()) {
|
|
||||||
let error = FinalError::with_title(format!(
|
|
||||||
"Cannot compress to '{}'.",
|
|
||||||
EscapedPathDisplay::new(&output_path)
|
|
||||||
))
|
|
||||||
.detail(format!("Found the format '{format}' in an incorrect position."))
|
|
||||||
.detail(format!(
|
|
||||||
"'{format}' can only be used at the start of the file extension."
|
|
||||||
))
|
|
||||||
.hint(format!(
|
|
||||||
"If you wish to compress multiple files, start the extension with '{format}'."
|
|
||||||
))
|
|
||||||
.hint(format!(
|
|
||||||
"Otherwise, remove the last '{}' from '{}'.",
|
|
||||||
format,
|
|
||||||
EscapedPathDisplay::new(&output_path)
|
|
||||||
));
|
|
||||||
|
|
||||||
return Err(error.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
let output_file = match utils::ask_to_create_file(&output_path, question_policy)? {
|
let output_file = match utils::ask_to_create_file(&output_path, question_policy)? {
|
||||||
Some(writer) => writer,
|
Some(writer) => writer,
|
||||||
@ -265,35 +131,11 @@ pub fn run(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let ControlFlow::Break(_) = check_mime_type(&files, &mut formats, question_policy)? {
|
if let ControlFlow::Break(_) = check::check_mime_type(&files, &mut formats, question_policy)? {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let files_missing_format: Vec<PathBuf> = files
|
check::check_missing_formats_when_decompressing(&files, &formats)?;
|
||||||
.iter()
|
|
||||||
.zip(&formats)
|
|
||||||
.filter(|(_, formats)| formats.is_empty())
|
|
||||||
.map(|(input_path, _)| PathBuf::from(input_path))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
if let Some(path) = files_missing_format.first() {
|
|
||||||
let error = FinalError::with_title("Cannot decompress files without extensions")
|
|
||||||
.detail(format!(
|
|
||||||
"Files without supported extensions: {}",
|
|
||||||
pretty_format_list_of_paths(&files_missing_format)
|
|
||||||
))
|
|
||||||
.detail("Decompression formats are detected automatically by the file extension")
|
|
||||||
.hint("Provide a file with a supported extension:")
|
|
||||||
.hint(" ouch decompress example.tar.gz")
|
|
||||||
.hint("")
|
|
||||||
.hint("Or overwrite this option with the '--format' flag:")
|
|
||||||
.hint(format!(
|
|
||||||
" ouch decompress {} --format tar.gz",
|
|
||||||
EscapedPathDisplay::new(path),
|
|
||||||
));
|
|
||||||
|
|
||||||
return Err(error.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
// The directory that will contain the output files
|
// The directory that will contain the output files
|
||||||
// We default to the current directory if the user didn't specify an output directory with --dir
|
// We default to the current directory if the user didn't specify an output directory with --dir
|
||||||
@ -334,13 +176,13 @@ pub fn run(
|
|||||||
formats.push(file_formats);
|
formats.push(file_formats);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let ControlFlow::Break(_) = check_mime_type(&files, &mut formats, question_policy)? {
|
if let ControlFlow::Break(_) = check::check_mime_type(&files, &mut formats, question_policy)? {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure we were not told to list the content of a non-archive compressed file
|
// Ensure we were not told to list the content of a non-archive compressed file
|
||||||
check_for_non_archive_formats(&files, &formats)?;
|
check::check_for_non_archive_formats(&files, &formats)?;
|
||||||
|
|
||||||
let list_options = ListOptions { tree };
|
let list_options = ListOptions { tree };
|
||||||
|
|
||||||
@ -348,88 +190,10 @@ pub fn run(
|
|||||||
if i > 0 {
|
if i > 0 {
|
||||||
println!();
|
println!();
|
||||||
}
|
}
|
||||||
let formats = flatten_compression_formats(&formats);
|
let formats = extension::flatten_compression_formats(&formats);
|
||||||
list_archive_contents(archive_path, formats, list_options, question_policy)?;
|
list_archive_contents(archive_path, formats, list_options, question_policy)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_mime_type(
|
|
||||||
files: &[PathBuf],
|
|
||||||
formats: &mut [Vec<Extension>],
|
|
||||||
question_policy: QuestionPolicy,
|
|
||||||
) -> crate::Result<ControlFlow<()>> {
|
|
||||||
for (path, format) in files.iter().zip(formats.iter_mut()) {
|
|
||||||
if format.is_empty() {
|
|
||||||
// File with no extension
|
|
||||||
// Try to detect it automatically and prompt the user about it
|
|
||||||
if let Some(detected_format) = try_infer_extension(path) {
|
|
||||||
// Inferring the file extension can have unpredicted consequences (e.g. the user just
|
|
||||||
// mistyped, ...) which we should always inform the user about.
|
|
||||||
info!(
|
|
||||||
accessible,
|
|
||||||
"Detected file: `{}` extension as `{}`",
|
|
||||||
path.display(),
|
|
||||||
detected_format
|
|
||||||
);
|
|
||||||
if user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
|
|
||||||
format.push(detected_format);
|
|
||||||
} else {
|
|
||||||
return Ok(ControlFlow::Break(()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if let Some(detected_format) = try_infer_extension(path) {
|
|
||||||
// File ending with extension
|
|
||||||
// Try to detect the extension and warn the user if it differs from the written one
|
|
||||||
let outer_ext = format.iter().next_back().unwrap();
|
|
||||||
if !outer_ext
|
|
||||||
.compression_formats
|
|
||||||
.ends_with(detected_format.compression_formats)
|
|
||||||
{
|
|
||||||
warning!(
|
|
||||||
"The file extension: `{}` differ from the detected extension: `{}`",
|
|
||||||
outer_ext,
|
|
||||||
detected_format
|
|
||||||
);
|
|
||||||
if !user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
|
|
||||||
return Ok(ControlFlow::Break(()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// NOTE: If this actually produces no false positives, we can upgrade it in the future
|
|
||||||
// to a warning and ask the user if he wants to continue decompressing.
|
|
||||||
info!(accessible, "Could not detect the extension of `{}`", path.display());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(ControlFlow::Continue(()))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
use super::build_archive_file_suggestion;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn builds_suggestion_correctly() {
|
|
||||||
assert_eq!(build_archive_file_suggestion(Path::new("linux.png"), ".tar"), None);
|
|
||||||
assert_eq!(
|
|
||||||
build_archive_file_suggestion(Path::new("linux.xz.gz.zst"), ".tar").unwrap(),
|
|
||||||
"linux.tar.xz.gz.zst"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
build_archive_file_suggestion(Path::new("linux.pkg.xz.gz.zst"), ".tar").unwrap(),
|
|
||||||
"linux.pkg.tar.xz.gz.zst"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
build_archive_file_suggestion(Path::new("linux.pkg.zst"), ".tar").unwrap(),
|
|
||||||
"linux.pkg.tar.zst"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
build_archive_file_suggestion(Path::new("linux.pkg.info.zst"), ".tar").unwrap(),
|
|
||||||
"linux.pkg.info.tar.zst"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -170,22 +170,6 @@ pub fn extensions_from_path(path: &Path) -> Vec<Extension> {
|
|||||||
extensions
|
extensions
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_extensions_from_path() {
|
|
||||||
use CompressionFormat::*;
|
|
||||||
let path = Path::new("bolovo.tar.gz");
|
|
||||||
|
|
||||||
let extensions: Vec<Extension> = extensions_from_path(path);
|
|
||||||
let formats: Vec<CompressionFormat> = flatten_compression_formats(&extensions);
|
|
||||||
|
|
||||||
assert_eq!(formats, vec![Tar, Gzip]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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);
|
||||||
@ -200,3 +184,76 @@ pub fn flatten_compression_formats(extensions: &[Extension]) -> Vec<CompressionF
|
|||||||
.copied()
|
.copied()
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Builds a suggested output file in scenarios where the user tried to compress
|
||||||
|
/// a folder into a non-archive compression format, for error message purposes
|
||||||
|
///
|
||||||
|
/// E.g.: `build_suggestion("file.bz.xz", ".tar")` results in `Some("file.tar.bz.xz")`
|
||||||
|
pub fn build_archive_file_suggestion(path: &Path, suggested_extension: &str) -> Option<String> {
|
||||||
|
let path = path.to_string_lossy();
|
||||||
|
let mut rest = &*path;
|
||||||
|
let mut position_to_insert = 0;
|
||||||
|
|
||||||
|
// Walk through the path to find the first supported compression extension
|
||||||
|
while let Some(pos) = rest.find('.') {
|
||||||
|
// Use just the text located after the dot we found
|
||||||
|
rest = &rest[pos + 1..];
|
||||||
|
position_to_insert += pos + 1;
|
||||||
|
|
||||||
|
// If the string contains more chained extensions, clip to the immediate one
|
||||||
|
let maybe_extension = {
|
||||||
|
let idx = rest.find('.').unwrap_or(rest.len());
|
||||||
|
&rest[..idx]
|
||||||
|
};
|
||||||
|
|
||||||
|
// If the extension we got is a supported extension, generate the suggestion
|
||||||
|
// at the position we found
|
||||||
|
if SUPPORTED_EXTENSIONS.contains(&maybe_extension) {
|
||||||
|
let mut path = path.to_string();
|
||||||
|
path.insert_str(position_to_insert - 1, suggested_extension);
|
||||||
|
|
||||||
|
return Some(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_extensions_from_path() {
|
||||||
|
use CompressionFormat::*;
|
||||||
|
let path = Path::new("bolovo.tar.gz");
|
||||||
|
|
||||||
|
let extensions: Vec<Extension> = extensions_from_path(path);
|
||||||
|
let formats: Vec<CompressionFormat> = flatten_compression_formats(&extensions);
|
||||||
|
|
||||||
|
assert_eq!(formats, vec![Tar, Gzip]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn builds_suggestion_correctly() {
|
||||||
|
assert_eq!(build_archive_file_suggestion(Path::new("linux.png"), ".tar"), None);
|
||||||
|
assert_eq!(
|
||||||
|
build_archive_file_suggestion(Path::new("linux.xz.gz.zst"), ".tar").unwrap(),
|
||||||
|
"linux.tar.xz.gz.zst"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
build_archive_file_suggestion(Path::new("linux.pkg.xz.gz.zst"), ".tar").unwrap(),
|
||||||
|
"linux.pkg.tar.xz.gz.zst"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
build_archive_file_suggestion(Path::new("linux.pkg.zst"), ".tar").unwrap(),
|
||||||
|
"linux.pkg.tar.zst"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
build_archive_file_suggestion(Path::new("linux.pkg.info.zst"), ".tar").unwrap(),
|
||||||
|
"linux.pkg.info.tar.zst"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ -3,6 +3,7 @@ pub mod macros;
|
|||||||
|
|
||||||
pub mod accessible;
|
pub mod accessible;
|
||||||
pub mod archive;
|
pub mod archive;
|
||||||
|
pub mod check;
|
||||||
pub mod cli;
|
pub mod cli;
|
||||||
pub mod commands;
|
pub mod commands;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
@ -10,14 +11,11 @@ pub mod extension;
|
|||||||
pub mod list;
|
pub mod list;
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
|
|
||||||
/// CLI argparsing definitions, using `clap`.
|
|
||||||
pub mod opts;
|
|
||||||
|
|
||||||
use std::{env, path::PathBuf};
|
use std::{env, path::PathBuf};
|
||||||
|
|
||||||
|
use cli::CliArgs;
|
||||||
use error::{Error, Result};
|
use error::{Error, Result};
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use opts::{Opts, Subcommand};
|
|
||||||
use utils::{QuestionAction, QuestionPolicy};
|
use utils::{QuestionAction, QuestionPolicy};
|
||||||
|
|
||||||
// Used in BufReader and BufWriter to perform less syscalls
|
// Used in BufReader and BufWriter to perform less syscalls
|
||||||
@ -37,6 +35,6 @@ fn main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn run() -> Result<()> {
|
fn run() -> Result<()> {
|
||||||
let (args, skip_questions_positively, file_visibility_policy) = Opts::parse_args()?;
|
let (args, skip_questions_positively, file_visibility_policy) = CliArgs::parse_args()?;
|
||||||
commands::run(args, skip_questions_positively, file_visibility_policy)
|
commands::run(args, skip_questions_positively, file_visibility_policy)
|
||||||
}
|
}
|
||||||
|
@ -62,7 +62,7 @@ pub fn strip_cur_dir(source_path: &Path) -> &Path {
|
|||||||
source_path.strip_prefix(current_dir).unwrap_or(source_path)
|
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 pretty_format_list_of_paths(os_strs: &[impl AsRef<Path>]) -> String {
|
pub fn pretty_format_list_of_paths(os_strs: &[impl AsRef<Path>]) -> String {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user