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.
38 info_accessible(format!(
39 "Detected file: `{}` extension as `{}`",
44 if user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
45 formats.push(detected_format);
47 return Ok(ControlFlow::Break(()));
50 } else if let Some(detected_format) = try_infer_extension(path) {
51 // File ending with extension
52 // Try to detect the extension and warn the user if it differs from the written one
54 let outer_ext = formats.iter().next_back().unwrap();
57 .ends_with(detected_format.compression_formats)
60 "The file extension: `{}` differ from the detected extension: `{}`",
61 outer_ext, detected_format
64 if !user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
65 return Ok(ControlFlow::Break(()));
69 // NOTE: If this actually produces no false positives, we can upgrade it in the future
70 // to a warning and ask the user if he wants to continue decompressing.
71 info_accessible(format!(
72 "Failed to confirm the format of `{}` by sniffing the contents, file might be misnamed",
76 Ok(ControlFlow::Continue(()))
79 /// In the context of listing archives, this function checks if `ouch` was told to list
80 /// the contents of a compressed file that is not an archive
81 pub fn check_for_non_archive_formats(files: &[PathBuf], formats: &[Vec<Extension>]) -> Result<()> {
82 let mut not_archives = files
85 .filter(|(_, formats)| !formats.first().map(Extension::is_archive).unwrap_or(false))
86 .map(|(path, _)| path)
89 if not_archives.peek().is_some() {
90 let not_archives: Vec<_> = not_archives.collect();
91 let error = FinalError::with_title("Cannot list archive contents")
92 .detail("Only archives can have their contents listed")
94 "Files are not archives: {}",
95 pretty_format_list_of_paths(¬_archives)
98 return Err(error.into());
104 /// Show error if archive format is not the first format in the chain.
105 pub fn check_archive_formats_position(formats: &[Extension], output_path: &Path) -> Result<()> {
106 if let Some(format) = formats.iter().skip(1).find(|format| format.is_archive()) {
107 let error = FinalError::with_title(format!(
108 "Cannot compress to '{}'.",
109 EscapedPathDisplay::new(output_path)
111 .detail(format!("Found the format '{format}' in an incorrect position."))
113 "'{format}' can only be used at the start of the file extension."
116 "If you wish to compress multiple files, start the extension with '{format}'."
119 "Otherwise, remove the last '{}' from '{}'.",
121 EscapedPathDisplay::new(output_path)
124 return Err(error.into());
129 /// Check if all provided files have formats to decompress.
130 pub fn check_missing_formats_when_decompressing(files: &[PathBuf], formats: &[Vec<Extension>]) -> Result<()> {
131 let files_with_broken_extension: Vec<&PathBuf> = files
134 .filter(|(_, format)| format.is_empty())
135 .map(|(input_path, _)| input_path)
138 if files_with_broken_extension.is_empty() {
142 let (files_with_unsupported_extensions, files_missing_extension): (Vec<&PathBuf>, Vec<&PathBuf>) =
143 files_with_broken_extension
145 .partition(|path| path.extension().is_some());
147 let mut error = FinalError::with_title("Cannot decompress files");
149 if !files_with_unsupported_extensions.is_empty() {
150 error = error.detail(format!(
151 "Files with unsupported extensions: {}",
152 pretty_format_list_of_paths(&files_with_unsupported_extensions)
156 if !files_missing_extension.is_empty() {
157 error = error.detail(format!(
158 "Files with missing extensions: {}",
159 pretty_format_list_of_paths(&files_missing_extension)
163 error = error.detail("Decompression formats are detected automatically from file extension");
164 error = error.hint_all_supported_formats();
166 // If there's exactly one file, give a suggestion to use `--format`
167 if let &[path] = files_with_broken_extension.as_slice() {
170 .hint("Alternatively, you can pass an extension to the '--format' flag:")
172 " ouch decompress {} --format tar.gz",
173 EscapedPathDisplay::new(path),
180 /// Check if there is a first format when compressing, and returns it.
181 pub fn check_first_format_when_compressing<'a>(formats: &'a [Extension], output_path: &Path) -> Result<&'a Extension> {
182 formats.first().ok_or_else(|| {
183 let output_path = EscapedPathDisplay::new(output_path);
184 FinalError::with_title(format!("Cannot compress to '{output_path}'."))
185 .detail("You shall supply the compression format")
186 .hint("Try adding supported extensions (see --help):")
187 .hint(format!(" ouch compress <FILES>... {output_path}.tar.gz"))
188 .hint(format!(" ouch compress <FILES>... {output_path}.zip"))
190 .hint("Alternatively, you can overwrite this option by using the '--format' flag:")
191 .hint(format!(" ouch compress <FILES>... {output_path} --format tar.gz"))
196 /// Check if compression is invalid because an archive format is necessary.
198 /// Non-archive formats don't support multiple file compression or folder compression.
199 pub fn check_invalid_compression_with_non_archive_format(
200 formats: &[Extension],
203 formats_from_flag: Option<&OsString>,
205 let first_format = check_first_format_when_compressing(formats, output_path)?;
207 let is_some_input_a_folder = files.iter().any(|path| path.is_dir());
208 let is_multiple_inputs = files.len() > 1;
210 // If format is archive, nothing to check
211 // If there's no folder or multiple inputs, non-archive formats can handle it
212 if first_format.is_archive() || !is_some_input_a_folder && !is_multiple_inputs {
216 let first_detail_message = if is_multiple_inputs {
217 "You are trying to compress multiple files."
219 "You are trying to compress a folder."
222 let (from_hint, to_hint) = if let Some(formats) = formats_from_flag {
223 let formats = formats.to_string_lossy();
225 format!("From: --format {formats}"),
226 format!("To: --format tar.{formats}"),
229 // This piece of code creates a suggestion for compressing multiple files
231 // Change from file.bz.xz
233 let suggested_output_path = build_archive_file_suggestion(output_path, ".tar")
234 .expect("output path should contain a compression format");
237 format!("From: {}", EscapedPathDisplay::new(output_path)),
238 format!("To: {suggested_output_path}"),
241 let output_path = EscapedPathDisplay::new(output_path);
243 let error = FinalError::with_title(format!("Cannot compress to '{output_path}'."))
244 .detail(first_detail_message)
246 "The compression format '{first_format}' does not accept multiple files.",
248 .detail("Formats that bundle files into an archive are tar and zip.")
249 .hint(format!("Try inserting 'tar.' or 'zip.' before '{first_format}'."))