Add a sad Python script for Ouch testing
[ouch.git] / src / utils.rs
blob6f37830be69d62f64f87c844be1ebbe2b0094016
1 use std::{fs, path::{Path, PathBuf}};
3 use colored::Colorize;
4 use crate::{error::{Error, OuchResult}, extension::CompressionFormat, file::File};
6 pub (crate) fn ensure_exists<'a, P>(path: P) -> OuchResult<()>
7 where
8     P: AsRef<Path> + 'a   {
9         let exists = path.as_ref().exists();
10         if !exists {
11             eprintln!("{}: could not find file {:?}", "[ERROR]".red(), path.as_ref());
12             return Err(Error::FileNotFound(PathBuf::from(path.as_ref())));
13         }
14         Ok(())
15     }
17 pub (crate) fn check_for_multiple_files(files: &[PathBuf], format: &CompressionFormat) -> OuchResult<()> {
18     if files.len() != 1 {
19         eprintln!("{}: cannot compress multiple files directly to {:#?}.\n       Try using an intermediate archival method such as Tar.\n       Example: filename.tar{}", "[ERROR]".red(), format, format);
20         return Err(Error::InvalidInput);
21     }
23     Ok(())
26 pub (crate) fn create_path_if_non_existent(path: &Path) -> OuchResult<()> {
27     if !path.exists() {
28         println!(
29             "{}: attempting to create folder {:?}.",
30             "[INFO]".yellow(),
31             &path
32         );
33         std::fs::create_dir_all(path)?;
34         println!(
35             "{}: directory {:#?} created.",
36             "[INFO]".yellow(),
37             fs::canonicalize(&path)?
38         );
39     }
40     Ok(())
43 pub (crate) fn get_destination_path(dest: &Option<File>) -> &Path {
44     match dest {
45         Some(output) => {
46             // Must be None according to the way command-line arg. parsing in Ouch works
47             assert_eq!(output.extension, None);
49             Path::new(&output.path)
50         }
51         None => Path::new("."),
52     }