feat: cleanup codes and more error handling
[ouch.git] / src / commands / mod.rs
blobe5be2330ae2dde6f8bddb3f3010ef97010ee47c0
1 //! Receive command from the cli and call the respective function for that command.
3 mod compress;
4 mod decompress;
5 mod list;
7 use std::{ops::ControlFlow, path::PathBuf};
9 use rayon::prelude::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator};
10 use utils::colors;
12 use crate::{
13     check,
14     cli::Subcommand,
15     commands::{compress::compress_files, decompress::decompress_file, list::list_archive_contents},
16     error::{Error, FinalError},
17     extension::{self, parse_format},
18     info,
19     list::ListOptions,
20     utils::{self, to_utf, EscapedPathDisplay, FileVisibilityPolicy},
21     warning, CliArgs, QuestionPolicy,
24 /// Warn the user that (de)compressing this .zip archive might freeze their system.
25 fn warn_user_about_loading_zip_in_memory() {
26     const ZIP_IN_MEMORY_LIMITATION_WARNING: &str = "\n\
27         \tThe format '.zip' is limited and cannot be (de)compressed using encoding streams.\n\
28         \tWhen using '.zip' with other formats, (de)compression must be done in-memory\n\
29         \tCareful, you might run out of RAM if the archive is too large!";
31     warning!("{}", ZIP_IN_MEMORY_LIMITATION_WARNING);
34 /// This function checks what command needs to be run and performs A LOT of ahead-of-time checks
35 /// to assume everything is OK.
36 ///
37 /// There are a lot of custom errors to give enough error description and explanation.
38 pub fn run(
39     args: CliArgs,
40     question_policy: QuestionPolicy,
41     file_visibility_policy: FileVisibilityPolicy,
42 ) -> crate::Result<()> {
43     match args.cmd {
44         Subcommand::Compress {
45             files,
46             output: output_path,
47             level,
48             fast,
49             slow,
50         } => {
51             // After cleaning, if there are no input files left, exit
52             if files.is_empty() {
53                 return Err(FinalError::with_title("No files to compress").into());
54             }
56             // Formats from path extension, like "file.tar.gz.xz" -> vec![Tar, Gzip, Lzma]
57             let (formats_from_flag, formats) = match args.format {
58                 Some(formats) => {
59                     let parsed_formats = parse_format(&formats)?;
60                     (Some(formats), parsed_formats)
61                 }
62                 None => (None, extension::extensions_from_path(&output_path)),
63             };
65             check::check_invalid_compression_with_non_archive_format(
66                 &formats,
67                 &output_path,
68                 &files,
69                 formats_from_flag.as_ref(),
70             )?;
71             check::check_archive_formats_position(&formats, &output_path)?;
73             let output_file = match utils::ask_to_create_file(&output_path, question_policy)? {
74                 Some(writer) => writer,
75                 None => return Ok(()),
76             };
78             let level = if fast {
79                 Some(1) // Lowest level of compression
80             } else if slow {
81                 Some(i16::MAX) // Highest level of compression
82             } else {
83                 level
84             };
86             let compress_result = compress_files(
87                 files,
88                 formats,
89                 output_file,
90                 &output_path,
91                 args.quiet,
92                 question_policy,
93                 file_visibility_policy,
94                 level,
95             );
97             if let Ok(true) = compress_result {
98                 // this is only printed once, so it doesn't result in much text. On the other hand,
99                 // having a final status message is important especially in an accessibility context
100                 // as screen readers may not read a commands exit code, making it hard to reason
101                 // about whether the command succeeded without such a message
102                 info!(accessible, "Successfully compressed '{}'.", to_utf(&output_path));
103             } else {
104                 // If Ok(false) or Err() occurred, delete incomplete file at `output_path`
105                 //
106                 // if deleting fails, print an extra alert message pointing
107                 // out that we left a possibly CORRUPTED file at `output_path`
108                 if utils::remove_file_or_dir(&output_path).is_err() {
109                     eprintln!("{red}FATAL ERROR:\n", red = *colors::RED);
110                     eprintln!(
111                         "  Ouch failed to delete the file '{}'.",
112                         EscapedPathDisplay::new(&output_path)
113                     );
114                     eprintln!("  Please delete it manually.");
115                     eprintln!("  This file is corrupted if compression didn't finished.");
117                     if compress_result.is_err() {
118                         eprintln!("  Compression failed for reasons below.");
119                     }
120                 }
121             }
123             compress_result?;
124         }
125         Subcommand::Decompress { files, output_dir } => {
126             let mut output_paths = vec![];
127             let mut formats = vec![];
129             if let Some(format) = args.format {
130                 let format = parse_format(&format)?;
131                 for path in files.iter() {
132                     let file_name = path.file_name().ok_or_else(|| Error::NotFound {
133                         error_title: format!("{} does not have a file name", EscapedPathDisplay::new(path)),
134                     })?;
135                     output_paths.push(file_name.as_ref());
136                     formats.push(format.clone());
137                 }
138             } else {
139                 for path in files.iter() {
140                     let (pathbase, mut file_formats) = extension::separate_known_extensions_from_name(path);
142                     if let ControlFlow::Break(_) = check::check_mime_type(path, &mut file_formats, question_policy)? {
143                         return Ok(());
144                     }
146                     output_paths.push(pathbase);
147                     formats.push(file_formats);
148                 }
149             }
151             check::check_missing_formats_when_decompressing(&files, &formats)?;
153             // The directory that will contain the output files
154             // We default to the current directory if the user didn't specify an output directory with --dir
155             let output_dir = if let Some(dir) = output_dir {
156                 utils::create_dir_if_non_existent(&dir)?;
157                 dir
158             } else {
159                 PathBuf::from(".")
160             };
162             files
163                 .par_iter()
164                 .zip(formats)
165                 .zip(output_paths)
166                 .try_for_each(|((input_path, formats), file_name)| {
167                     let output_file_path = output_dir.join(file_name); // Path used by single file format archives
168                     decompress_file(
169                         input_path,
170                         formats,
171                         &output_dir,
172                         output_file_path,
173                         question_policy,
174                         args.quiet,
175                     )
176                 })?;
177         }
178         Subcommand::List { archives: files, tree } => {
179             let mut formats = vec![];
181             if let Some(format) = args.format {
182                 let format = parse_format(&format)?;
183                 for _ in 0..files.len() {
184                     formats.push(format.clone());
185                 }
186             } else {
187                 for path in files.iter() {
188                     let mut file_formats = extension::extensions_from_path(path);
190                     if let ControlFlow::Break(_) = check::check_mime_type(path, &mut file_formats, question_policy)? {
191                         return Ok(());
192                     }
194                     formats.push(file_formats);
195                 }
196             }
198             // Ensure we were not told to list the content of a non-archive compressed file
199             check::check_for_non_archive_formats(&files, &formats)?;
201             let list_options = ListOptions { tree };
203             for (i, (archive_path, formats)) in files.iter().zip(formats).enumerate() {
204                 if i > 0 {
205                     println!();
206                 }
207                 let formats = extension::flatten_compression_formats(&formats);
208                 list_archive_contents(archive_path, formats, list_options, question_policy)?;
209             }
210         }
211     }
212     Ok(())