use anyhow::Result;
use std::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArchiveFormat {
Zip,
TarGz,
}
impl ArchiveFormat {
pub fn extension(&self) -> &str {
match self {
Self::Zip => ".zip",
Self::TarGz => ".tar.gz",
}
}
fn from_infer_kind(kind: &infer::Type) -> Option<Self> {
match kind.extension() {
"zip" => Some(ArchiveFormat::Zip),
"gz" | "tgz" => Some(ArchiveFormat::TarGz),
_ => None,
}
}
}
pub fn detect_format_by_magic(path: &Path) -> Result<ArchiveFormat> {
let kind =
infer::get_from_path(path)?.ok_or_else(|| anyhow::anyhow!("Unable to detect file format"))?;
ArchiveFormat::from_infer_kind(&kind)
.ok_or_else(|| anyhow::anyhow!("Unsupported file format: {}", kind.mime_type()))
}
pub fn generate_docker_filename(arch: &str, format: ArchiveFormat) -> String {
format!("docker-{}{}", arch, format.extension())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_generate_filename() {
assert_eq!(
generate_docker_filename("aarch64", ArchiveFormat::TarGz),
"docker-aarch64.tar.gz"
);
assert_eq!(
generate_docker_filename("x86_64", ArchiveFormat::Zip),
"docker-x86_64.zip"
);
}
#[test]
fn test_archive_format_extension() {
assert_eq!(ArchiveFormat::Zip.extension(), ".zip");
assert_eq!(ArchiveFormat::TarGz.extension(), ".tar.gz");
}
}