Merge pull request #253 from Crypto-Spartan/update-dependencies
[ouch.git] / src / extension.rs
blobe8807d00e5c74f929854793fef61eec721430a33
1 //! Our representation of all the supported compression formats.
3 use std::{ffi::OsStr, fmt, path::Path};
5 use self::CompressionFormat::*;
7 /// A wrapper around `CompressionFormat` that allows combinations like `tgz`
8 #[derive(Debug, Clone, Eq)]
9 #[non_exhaustive]
10 pub struct Extension {
11     /// One extension like "tgz" can be made of multiple CompressionFormats ([Tar, Gz])
12     pub compression_formats: &'static [CompressionFormat],
13     /// The input text for this extension, like "tgz", "tar" or "xz"
14     pub display_text: String,
16 // The display_text should be ignored when comparing extensions
17 impl PartialEq for Extension {
18     fn eq(&self, other: &Self) -> bool {
19         self.compression_formats == other.compression_formats
20     }
23 impl Extension {
24     /// # Panics:
25     ///   Will panic if `formats` is empty
26     pub fn new(formats: &'static [CompressionFormat], text: impl Into<String>) -> Self {
27         assert!(!formats.is_empty());
28         Self { compression_formats: formats, display_text: text.into() }
29     }
31     /// Checks if the first format in `compression_formats` is an archive
32     pub fn is_archive(&self) -> bool {
33         // Safety: we check that `compression_formats` is not empty in `Self::new`
34         self.compression_formats[0].is_archive_format()
35     }
37     /// Iteration to inner compression formats, useful for flat_mapping
38     pub fn iter(&self) -> impl Iterator<Item = &CompressionFormat> {
39         self.compression_formats.iter()
40     }
43 impl fmt::Display for Extension {
44     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45         self.display_text.fmt(f)
46     }
49 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
50 /// Accepted extensions for input and output
51 pub enum CompressionFormat {
52     /// .gz
53     Gzip,
54     /// .bz .bz2
55     Bzip,
56     /// .lz4
57     Lz4,
58     /// .xz .lzma
59     Lzma,
60     /// .sz
61     Snappy,
62     /// tar, tgz, tbz, tbz2, txz, tlz4, tlzma, tsz, tzst
63     Tar,
64     /// .zst
65     Zstd,
66     /// .zip
67     Zip,
70 impl CompressionFormat {
71     /// Currently supported archive formats are .tar (and aliases to it) and .zip
72     pub fn is_archive_format(&self) -> bool {
73         // Keep this match like that without a wildcard `_` so we don't forget to update it
74         match self {
75             Tar | Zip => true,
76             Gzip => false,
77             Bzip => false,
78             Lz4 => false,
79             Lzma => false,
80             Snappy => false,
81             Zstd => false,
82         }
83     }
86 impl fmt::Display for CompressionFormat {
87     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
88         write!(
89             f,
90             "{}",
91             match self {
92                 Gzip => ".gz",
93                 Bzip => ".bz",
94                 Zstd => ".zst",
95                 Lz4 => ".lz4",
96                 Lzma => ".lz",
97                 Snappy => ".sz",
98                 Tar => ".tar",
99                 Zip => ".zip",
100             }
101         )
102     }
105 // use crate::extension::CompressionFormat::*;
108 /// Extracts extensions from a path,
109 /// return both the remaining path and the list of extension objects
110 pub fn separate_known_extensions_from_name(mut path: &Path) -> (&Path, Vec<Extension>) {
111     // // TODO: check for file names with the name of an extension
112     // // TODO2: warn the user that currently .tar.gz is a .gz file named .tar
113     //
114     // let all = ["tar", "zip", "bz", "bz2", "gz", "xz", "lzma", "lz"];
115     // if path.file_name().is_some() && all.iter().any(|ext| path.file_name().unwrap() == *ext) {
116     //     todo!("we found a extension in the path name instead, what to do with this???");
117     // }
119     let mut extensions = vec![];
121     // While there is known extensions at the tail, grab them
122     while let Some(extension) = path.extension().and_then(OsStr::to_str) {
123         let formats: &[CompressionFormat] = match extension {
124             "tar" => &[Tar],
125             "tgz" => &[Tar, Gzip],
126             "tbz" | "tbz2" => &[Tar, Bzip],
127             "tlz4" => &[Tar, Lz4],
128             "txz" | "tlzma" => &[Tar, Lzma],
129             "tsz" => &[Tar, Snappy],
130             "tzst" => &[Tar, Zstd],
131             "zip" => &[Zip],
132             "bz" | "bz2" => &[Bzip],
133             "gz" => &[Gzip],
134             "lz4" => &[Lz4],
135             "xz" | "lzma" => &[Lzma],
136             "sz" => &[Snappy],
137             "zst" => &[Zstd],
138             _ => break,
139         };
141         let extension = Extension::new(formats, extension);
142         extensions.push(extension);
144         // Update for the next iteration
145         path = if let Some(stem) = path.file_stem() { Path::new(stem) } else { Path::new("") };
146     }
147     // Put the extensions in the correct order: left to right
148     extensions.reverse();
150     (path, extensions)
153 /// Extracts extensions from a path, return only the list of extension objects
154 pub fn extensions_from_path(path: &Path) -> Vec<Extension> {
155     let (_, extensions) = separate_known_extensions_from_name(path);
156     extensions
159 #[cfg(test)]
160 mod tests {
161     use super::*;
163     #[test]
164     fn test_extensions_from_path() {
165         use CompressionFormat::*;
166         let path = Path::new("bolovo.tar.gz");
168         let extensions: Vec<Extension> = extensions_from_path(path);
169         let formats: Vec<&CompressionFormat> = extensions.iter().flat_map(Extension::iter).collect::<Vec<_>>();
171         assert_eq!(formats, vec![&Tar, &Gzip]);
172     }