14 utils::{pretty_format_list_of_paths, try_infer_extension, user_wants_to_continue, EscapedPathDisplay},
15 warning, QuestionAction, QuestionPolicy, Result,
18 /// Check, for each file, if the mime type matches the detected extensions.
20 /// In case the file doesn't has any extensions, try to infer the format.
22 /// TODO: maybe the name of this should be "magic numbers" or "file signature",
24 pub fn check_mime_type(
26 formats: &mut [Vec<Extension>],
27 question_policy: QuestionPolicy,
28 ) -> Result<ControlFlow<()>> {
29 for (path, format) in files.iter().zip(formats.iter_mut()) {
30 if format.is_empty() {
31 // File with no extension
32 // Try to detect it automatically and prompt the user about it
33 if let Some(detected_format) = try_infer_extension(path) {
34 // Inferring the file extension can have unpredicted consequences (e.g. the user just
35 // mistyped, ...) which we should always inform the user about.
38 "Detected file: `{}` extension as `{}`",
42 if user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
43 format.push(detected_format);
45 return Ok(ControlFlow::Break(()));
48 } else if let Some(detected_format) = try_infer_extension(path) {
49 // File ending with extension
50 // Try to detect the extension and warn the user if it differs from the written one
51 let outer_ext = format.iter().next_back().unwrap();
54 .ends_with(detected_format.compression_formats)
57 "The file extension: `{}` differ from the detected extension: `{}`",
61 if !user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
62 return Ok(ControlFlow::Break(()));
66 // NOTE: If this actually produces no false positives, we can upgrade it in the future
67 // to a warning and ask the user if he wants to continue decompressing.
68 info!(accessible, "Could not detect the extension of `{}`", path.display());
71 Ok(ControlFlow::Continue(()))
74 /// In the context of listing archives, this function checks if `ouch` was told to list
75 /// the contents of a compressed file that is not an archive
76 pub fn check_for_non_archive_formats(files: &[PathBuf], formats: &[Vec<Extension>]) -> Result<()> {
77 let mut not_archives = files
80 .filter(|(_, formats)| !formats.first().map(Extension::is_archive).unwrap_or(false))
81 .map(|(path, _)| path)
84 if not_archives.peek().is_some() {
85 let not_archives: Vec<_> = not_archives.collect();
86 let error = FinalError::with_title("Cannot list archive contents")
87 .detail("Only archives can have their contents listed")
89 "Files are not archives: {}",
90 pretty_format_list_of_paths(¬_archives)
93 return Err(error.into());
99 /// Show error if archive format is not the first format in the chain.
100 pub fn check_archive_formats_position(formats: &[Extension], output_path: &Path) -> Result<()> {
101 if let Some(format) = formats.iter().skip(1).find(|format| format.is_archive()) {
102 let error = FinalError::with_title(format!(
103 "Cannot compress to '{}'.",
104 EscapedPathDisplay::new(output_path)
106 .detail(format!("Found the format '{format}' in an incorrect position."))
108 "'{format}' can only be used at the start of the file extension."
111 "If you wish to compress multiple files, start the extension with '{format}'."
114 "Otherwise, remove the last '{}' from '{}'.",
116 EscapedPathDisplay::new(output_path)
119 return Err(error.into());
124 /// Check if all provided files have formats to decompress.
125 pub fn check_missing_formats_when_decompressing(files: &[PathBuf], formats: &[Vec<Extension>]) -> Result<()> {
126 let files_missing_format: Vec<PathBuf> = files
129 .filter(|(_, format)| format.is_empty())
130 .map(|(input_path, _)| PathBuf::from(input_path))
133 if let Some(path) = files_missing_format.first() {
134 let error = FinalError::with_title("Cannot decompress files without extensions")
136 "Files without supported extensions: {}",
137 pretty_format_list_of_paths(&files_missing_format)
139 .detail("Decompression formats are detected automatically by the file extension")
140 .hint("Provide a file with a supported extension:")
141 .hint(" ouch decompress example.tar.gz")
143 .hint("Or overwrite this option with the '--format' flag:")
145 " ouch decompress {} --format tar.gz",
146 EscapedPathDisplay::new(path),
149 return Err(error.into());
154 /// Check if there is a first format when compressing, and returns it.
155 pub fn check_first_format_when_compressing<'a>(formats: &'a [Extension], output_path: &Path) -> Result<&'a Extension> {
156 formats.first().ok_or_else(|| {
157 let output_path = EscapedPathDisplay::new(output_path);
158 FinalError::with_title(format!("Cannot compress to '{output_path}'."))
159 .detail("You shall supply the compression format")
160 .hint("Try adding supported extensions (see --help):")
161 .hint(format!(" ouch compress <FILES>... {output_path}.tar.gz"))
162 .hint(format!(" ouch compress <FILES>... {output_path}.zip"))
164 .hint("Alternatively, you can overwrite this option by using the '--format' flag:")
165 .hint(format!(" ouch compress <FILES>... {output_path} --format tar.gz"))