chore: simplify code after feature stabilization
[ouch.git] / src / check.rs
blob7face91758feafb1801b28da7507608c2ee6c901
1 //! Checks for errors.
3 #![warn(missing_docs)]
5 use std::{
6     ffi::OsString,
7     ops::ControlFlow,
8     path::{Path, PathBuf},
9 };
11 use crate::{
12     error::FinalError,
13     extension::{build_archive_file_suggestion, Extension},
14     utils::{
15         logger::{info_accessible, warning},
16         pretty_format_list_of_paths, try_infer_extension, user_wants_to_continue, EscapedPathDisplay,
17     },
18     QuestionAction, QuestionPolicy, Result,
21 /// Check if the mime type matches the detected extensions.
22 ///
23 /// In case the file doesn't has any extensions, try to infer the format.
24 ///
25 /// TODO: maybe the name of this should be "magic numbers" or "file signature",
26 /// and not MIME.
27 pub fn check_mime_type(
28     path: &Path,
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 `{}`",
40                 path.display(),
41                 detected_format
42             ));
44             if user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
45                 formats.push(detected_format);
46             } else {
47                 return Ok(ControlFlow::Break(()));
48             }
49         }
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();
55         if !outer_ext
56             .compression_formats
57             .ends_with(detected_format.compression_formats)
58         {
59             warning(format!(
60                 "The file extension: `{}` differ from the detected extension: `{}`",
61                 outer_ext, detected_format
62             ));
64             if !user_wants_to_continue(path, question_policy, QuestionAction::Decompression)? {
65                 return Ok(ControlFlow::Break(()));
66             }
67         }
68     } else {
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",
73             path.display()
74         ));
75     }
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
83         .iter()
84         .zip(formats)
85         .filter(|(_, formats)| !formats.first().map(Extension::is_archive).unwrap_or(false))
86         .map(|(path, _)| path)
87         .peekable();
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")
93             .detail(format!(
94                 "Files are not archives: {}",
95                 pretty_format_list_of_paths(&not_archives)
96             ));
98         return Err(error.into());
99     }
101     Ok(())
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)
110         ))
111         .detail(format!("Found the format '{format}' in an incorrect position."))
112         .detail(format!(
113             "'{format}' can only be used at the start of the file extension."
114         ))
115         .hint(format!(
116             "If you wish to compress multiple files, start the extension with '{format}'."
117         ))
118         .hint(format!(
119             "Otherwise, remove the last '{}' from '{}'.",
120             format,
121             EscapedPathDisplay::new(output_path)
122         ));
124         return Err(error.into());
125     }
126     Ok(())
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
132         .iter()
133         .zip(formats)
134         .filter(|(_, format)| format.is_empty())
135         .map(|(input_path, _)| input_path)
136         .collect();
138     if files_with_broken_extension.is_empty() {
139         return Ok(());
140     }
142     let (files_with_unsupported_extensions, files_missing_extension): (Vec<&PathBuf>, Vec<&PathBuf>) =
143         files_with_broken_extension
144             .iter()
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)
153         ));
154     }
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)
160         ));
161     }
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() {
168         error = error
169             .hint("")
170             .hint("Alternatively, you can pass an extension to the '--format' flag:")
171             .hint(format!(
172                 "  ouch decompress {} --format tar.gz",
173                 EscapedPathDisplay::new(path),
174             ));
175     }
177     Err(error.into())
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"))
189             .hint("")
190             .hint("Alternatively, you can overwrite this option by using the '--format' flag:")
191             .hint(format!("  ouch compress <FILES>... {output_path} --format tar.gz"))
192             .into()
193     })
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],
201     output_path: &Path,
202     files: &[PathBuf],
203     formats_from_flag: Option<&OsString>,
204 ) -> Result<()> {
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 {
213         return Ok(());
214     }
216     let first_detail_message = if is_multiple_inputs {
217         "You are trying to compress multiple files."
218     } else {
219         "You are trying to compress a folder."
220     };
222     let (from_hint, to_hint) = if let Some(formats) = formats_from_flag {
223         let formats = formats.to_string_lossy();
224         (
225             format!("From: --format {formats}"),
226             format!("To:   --format tar.{formats}"),
227         )
228     } else {
229         // This piece of code creates a suggestion for compressing multiple files
230         // It says:
231         // Change from file.bz.xz
232         // To          file.tar.bz.xz
233         let suggested_output_path = build_archive_file_suggestion(output_path, ".tar")
234             .expect("output path should contain a compression format");
236         (
237             format!("From: {}", EscapedPathDisplay::new(output_path)),
238             format!("To:   {suggested_output_path}"),
239         )
240     };
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)
245         .detail(format!(
246             "The compression format '{first_format}' does not accept multiple files.",
247         ))
248         .detail("Formats that bundle files into an archive are tar and zip.")
249         .hint(format!("Try inserting 'tar.' or 'zip.' before '{first_format}'."))
250         .hint(from_hint)
251         .hint(to_hint);
253     Err(error.into())