13 extension::{build_archive_file_suggestion, Extension},
15 utils::{pretty_format_list_of_paths, try_infer_extension, user_wants_to_continue, EscapedPathDisplay},
16 warning, QuestionAction, QuestionPolicy, Result,
19 /// Check, for each file, if the mime type matches the detected extensions.
21 /// In case the file doesn't has any extensions, try to infer the format.
23 /// TODO: maybe the name of this should be "magic numbers" or "file signature",
25 pub fn check_mime_type(
27 formats: &mut [Vec<Extension>],
28 question_policy: QuestionPolicy,
29 ) -> Result<ControlFlow<()>> {
30 for (path, format) in files.iter().zip(formats.iter_mut()) {
31 if format.is_empty() {
32 // File with no extension
33 // Try to detect it automatically and prompt the user about it
34 if let Some(detected_format) = try_infer_extension(path) {
35 // Inferring the file extension can have unpredicted consequences (e.g. the user just
36 // mistyped, ...) which we should always inform the user about.
39 "Detected file: `{}` extension as `{}`",
43 if user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
44 format.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
52 let outer_ext = format.iter().next_back().unwrap();
55 .ends_with(detected_format.compression_formats)
58 "The file extension: `{}` differ from the detected extension: `{}`",
62 if !user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
63 return Ok(ControlFlow::Break(()));
67 // NOTE: If this actually produces no false positives, we can upgrade it in the future
68 // to a warning and ask the user if he wants to continue decompressing.
69 info!(accessible, "Could not detect the extension of `{}`", path.display());
72 Ok(ControlFlow::Continue(()))
75 /// In the context of listing archives, this function checks if `ouch` was told to list
76 /// the contents of a compressed file that is not an archive
77 pub fn check_for_non_archive_formats(files: &[PathBuf], formats: &[Vec<Extension>]) -> Result<()> {
78 let mut not_archives = files
81 .filter(|(_, formats)| !formats.first().map(Extension::is_archive).unwrap_or(false))
82 .map(|(path, _)| path)
85 if not_archives.peek().is_some() {
86 let not_archives: Vec<_> = not_archives.collect();
87 let error = FinalError::with_title("Cannot list archive contents")
88 .detail("Only archives can have their contents listed")
90 "Files are not archives: {}",
91 pretty_format_list_of_paths(¬_archives)
94 return Err(error.into());
100 /// Show error if archive format is not the first format in the chain.
101 pub fn check_archive_formats_position(formats: &[Extension], output_path: &Path) -> Result<()> {
102 if let Some(format) = formats.iter().skip(1).find(|format| format.is_archive()) {
103 let error = FinalError::with_title(format!(
104 "Cannot compress to '{}'.",
105 EscapedPathDisplay::new(output_path)
107 .detail(format!("Found the format '{format}' in an incorrect position."))
109 "'{format}' can only be used at the start of the file extension."
112 "If you wish to compress multiple files, start the extension with '{format}'."
115 "Otherwise, remove the last '{}' from '{}'.",
117 EscapedPathDisplay::new(output_path)
120 return Err(error.into());
125 /// Check if all provided files have formats to decompress.
126 pub fn check_missing_formats_when_decompressing(files: &[PathBuf], formats: &[Vec<Extension>]) -> Result<()> {
127 let files_missing_format: Vec<PathBuf> = files
130 .filter(|(_, format)| format.is_empty())
131 .map(|(input_path, _)| PathBuf::from(input_path))
134 if let Some(path) = files_missing_format.first() {
135 let error = FinalError::with_title("Cannot decompress files without extensions")
137 "Files without supported extensions: {}",
138 pretty_format_list_of_paths(&files_missing_format)
140 .detail("Decompression formats are detected automatically by the file extension")
141 .hint("Provide a file with a supported extension:")
142 .hint(" ouch decompress example.tar.gz")
144 .hint("Or overwrite this option with the '--format' flag:")
146 " ouch decompress {} --format tar.gz",
147 EscapedPathDisplay::new(path),
150 return Err(error.into());
155 /// Check if there is a first format when compressing, and returns it.
156 pub fn check_first_format_when_compressing<'a>(formats: &'a [Extension], output_path: &Path) -> Result<&'a Extension> {
157 formats.first().ok_or_else(|| {
158 let output_path = EscapedPathDisplay::new(output_path);
159 FinalError::with_title(format!("Cannot compress to '{output_path}'."))
160 .detail("You shall supply the compression format")
161 .hint("Try adding supported extensions (see --help):")
162 .hint(format!(" ouch compress <FILES>... {output_path}.tar.gz"))
163 .hint(format!(" ouch compress <FILES>... {output_path}.zip"))
165 .hint("Alternatively, you can overwrite this option by using the '--format' flag:")
166 .hint(format!(" ouch compress <FILES>... {output_path} --format tar.gz"))
171 /// Check if compression is invalid because an archive format is necessary.
172 pub fn check_invalid_compression_with_non_archive_format(
173 formats: &[Extension],
176 formats_from_flag: Option<&OsString>,
178 let first_format = check_first_format_when_compressing(formats, output_path)?;
180 let is_some_input_a_folder = files.iter().any(|path| path.is_dir());
181 let is_multiple_inputs = files.len() > 1;
183 // If first format is not archive, can't compress folder, or multiple files
184 if !first_format.is_archive() && (is_some_input_a_folder || is_multiple_inputs) {
185 let first_detail_message = if is_multiple_inputs {
186 "You are trying to compress multiple files."
188 "You are trying to compress a folder."
191 let (from_hint, to_hint) = if let Some(formats) = formats_from_flag {
192 let formats = formats.to_string_lossy();
194 format!("From: --format {formats}"),
195 format!("To: --format tar.{formats}"),
198 // This piece of code creates a suggestion for compressing multiple files
200 // Change from file.bz.xz
202 let suggested_output_path = build_archive_file_suggestion(output_path, ".tar")
203 .expect("output path should contain a compression format");
206 format!("From: {}", EscapedPathDisplay::new(output_path)),
207 format!("To: {suggested_output_path}"),
210 let output_path = EscapedPathDisplay::new(output_path);
212 let error = FinalError::with_title(format!("Cannot compress to '{output_path}'."))
213 .detail(first_detail_message)
215 "The compression format '{first_format}' does not accept multiple files.",
217 .detail("Formats that bundle files into an archive are tar and zip.")
218 .hint(format!("Try inserting 'tar.' or 'zip.' before '{first_format}'."))
222 return Err(error.into());