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 /// A wrapper around `CompressionFormat` that allows combinations like `tgz`
11 #[derive(Debug, Clone, Eq)]
13 pub struct Extension {
14 /// One extension like "tgz" can be made of multiple CompressionFormats ([Tar, Gz])
15 pub compression_formats: &'static [CompressionFormat],
16 /// The input text for this extension, like "tgz", "tar" or "xz"
20 // The display_text should be ignored when comparing extensions
21 impl PartialEq for Extension {
22 fn eq(&self, other: &Self) -> bool {
23 self.compression_formats == other.compression_formats
29 /// Will panic if `formats` is empty
30 pub fn new(formats: &'static [CompressionFormat], text: impl ToString) -> Self {
31 assert!(!formats.is_empty());
33 compression_formats: formats,
34 display_text: text.to_string(),
38 /// Checks if the first format in `compression_formats` is an archive
39 pub fn is_archive(&self) -> bool {
40 // Safety: we check that `compression_formats` is not empty in `Self::new`
41 self.compression_formats[0].is_archive_format()
45 impl fmt::Display for Extension {
46 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47 self.display_text.fmt(f)
51 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
52 /// Accepted extensions for input and output
53 pub enum CompressionFormat {
64 /// tar, tgz, tbz, tbz2, txz, tlz4, tlzma, tsz, tzst
72 impl CompressionFormat {
73 /// Currently supported archive formats are .tar (and aliases to it) and .zip
74 fn is_archive_format(&self) -> bool {
75 // Keep this match like that without a wildcard `_` so we don't forget to update it
88 pub const SUPPORTED_EXTENSIONS: &[&str] = &[
89 "tar", "tgz", "tbz", "tlz4", "txz", "tzlma", "tsz", "tzst", "zip", "bz", "bz2", "gz", "lz4", "xz", "lzma", "sz",
93 fn to_extension(ext: &[u8]) -> Option<Extension> {
97 b"tgz" => &[Tar, Gzip],
98 b"tbz" | b"tbz2" => &[Tar, Bzip],
99 b"tlz4" => &[Tar, Lz4],
100 b"txz" | b"tlzma" => &[Tar, Lzma],
101 b"tsz" => &[Tar, Snappy],
102 b"tzst" => &[Tar, Zstd],
104 b"bz" | b"bz2" => &[Bzip],
107 b"xz" | b"lzma" => &[Lzma],
116 fn split_extension(name: &mut &[u8]) -> Option<Extension> {
117 let (new_name, ext) = name.rsplit_once_str(b".")?;
118 if matches!(new_name, b"" | b"." | b"..") {
121 let ext = to_extension(ext)?;
126 pub fn parse_format(fmt: &OsStr) -> crate::Result<Vec<Extension>> {
127 let fmt = <[u8] as ByteSlice>::from_os_str(fmt).ok_or_else(|| Error::InvalidFormat {
128 reason: "Invalid UTF-8".into(),
131 let mut extensions = Vec::new();
132 for extension in fmt.split_str(b".") {
133 let extension = to_extension(extension).ok_or_else(|| Error::InvalidFormat {
134 reason: format!("Unsupported extension: {}", extension.to_str_lossy()),
136 extensions.push(extension);
142 /// Extracts extensions from a path.
144 /// Returns both the remaining path and the list of extension objects
145 pub fn separate_known_extensions_from_name(path: &Path) -> (&Path, Vec<Extension>) {
146 let mut extensions = vec![];
148 let Some(mut name) = path.file_name().and_then(<[u8] as ByteSlice>::from_os_str) else {
149 return (path, extensions);
152 // While there is known extensions at the tail, grab them
153 while let Some(extension) = split_extension(&mut name) {
154 extensions.insert(0, extension);
157 if let Ok(name) = name.to_str() {
158 let file_stem = name.trim_matches('.');
159 if SUPPORTED_EXTENSIONS.contains(&file_stem) {
160 warning!("Received a file with name '{file_stem}', but {file_stem} was expected as the extension.");
164 (name.to_path().unwrap(), extensions)
167 /// Extracts extensions from a path, return only the list of extension objects
168 pub fn extensions_from_path(path: &Path) -> Vec<Extension> {
169 let (_, extensions) = separate_known_extensions_from_name(path);
173 // Panics if formats has an empty list of compression formats
174 pub fn split_first_compression_format(formats: &[Extension]) -> (CompressionFormat, Vec<CompressionFormat>) {
175 let mut extensions: Vec<CompressionFormat> = flatten_compression_formats(formats);
176 let first_extension = extensions.remove(0);
177 (first_extension, extensions)
180 pub fn flatten_compression_formats(extensions: &[Extension]) -> Vec<CompressionFormat> {
183 .flat_map(|extension| extension.compression_formats.iter())
188 /// Builds a suggested output file in scenarios where the user tried to compress
189 /// a folder into a non-archive compression format, for error message purposes
191 /// E.g.: `build_suggestion("file.bz.xz", ".tar")` results in `Some("file.tar.bz.xz")`
192 pub fn build_archive_file_suggestion(path: &Path, suggested_extension: &str) -> Option<String> {
193 let path = path.to_string_lossy();
194 let mut rest = &*path;
195 let mut position_to_insert = 0;
197 // Walk through the path to find the first supported compression extension
198 while let Some(pos) = rest.find('.') {
199 // Use just the text located after the dot we found
200 rest = &rest[pos + 1..];
201 position_to_insert += pos + 1;
203 // If the string contains more chained extensions, clip to the immediate one
204 let maybe_extension = {
205 let idx = rest.find('.').unwrap_or(rest.len());
209 // If the extension we got is a supported extension, generate the suggestion
210 // at the position we found
211 if SUPPORTED_EXTENSIONS.contains(&maybe_extension) {
212 let mut path = path.to_string();
213 path.insert_str(position_to_insert - 1, suggested_extension);
229 fn test_extensions_from_path() {
230 use CompressionFormat::*;
231 let path = Path::new("bolovo.tar.gz");
233 let extensions: Vec<Extension> = extensions_from_path(path);
234 let formats: Vec<CompressionFormat> = flatten_compression_formats(&extensions);
236 assert_eq!(formats, vec![Tar, Gzip]);
240 fn builds_suggestion_correctly() {
241 assert_eq!(build_archive_file_suggestion(Path::new("linux.png"), ".tar"), None);
243 build_archive_file_suggestion(Path::new("linux.xz.gz.zst"), ".tar").unwrap(),
244 "linux.tar.xz.gz.zst"
247 build_archive_file_suggestion(Path::new("linux.pkg.xz.gz.zst"), ".tar").unwrap(),
248 "linux.pkg.tar.xz.gz.zst"
251 build_archive_file_suggestion(Path::new("linux.pkg.zst"), ".tar").unwrap(),
255 build_archive_file_suggestion(Path::new("linux.pkg.info.zst"), ".tar").unwrap(),
256 "linux.pkg.info.tar.zst"