Make ouch support paths with dot-dot (..) for input files/directories
[ouch.git] / src / utils.rs
blob5c7225fbe6522792c22110a9b2491882fad95840
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: &Vec<PathBuf>, format: &CompressionFormat) -> OuchResult<()> {
19     if files.len() != 1 {
20         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);
21         return Err(Error::InvalidInput);
22     }
24     Ok(())
27 pub (crate) fn create_path_if_non_existent(path: &Path) -> OuchResult<()> {
28     if !path.exists() {
29         println!(
30             "{}: attempting to create folder {:?}.",
31             "[INFO]".yellow(),
32             &path
33         );
34         std::fs::create_dir_all(path)?;
35         println!(
36             "{}: directory {:#?} created.",
37             "[INFO]".yellow(),
38             fs::canonicalize(&path)?
39         );
40     }
41     Ok(())
44 pub (crate) fn get_destination_path(dest: &Option<File>) -> &Path {
45     match dest {
46         Some(output) => {
47             // Must be None according to the way command-line arg. parsing in Ouch works
48             assert_eq!(output.extension, None);
50             Path::new(&output.path)
51         }
52         None => Path::new("."),
53     }