13 extension::{build_archive_file_suggestion, Extension},
15 logger::{info_accessible, warning},
16 pretty_format_list_of_paths, try_infer_extension, user_wants_to_continue, EscapedPathDisplay,
18 QuestionAction, QuestionPolicy, Result,
21 /// Check if the mime type matches the detected extensions.
23 /// In case the file doesn't has any extensions, try to infer the format.
25 /// TODO: maybe the name of this should be "magic numbers" or "file signature",
27 pub fn check_mime_type(
29 formats: &mut Vec<Extension>,
30 question_policy: QuestionPolicy,
31 ) -> Result<ControlFlow<()>> {
32 if formats.is_empty() {
33 // File with no extension
34 // Try to detect it automatically and prompt the user about it
35 if let Some(detected_format) = try_infer_extension(path) {
36 // Inferring the file extension can have unpredicted consequences (e.g. the user just
37 // mistyped, ...) which we should always inform the user about.
39 "We detected a file named `{}`, do you want to decompress it?",
43 if user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
44 formats.push(detected_format);
46 return Ok(ControlFlow::Break(()));
49 } else if let Some(detected_format) = try_infer_extension(path) {
50 // File ending with extension
51 // Try to detect the extension and warn the user if it differs from the written one
53 let outer_ext = formats.iter().next_back().unwrap();
56 .ends_with(detected_format.compression_formats)
59 "The file extension: `{}` differ from the detected extension: `{}`",
60 outer_ext, detected_format
63 if !user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
64 return Ok(ControlFlow::Break(()));
68 // NOTE: If this actually produces no false positives, we can upgrade it in the future
69 // to a warning and ask the user if he wants to continue decompressing.
70 info_accessible(format!(
71 "Failed to confirm the format of `{}` by sniffing the contents, file might be misnamed",
75 Ok(ControlFlow::Continue(()))
78 /// In the context of listing archives, this function checks if `ouch` was told to list
79 /// the contents of a compressed file that is not an archive
80 pub fn check_for_non_archive_formats(files: &[PathBuf], formats: &[Vec<Extension>]) -> Result<()> {
81 let mut not_archives = files
84 .filter(|(_, formats)| !formats.first().map(Extension::is_archive).unwrap_or(false))
85 .map(|(path, _)| path)
88 if not_archives.peek().is_some() {
89 let not_archives: Vec<_> = not_archives.collect();
90 let error = FinalError::with_title("Cannot list archive contents")
91 .detail("Only archives can have their contents listed")
93 "Files are not archives: {}",
94 pretty_format_list_of_paths(¬_archives)
97 return Err(error.into());
103 /// Show error if archive format is not the first format in the chain.
104 pub fn check_archive_formats_position(formats: &[Extension], output_path: &Path) -> Result<()> {
105 if let Some(format) = formats.iter().skip(1).find(|format| format.is_archive()) {
106 let error = FinalError::with_title(format!(
107 "Cannot compress to '{}'.",
108 EscapedPathDisplay::new(output_path)
110 .detail(format!("Found the format '{format}' in an incorrect position."))
112 "'{format}' can only be used at the start of the file extension."
115 "If you wish to compress multiple files, start the extension with '{format}'."
118 "Otherwise, remove the last '{}' from '{}'.",
120 EscapedPathDisplay::new(output_path)
123 return Err(error.into());
128 /// Check if all provided files have formats to decompress.
129 pub fn check_missing_formats_when_decompressing(files: &[PathBuf], formats: &[Vec<Extension>]) -> Result<()> {
130 let files_with_broken_extension: Vec<&PathBuf> = files
133 .filter(|(_, format)| format.is_empty())
134 .map(|(input_path, _)| input_path)
137 if files_with_broken_extension.is_empty() {
141 let (files_with_unsupported_extensions, files_missing_extension): (Vec<&PathBuf>, Vec<&PathBuf>) =
142 files_with_broken_extension
144 .partition(|path| path.extension().is_some());
146 let mut error = FinalError::with_title("Cannot decompress files");
148 if !files_with_unsupported_extensions.is_empty() {
149 error = error.detail(format!(
150 "Files with unsupported extensions: {}",
151 pretty_format_list_of_paths(&files_with_unsupported_extensions)
155 if !files_missing_extension.is_empty() {
156 error = error.detail(format!(
157 "Files with missing extensions: {}",
158 pretty_format_list_of_paths(&files_missing_extension)
162 error = error.detail("Decompression formats are detected automatically from file extension");
163 error = error.hint_all_supported_formats();
165 // If there's exactly one file, give a suggestion to use `--format`
166 if let &[path] = files_with_broken_extension.as_slice() {
169 .hint("Alternatively, you can pass an extension to the '--format' flag:")
171 " ouch decompress {} --format tar.gz",
172 EscapedPathDisplay::new(path),
179 /// Check if there is a first format when compressing, and returns it.
180 pub fn check_first_format_when_compressing<'a>(formats: &'a [Extension], output_path: &Path) -> Result<&'a Extension> {
181 formats.first().ok_or_else(|| {
182 let output_path = EscapedPathDisplay::new(output_path);
183 FinalError::with_title(format!("Cannot compress to '{output_path}'."))
184 .detail("You shall supply the compression format")
185 .hint("Try adding supported extensions (see --help):")
186 .hint(format!(" ouch compress <FILES>... {output_path}.tar.gz"))
187 .hint(format!(" ouch compress <FILES>... {output_path}.zip"))
189 .hint("Alternatively, you can overwrite this option by using the '--format' flag:")
190 .hint(format!(" ouch compress <FILES>... {output_path} --format tar.gz"))
195 /// Check if compression is invalid because an archive format is necessary.
197 /// Non-archive formats don't support multiple file compression or folder compression.
198 pub fn check_invalid_compression_with_non_archive_format(
199 formats: &[Extension],
202 formats_from_flag: Option<&OsString>,
204 let first_format = check_first_format_when_compressing(formats, output_path)?;
206 let is_some_input_a_folder = files.iter().any(|path| path.is_dir());
207 let is_multiple_inputs = files.len() > 1;
209 // If format is archive, nothing to check
210 // If there's no folder or multiple inputs, non-archive formats can handle it
211 if first_format.is_archive() || !is_some_input_a_folder && !is_multiple_inputs {
215 let first_detail_message = if is_multiple_inputs {
216 "You are trying to compress multiple files."
218 "You are trying to compress a folder."
221 let (from_hint, to_hint) = if let Some(formats) = formats_from_flag {
222 let formats = formats.to_string_lossy();
224 format!("From: --format {formats}"),
225 format!("To: --format tar.{formats}"),
228 // This piece of code creates a suggestion for compressing multiple files
230 // Change from file.bz.xz
232 let suggested_output_path = build_archive_file_suggestion(output_path, ".tar")
233 .expect("output path should contain a compression format");
236 format!("From: {}", EscapedPathDisplay::new(output_path)),
237 format!("To: {suggested_output_path}"),
240 let output_path = EscapedPathDisplay::new(output_path);
242 let error = FinalError::with_title(format!("Cannot compress to '{output_path}'."))
243 .detail(first_detail_message)
245 "The compression format '{first_format}' does not accept multiple files.",
247 .detail("Formats that bundle files into an archive are tar and zip.")
248 .hint(format!("Try inserting 'tar.' or 'zip.' before '{first_format}'."))