1 //! Our representation of all the supported compression formats.
3 use std::{ffi::OsStr, fmt, path::Path};
6 use CompressionFormat::*;
8 use crate::{error::Error, utils::logger::warning};
10 pub const SUPPORTED_EXTENSIONS: &[&str] = &[
21 #[cfg(feature = "unrar")]
26 pub const SUPPORTED_ALIASES: &[&str] = &["tgz", "tbz", "tlz4", "txz", "tzlma", "tsz", "tzst"];
28 #[cfg(not(feature = "unrar"))]
29 pub const PRETTY_SUPPORTED_EXTENSIONS: &str = "tar, zip, bz, bz2, gz, lz4, xz, lzma, sz, zst, 7z";
30 #[cfg(feature = "unrar")]
31 pub const PRETTY_SUPPORTED_EXTENSIONS: &str = "tar, zip, bz, bz2, gz, lz4, xz, lzma, sz, zst, rar, 7z";
33 pub const PRETTY_SUPPORTED_ALIASES: &str = "tgz, tbz, tlz4, txz, tzlma, tsz, tzst";
35 /// A wrapper around `CompressionFormat` that allows combinations like `tgz`
36 #[derive(Debug, Clone)]
37 // Keep `PartialEq` only for testing because two formats are the same even if
38 // their `display_text` does not match (beware of aliases)
39 #[cfg_attr(test, derive(PartialEq))]
40 // Should only be built with constructors
42 pub struct Extension {
43 /// One extension like "tgz" can be made of multiple CompressionFormats ([Tar, Gz])
44 pub compression_formats: &'static [CompressionFormat],
45 /// The input text for this extension, like "tgz", "tar" or "xz"
51 /// Will panic if `formats` is empty
52 pub fn new(formats: &'static [CompressionFormat], text: impl ToString) -> Self {
53 assert!(!formats.is_empty());
55 compression_formats: formats,
56 display_text: text.to_string(),
60 /// Checks if the first format in `compression_formats` is an archive
61 pub fn is_archive(&self) -> bool {
62 // Safety: we check that `compression_formats` is not empty in `Self::new`
63 self.compression_formats[0].is_archive_format()
67 impl fmt::Display for Extension {
68 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69 self.display_text.fmt(f)
73 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
74 /// Accepted extensions for input and output
75 pub enum CompressionFormat {
86 /// tar, tgz, tbz, tbz2, txz, tlz4, tlzma, tsz, tzst
92 // even if built without RAR support, we still want to recognise the format
99 impl CompressionFormat {
100 /// Currently supported archive formats are .tar (and aliases to it) and .zip
101 fn is_archive_format(&self) -> bool {
102 // Keep this match like that without a wildcard `_` so we don't forget to update it
104 Tar | Zip | Rar | SevenZip => true,
115 fn to_extension(ext: &[u8]) -> Option<Extension> {
119 b"tgz" => &[Tar, Gzip],
120 b"tbz" | b"tbz2" => &[Tar, Bzip],
121 b"tlz4" => &[Tar, Lz4],
122 b"txz" | b"tlzma" => &[Tar, Lzma],
123 b"tsz" => &[Tar, Snappy],
124 b"tzst" => &[Tar, Zstd],
126 b"bz" | b"bz2" => &[Bzip],
129 b"xz" | b"lzma" => &[Lzma],
133 b"7z" => &[SevenZip],
140 fn split_extension(name: &mut &[u8]) -> Option<Extension> {
141 let (new_name, ext) = name.rsplit_once_str(b".")?;
142 if matches!(new_name, b"" | b"." | b"..") {
145 let ext = to_extension(ext)?;
150 pub fn parse_format_flag(input: &OsStr) -> crate::Result<Vec<Extension>> {
151 let format = input.as_encoded_bytes();
153 let format = std::str::from_utf8(format).map_err(|_| Error::InvalidFormatFlag {
154 text: input.to_owned(),
155 reason: "Invalid UTF-8.".to_string(),
158 let extensions: Vec<Extension> = format
160 .filter(|extension| !extension.is_empty())
162 to_extension(extension.as_bytes()).ok_or_else(|| Error::InvalidFormatFlag {
163 text: input.to_owned(),
164 reason: format!("Unsupported extension '{}'", extension),
167 .collect::<crate::Result<_>>()?;
169 if extensions.is_empty() {
170 return Err(Error::InvalidFormatFlag {
171 text: input.to_owned(),
172 reason: "Parsing got an empty list of extensions.".to_string(),
179 /// Extracts extensions from a path.
181 /// Returns both the remaining path and the list of extension objects
182 pub fn separate_known_extensions_from_name(path: &Path) -> (&Path, Vec<Extension>) {
183 let mut extensions = vec![];
185 let Some(mut name) = path.file_name().and_then(<[u8] as ByteSlice>::from_os_str) else {
186 return (path, extensions);
189 // While there is known extensions at the tail, grab them
190 while let Some(extension) = split_extension(&mut name) {
191 extensions.insert(0, extension);
194 if let Ok(name) = name.to_str() {
195 let file_stem = name.trim_matches('.');
196 if SUPPORTED_EXTENSIONS.contains(&file_stem) || SUPPORTED_ALIASES.contains(&file_stem) {
198 "Received a file with name '{file_stem}', but {file_stem} was expected as the extension."
203 (name.to_path().unwrap(), extensions)
206 /// Extracts extensions from a path, return only the list of extension objects
207 pub fn extensions_from_path(path: &Path) -> Vec<Extension> {
208 let (_, extensions) = separate_known_extensions_from_name(path);
212 /// Panics if formats has an empty list of compression formats
213 pub fn split_first_compression_format(formats: &[Extension]) -> (CompressionFormat, Vec<CompressionFormat>) {
214 let mut extensions: Vec<CompressionFormat> = flatten_compression_formats(formats);
215 let first_extension = extensions.remove(0);
216 (first_extension, extensions)
219 pub fn flatten_compression_formats(extensions: &[Extension]) -> Vec<CompressionFormat> {
222 .flat_map(|extension| extension.compression_formats.iter())
227 /// Builds a suggested output file in scenarios where the user tried to compress
228 /// a folder into a non-archive compression format, for error message purposes
230 /// E.g.: `build_suggestion("file.bz.xz", ".tar")` results in `Some("file.tar.bz.xz")`
231 pub fn build_archive_file_suggestion(path: &Path, suggested_extension: &str) -> Option<String> {
232 let path = path.to_string_lossy();
233 let mut rest = &*path;
234 let mut position_to_insert = 0;
236 // Walk through the path to find the first supported compression extension
237 while let Some(pos) = rest.find('.') {
238 // Use just the text located after the dot we found
239 rest = &rest[pos + 1..];
240 position_to_insert += pos + 1;
242 // If the string contains more chained extensions, clip to the immediate one
243 let maybe_extension = {
244 let idx = rest.find('.').unwrap_or(rest.len());
248 // If the extension we got is a supported extension, generate the suggestion
249 // at the position we found
250 if SUPPORTED_EXTENSIONS.contains(&maybe_extension) || SUPPORTED_ALIASES.contains(&maybe_extension) {
251 let mut path = path.to_string();
252 path.insert_str(position_to_insert - 1, suggested_extension);
264 use crate::utils::logger::spawn_logger_thread;
267 fn test_extensions_from_path() {
268 let path = Path::new("bolovo.tar.gz");
270 let extensions: Vec<Extension> = extensions_from_path(path);
271 let formats: Vec<CompressionFormat> = flatten_compression_formats(&extensions);
273 assert_eq!(formats, vec![Tar, Gzip]);
277 /// Test extension parsing for input/output files
278 fn test_separate_known_extensions_from_name() {
279 let _handler = spawn_logger_thread();
281 separate_known_extensions_from_name("file".as_ref()),
282 ("file".as_ref(), vec![])
285 separate_known_extensions_from_name("tar".as_ref()),
286 ("tar".as_ref(), vec![])
289 separate_known_extensions_from_name(".tar".as_ref()),
290 (".tar".as_ref(), vec![])
293 separate_known_extensions_from_name("file.tar".as_ref()),
294 ("file".as_ref(), vec![Extension::new(&[Tar], "tar")])
297 separate_known_extensions_from_name("file.tar.gz".as_ref()),
300 vec![Extension::new(&[Tar], "tar"), Extension::new(&[Gzip], "gz")]
304 separate_known_extensions_from_name(".tar.gz".as_ref()),
305 (".tar".as_ref(), vec![Extension::new(&[Gzip], "gz")])
310 /// Test extension parsing of `--format FORMAT`
311 fn test_parse_of_format_flag() {
313 parse_format_flag(OsStr::new("tar")).unwrap(),
314 vec![Extension::new(&[Tar], "tar")]
317 parse_format_flag(OsStr::new(".tar")).unwrap(),
318 vec![Extension::new(&[Tar], "tar")]
321 parse_format_flag(OsStr::new("tar.gz")).unwrap(),
322 vec![Extension::new(&[Tar], "tar"), Extension::new(&[Gzip], "gz")]
325 parse_format_flag(OsStr::new(".tar.gz")).unwrap(),
326 vec![Extension::new(&[Tar], "tar"), Extension::new(&[Gzip], "gz")]
329 parse_format_flag(OsStr::new("..tar..gz.....")).unwrap(),
330 vec![Extension::new(&[Tar], "tar"), Extension::new(&[Gzip], "gz")]
333 assert!(parse_format_flag(OsStr::new("../tar.gz")).is_err());
334 assert!(parse_format_flag(OsStr::new("targz")).is_err());
335 assert!(parse_format_flag(OsStr::new("tar.gz.unknown")).is_err());
336 assert!(parse_format_flag(OsStr::new(".tar.gz.unknown")).is_err());
337 assert!(parse_format_flag(OsStr::new(".tar.!@#.gz")).is_err());
341 fn builds_suggestion_correctly() {
342 assert_eq!(build_archive_file_suggestion(Path::new("linux.png"), ".tar"), None);
344 build_archive_file_suggestion(Path::new("linux.xz.gz.zst"), ".tar").unwrap(),
345 "linux.tar.xz.gz.zst"
348 build_archive_file_suggestion(Path::new("linux.pkg.xz.gz.zst"), ".tar").unwrap(),
349 "linux.pkg.tar.xz.gz.zst"
352 build_archive_file_suggestion(Path::new("linux.pkg.zst"), ".tar").unwrap(),
356 build_archive_file_suggestion(Path::new("linux.pkg.info.zst"), ".tar").unwrap(),
357 "linux.pkg.info.tar.zst"