1 //! Our representation of all the supported compression formats.
3 use std::{ffi::OsStr, fmt, path::Path};
7 use self::CompressionFormat::*;
8 use crate::{error::Error, warning};
10 pub const SUPPORTED_EXTENSIONS: &[&str] = &[
11 "tar", "zip", "bz", "bz2", "gz", "lz4", "xz", "lzma", "sz", "zst", "rar", "7z",
13 pub const SUPPORTED_ALIASES: &[&str] = &["tgz", "tbz", "tlz4", "txz", "tzlma", "tsz", "tzst"];
14 pub const PRETTY_SUPPORTED_EXTENSIONS: &str = "tar, zip, bz, bz2, gz, lz4, xz, lzma, sz, zst, rar";
15 pub const PRETTY_SUPPORTED_ALIASES: &str = "tgz, tbz, tlz4, txz, tzlma, tsz, tzst";
17 /// A wrapper around `CompressionFormat` that allows combinations like `tgz`
18 #[derive(Debug, Clone, Eq)]
20 pub struct Extension {
21 /// One extension like "tgz" can be made of multiple CompressionFormats ([Tar, Gz])
22 pub compression_formats: &'static [CompressionFormat],
23 /// The input text for this extension, like "tgz", "tar" or "xz"
27 // The display_text should be ignored when comparing extensions
28 impl PartialEq for Extension {
29 fn eq(&self, other: &Self) -> bool {
30 self.compression_formats == other.compression_formats
36 /// Will panic if `formats` is empty
37 pub fn new(formats: &'static [CompressionFormat], text: impl ToString) -> Self {
38 assert!(!formats.is_empty());
40 compression_formats: formats,
41 display_text: text.to_string(),
45 /// Checks if the first format in `compression_formats` is an archive
46 pub fn is_archive(&self) -> bool {
47 // Safety: we check that `compression_formats` is not empty in `Self::new`
48 self.compression_formats[0].is_archive_format()
52 impl fmt::Display for Extension {
53 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54 self.display_text.fmt(f)
58 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
59 /// Accepted extensions for input and output
60 pub enum CompressionFormat {
71 /// tar, tgz, tbz, tbz2, txz, tlz4, tlzma, tsz, tzst
83 impl CompressionFormat {
84 /// Currently supported archive formats are .tar (and aliases to it) and .zip
85 fn is_archive_format(&self) -> bool {
86 // Keep this match like that without a wildcard `_` so we don't forget to update it
88 Tar | Zip | Rar | SevenZip => true,
99 fn to_extension(ext: &[u8]) -> Option<Extension> {
103 b"tgz" => &[Tar, Gzip],
104 b"tbz" | b"tbz2" => &[Tar, Bzip],
105 b"tlz4" => &[Tar, Lz4],
106 b"txz" | b"tlzma" => &[Tar, Lzma],
107 b"tsz" => &[Tar, Snappy],
108 b"tzst" => &[Tar, Zstd],
110 b"bz" | b"bz2" => &[Bzip],
113 b"xz" | b"lzma" => &[Lzma],
117 b"7z" => &[SevenZip],
124 fn split_extension(name: &mut &[u8]) -> Option<Extension> {
125 let (new_name, ext) = name.rsplit_once_str(b".")?;
126 if matches!(new_name, b"" | b"." | b"..") {
129 let ext = to_extension(ext)?;
134 pub fn parse_format(fmt: &OsStr) -> crate::Result<Vec<Extension>> {
135 let fmt = <[u8] as ByteSlice>::from_os_str(fmt).ok_or_else(|| Error::InvalidFormat {
136 reason: "Invalid UTF-8".into(),
139 let mut extensions = Vec::new();
140 for extension in fmt.split_str(b".") {
141 let extension = to_extension(extension).ok_or_else(|| Error::InvalidFormat {
142 reason: format!("Unsupported extension: {}", extension.to_str_lossy()),
144 extensions.push(extension);
150 /// Extracts extensions from a path.
152 /// Returns both the remaining path and the list of extension objects
153 pub fn separate_known_extensions_from_name(path: &Path) -> (&Path, Vec<Extension>) {
154 let mut extensions = vec![];
156 let Some(mut name) = path.file_name().and_then(<[u8] as ByteSlice>::from_os_str) else {
157 return (path, extensions);
160 // While there is known extensions at the tail, grab them
161 while let Some(extension) = split_extension(&mut name) {
162 extensions.insert(0, extension);
165 if let Ok(name) = name.to_str() {
166 let file_stem = name.trim_matches('.');
167 if SUPPORTED_EXTENSIONS.contains(&file_stem) || SUPPORTED_ALIASES.contains(&file_stem) {
168 warning!("Received a file with name '{file_stem}', but {file_stem} was expected as the extension.");
172 (name.to_path().unwrap(), extensions)
175 /// Extracts extensions from a path, return only the list of extension objects
176 pub fn extensions_from_path(path: &Path) -> Vec<Extension> {
177 let (_, extensions) = separate_known_extensions_from_name(path);
181 // Panics if formats has an empty list of compression formats
182 pub fn split_first_compression_format(formats: &[Extension]) -> (CompressionFormat, Vec<CompressionFormat>) {
183 let mut extensions: Vec<CompressionFormat> = flatten_compression_formats(formats);
184 let first_extension = extensions.remove(0);
185 (first_extension, extensions)
188 pub fn flatten_compression_formats(extensions: &[Extension]) -> Vec<CompressionFormat> {
191 .flat_map(|extension| extension.compression_formats.iter())
196 /// Builds a suggested output file in scenarios where the user tried to compress
197 /// a folder into a non-archive compression format, for error message purposes
199 /// E.g.: `build_suggestion("file.bz.xz", ".tar")` results in `Some("file.tar.bz.xz")`
200 pub fn build_archive_file_suggestion(path: &Path, suggested_extension: &str) -> Option<String> {
201 let path = path.to_string_lossy();
202 let mut rest = &*path;
203 let mut position_to_insert = 0;
205 // Walk through the path to find the first supported compression extension
206 while let Some(pos) = rest.find('.') {
207 // Use just the text located after the dot we found
208 rest = &rest[pos + 1..];
209 position_to_insert += pos + 1;
211 // If the string contains more chained extensions, clip to the immediate one
212 let maybe_extension = {
213 let idx = rest.find('.').unwrap_or(rest.len());
217 // If the extension we got is a supported extension, generate the suggestion
218 // at the position we found
219 if SUPPORTED_EXTENSIONS.contains(&maybe_extension) || SUPPORTED_ALIASES.contains(&maybe_extension) {
220 let mut path = path.to_string();
221 path.insert_str(position_to_insert - 1, suggested_extension);
237 fn test_extensions_from_path() {
238 let path = Path::new("bolovo.tar.gz");
240 let extensions: Vec<Extension> = extensions_from_path(path);
241 let formats: Vec<CompressionFormat> = flatten_compression_formats(&extensions);
243 assert_eq!(formats, vec![Tar, Gzip]);
247 fn builds_suggestion_correctly() {
248 assert_eq!(build_archive_file_suggestion(Path::new("linux.png"), ".tar"), None);
250 build_archive_file_suggestion(Path::new("linux.xz.gz.zst"), ".tar").unwrap(),
251 "linux.tar.xz.gz.zst"
254 build_archive_file_suggestion(Path::new("linux.pkg.xz.gz.zst"), ".tar").unwrap(),
255 "linux.pkg.tar.xz.gz.zst"
258 build_archive_file_suggestion(Path::new("linux.pkg.zst"), ".tar").unwrap(),
262 build_archive_file_suggestion(Path::new("linux.pkg.info.zst"), ".tar").unwrap(),
263 "linux.pkg.info.tar.zst"