use pretty_assertions::assert_eq;
use super::*;
#[test]
fn test_archive_content_files_tar_hashes_regular_files() {
let dir = tempfile::tempdir().unwrap();
let archive_path = dir.path().join("tool.tar");
{
let file = File::create(&archive_path).unwrap();
let mut builder = jdx_tar::Builder::new(file);
let mut header = jdx_tar::Header::new_gnu(EntryType::File);
header.set_size(4);
header.set_mode(0o755);
builder
.append_data(&mut header, "pkg/tool", &b"tool"[..])
.unwrap();
builder.finish().unwrap();
}
let files = archive_content_files(&archive_path, ExtractionFormat::Tar, 1).unwrap();
assert_eq!(files.len(), 1);
assert_eq!(files[0].name, "tool");
assert_eq!(files[0].sha256, hex::encode(Sha256::digest(b"tool")));
}
#[test]
fn test_archive_content_files_tar_rejects_symlink() {
let dir = tempfile::tempdir().unwrap();
let archive_path = dir.path().join("tool.tar");
{
let file = File::create(&archive_path).unwrap();
let mut builder = jdx_tar::Builder::new(file);
let mut header = jdx_tar::Header::new_gnu(EntryType::Symlink);
header.set_mode(0o777);
builder
.append_link(&mut header, "tool-link", "tool")
.unwrap();
builder.finish().unwrap();
}
let err = archive_content_files(&archive_path, ExtractionFormat::Tar, 0).unwrap_err();
assert!(err.to_string().contains("non-regular archive entry"));
}
#[test]
fn test_archive_content_files_zip_rejects_symlink() {
for name in ["tool-link", "tool-link/", "tool-link\\"] {
let dir = tempfile::tempdir().unwrap();
let archive_path = dir.path().join("tool.zip");
let options = zip::write::SimpleFileOptions::default();
let mut zip = zip::ZipWriter::new(File::create(&archive_path).unwrap());
zip.start_file("tool", options).unwrap();
zip.write_all(b"tool").unwrap();
zip.add_symlink(name, "tool", options).unwrap();
zip.finish().unwrap();
let err = archive_content_files(&archive_path, ExtractionFormat::Zip, 0).unwrap_err();
assert!(
err.to_string().contains("symlink archive entry"),
"{name}: {err}"
);
}
}
#[test]
fn test_archive_content_files_tar_zst_decodes_a_long_window() {
let dir = tempfile::tempdir().unwrap();
let archive_path = dir.path().join("tool.tar.zst");
let mut tar = Vec::new();
{
let mut builder = jdx_tar::Builder::new(&mut tar);
let mut header = jdx_tar::Header::new_gnu(EntryType::File);
header.set_size(4);
header.set_mode(0o755);
builder
.append_data(&mut header, "pkg/tool", &b"tool"[..])
.unwrap();
builder.finish().unwrap();
}
let mut encoder = zstd::Encoder::new(Vec::new(), 1).unwrap();
encoder.write_all(&tar).unwrap();
let mut zst = encoder.finish().unwrap();
assert_eq!(&zst[..4], &[0x28, 0xb5, 0x2f, 0xfd]);
assert_eq!(
zst[4] & 0x23,
0,
"expected no single-segment flag or dictionary id"
);
zst[5] = 20 << 3;
fs::write(&archive_path, &zst).unwrap();
let files = archive_content_files(&archive_path, ExtractionFormat::TarZst, 1).unwrap();
assert_eq!(files.len(), 1);
assert_eq!(files[0].name, "tool");
}
#[test]
fn test_archive_content_files_zip_charges_entries_that_share_a_member() {
use std::io::Write;
let dir = tempfile::tempdir().unwrap();
let archive_path = dir.path().join("tool.zip");
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for name in ["a", "b", "c"] {
zip.start_file(name, zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(b"tool").unwrap();
}
let mut bytes = zip.finish().unwrap().into_inner();
for i in 0..bytes.len() - 46 {
if bytes[i..].starts_with(b"PK\x01\x02") {
bytes[i + 42..i + 46].fill(0);
}
}
fs::write(&archive_path, &bytes).unwrap();
let files = archive_content_files_zip(&archive_path, 0, 12).unwrap();
assert_eq!(files.len(), 3);
for file in files {
assert_eq!(file.sha256, hex::encode(Sha256::digest(b"tool")));
}
let err = archive_content_files_zip(&archive_path, 0, 11).unwrap_err();
assert!(err.to_string().contains("unpacks to more than"), "{err}");
}
#[test]
fn test_archive_content_files_tar_rejects_huge_sparse_member() {
let dir = tempfile::tempdir().unwrap();
let archive_path = dir.path().join("tool.tar");
let mut builder = jdx_tar::Builder::new(Vec::new());
let pax = b"33 GNU.sparse.size=1099511627776\n\
26 GNU.sparse.numblocks=1\n\
22 GNU.sparse.map=0,4\n";
let mut pax_header = jdx_tar::Header::new_gnu(EntryType::Other(b'X'));
pax_header.set_size(pax.len() as u64);
builder
.append_data(&mut pax_header, "pax-sparse", pax.as_slice())
.unwrap();
let mut header = jdx_tar::Header::new_gnu(EntryType::File);
header.set_size(4);
header.set_mode(0o755);
builder
.append_data(&mut header, "tool", &b"tool"[..])
.unwrap();
let mut archive = builder.into_inner().unwrap();
archive[156] = b'x';
archive[257..265].copy_from_slice(b"ustar\x0000");
archive[148..156].fill(b' ');
let checksum = archive[..512]
.iter()
.map(|byte| u64::from(*byte))
.sum::<u64>();
archive[148..156].copy_from_slice(format!("{checksum:06o}\0 ").as_bytes());
fs::write(&archive_path, archive).unwrap();
let err = archive_content_files(&archive_path, ExtractionFormat::Tar, 0).unwrap_err();
assert!(err.to_string().contains("unpacks to more than"), "{err}");
}
#[test]
fn test_extract_archive_tar_strip_preserves_root_files() {
let dir = tempfile::tempdir().unwrap();
let archive_path = dir.path().join("tool.tar");
let dest = dir.path().join("out");
{
let file = File::create(&archive_path).unwrap();
let mut builder = jdx_tar::Builder::new(file);
let mut readme = jdx_tar::Header::new_gnu(EntryType::File);
readme.set_size(6);
readme.set_mode(0o644);
builder
.append_data(&mut readme, "README", &b"readme"[..])
.unwrap();
let mut tool = jdx_tar::Header::new_gnu(EntryType::File);
tool.set_size(4);
tool.set_mode(0o644);
builder
.append_data(&mut tool, "pkg/tool", &b"tool"[..])
.unwrap();
builder.finish().unwrap();
}
extract_archive(
&archive_path,
&dest,
ExtractionFormat::Tar,
&ExtractOptions {
strip_components: 1,
..Default::default()
},
)
.unwrap();
assert_eq!(fs::read(dest.join("README")).unwrap(), b"readme");
assert_eq!(fs::read(dest.join("tool")).unwrap(), b"tool");
assert!(!dest.join("pkg").exists());
}
fn tar_bytes() -> Vec<u8> {
let mut builder = jdx_tar::Builder::new(Vec::new());
let mut header = jdx_tar::Header::new_gnu(EntryType::File);
header.set_size(4);
header.set_mode(0o644);
builder
.append_data(&mut header, "pkg/tool", &b"tool"[..])
.unwrap();
builder.into_inner().unwrap()
}
#[test]
fn test_from_magic_identifies_suffixless_tarballs() {
use std::io::Write;
let tar = tar_bytes();
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gz.write_all(&tar).unwrap();
let mut xz = xz2::write::XzEncoder::new(Vec::new(), 6);
xz.write_all(&tar).unwrap();
let mut bz2 = bzip2::write::BzEncoder::new(Vec::new(), bzip2::Compression::default());
bz2.write_all(&tar).unwrap();
let cases = [
(gz.finish().unwrap(), ExtractionFormat::TarGz),
(xz.finish().unwrap(), ExtractionFormat::TarXz),
(bz2.finish().unwrap(), ExtractionFormat::TarBz2),
(
zstd::encode_all(&tar[..], 0).unwrap(),
ExtractionFormat::TarZst,
),
(tar.clone(), ExtractionFormat::Tar),
];
let dir = tempfile::tempdir().unwrap();
let archive = dir.path().join("v1.0.0");
for (bytes, expected) in cases {
fs::write(&archive, bytes).unwrap();
assert_eq!(
ExtractionFormat::from_magic(&archive).unwrap(),
Some(expected)
);
assert_eq!(
ExtractionFormat::detect(&archive, "v1.0.0").unwrap(),
expected
);
}
}
#[test]
fn test_from_magic_leaves_non_archives_alone() {
use std::io::Write;
let dir = tempfile::tempdir().unwrap();
let archive = dir.path().join("download");
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gz.write_all(&[b'x'; 1024]).unwrap();
fs::write(&archive, gz.finish().unwrap()).unwrap();
assert_eq!(ExtractionFormat::from_magic(&archive).unwrap(), None);
fs::write(&archive, b"\x1f\x8bnot really gzip").unwrap();
assert_eq!(ExtractionFormat::from_magic(&archive).unwrap(), None);
fs::write(&archive, b"#!/bin/sh\necho hi\n").unwrap();
assert_eq!(ExtractionFormat::from_magic(&archive).unwrap(), None);
assert_eq!(
ExtractionFormat::detect(&archive, "download").unwrap(),
ExtractionFormat::Raw
);
fs::write(&archive, b"").unwrap();
assert_eq!(ExtractionFormat::from_magic(&archive).unwrap(), None);
}
#[test]
fn test_detect_prefers_the_file_name() {
let dir = tempfile::tempdir().unwrap();
let archive = dir.path().join("tool.zip");
fs::write(&archive, tar_bytes()).unwrap();
assert_eq!(
ExtractionFormat::detect(&archive, "tool.zip").unwrap(),
ExtractionFormat::Zip
);
}
#[test]
fn test_display_filename() {
assert_eq!(display_filename("/tmp/mise.toml"), "mise.toml");
assert_eq!(display_filename("/"), "/");
}
#[test]
fn test_replace_path_uses_platform_separators() {
let expanded = replace_path(Path::new("~/a/b"));
let expected = dirs::HOME.join("a").join("b");
assert_eq!(expanded, expected);
assert_eq!(expanded.to_string_lossy(), expected.to_string_lossy());
#[cfg(windows)]
{
let rest = expanded.strip_prefix(*dirs::HOME).unwrap();
assert!(
!rest.to_string_lossy().contains('/'),
"expanded remainder must use `\\`: {}",
expanded.display()
);
}
assert_eq!(replace_path(Path::new("~")), *dirs::HOME);
assert_eq!(
replace_path(Path::new("/cwd/x")).to_string_lossy(),
"/cwd/x"
);
}
#[test]
#[cfg(windows)]
fn test_pathbuf_hashset_is_separator_insensitive() {
let mut set = std::collections::HashSet::new();
set.insert(PathBuf::from(
r"C:\Users\me\.local/share/mise/installs/go/1/bin",
));
assert!(set.contains(&PathBuf::from(
r"C:\Users\me\.local\share\mise\installs\go\1\bin"
)));
}
#[test]
fn test_paths_eq_exact() {
assert!(paths_eq(Path::new("/foo/bar"), Path::new("/foo/bar")));
assert!(!paths_eq(Path::new("/foo/bar"), Path::new("/foo/baz")));
}
#[test]
#[cfg(any(target_os = "macos", windows))]
fn test_paths_eq_case_insensitive() {
assert!(paths_eq(
Path::new("/Users/Olfway/.local/share/mise/shims"),
Path::new("/Users/olfway/.local/share/mise/shims"),
));
}
#[test]
#[cfg(any(target_os = "macos", windows))]
fn test_paths_eq_trailing_separator() {
assert!(paths_eq(Path::new("/foo/shims"), Path::new("/foo/shims/")));
assert!(paths_eq(Path::new("/foo/shims"), Path::new("/foo//shims"),));
}
#[test]
#[cfg(all(not(windows), not(target_os = "macos")))]
fn test_paths_eq_case_sensitive_on_linux() {
assert!(!paths_eq(Path::new("/foo/bar"), Path::new("/Foo/bar")));
}
#[test]
#[cfg(windows)]
fn test_paths_eq_separator_normalization() {
assert!(paths_eq(
Path::new("C:/Users/foo/shims"),
Path::new("C:\\Users\\foo\\shims"),
));
}
#[test]
fn test_should_strip_components() {
let non_existent_path = Path::new("/non/existent/archive.tar.gz");
let result = should_strip_components(non_existent_path, ExtractionFormat::TarGz);
assert!(result.is_err());
}
#[test]
fn test_inspect_tar_contents_logic() {
let mut components = std::collections::HashMap::new();
components.insert("mydir".to_string(), true);
let result: Vec<(String, bool)> = components.into_iter().collect();
assert_eq!(result.len(), 1);
let (name, is_directory) = &result[0];
assert_eq!(name, "mydir");
assert!(*is_directory);
let should_strip = result.len() == 1 && result[0].1;
assert!(should_strip);
}
#[test]
fn test_inspect_tar_contents_curdir_prefix() {
use flate2::Compression;
use flate2::write::GzEncoder;
use jdx_tar::{Builder, Header};
use tempfile::NamedTempFile;
let temp_file = NamedTempFile::new().unwrap();
let gz = GzEncoder::new(temp_file.as_file(), Compression::default());
let mut builder = Builder::new(gz);
let mut header = Header::new_gnu(EntryType::File);
header.set_size(0);
header.set_mode(0o755);
builder
.append_data(&mut header.clone(), "./dir1/file1", std::io::empty())
.unwrap();
builder
.append_data(&mut header.clone(), "./dir2/file2", std::io::empty())
.unwrap();
builder
.append_data(&mut header.clone(), "./standalone", std::io::empty())
.unwrap();
let gz = builder.into_inner().unwrap();
gz.finish().unwrap();
let result = inspect_tar_contents(temp_file.path(), ExtractionFormat::TarGz).unwrap();
assert_eq!(
result.len(),
2,
"Expected 2 top-level entries, got: {:?}",
result
);
let names: std::collections::HashSet<_> = result.iter().map(|(n, _)| n.as_str()).collect();
assert!(names.contains("dir1"), "Should contain dir1");
assert!(names.contains("dir2"), "Should contain dir2");
assert!(!names.contains("."), "Should NOT contain '.' (CurDir)");
for (name, is_dir) in &result {
assert!(*is_dir, "{} should be marked as directory", name);
}
let should_strip = should_strip_components(temp_file.path(), ExtractionFormat::TarGz).unwrap();
assert!(
!should_strip,
"Should NOT strip components for multi-entry archive"
);
}
#[test]
fn test_inspect_tar_contents_stops_at_second_top_level_entry() {
let dir = tempfile::tempdir().unwrap();
let archive_path = dir.path().join("tool.tar");
let mut builder = jdx_tar::Builder::new(Vec::new());
let mut header = jdx_tar::Header::new_gnu(EntryType::File);
header.set_size(0);
header.set_mode(0o755);
for name in ["pkg/a", "pkg/b", "other"] {
builder
.append_data(&mut header.clone(), name, std::io::empty())
.unwrap();
}
let mut archive = builder.into_inner().unwrap();
archive.truncate(3 * 512);
archive.extend([b'x'; 512]);
fs::write(&archive_path, &archive).unwrap();
let mut contents = inspect_tar_contents(&archive_path, ExtractionFormat::Tar).unwrap();
contents.sort();
assert_eq!(
contents,
vec![("other".to_string(), false), ("pkg".to_string(), true)]
);
assert!(!should_strip_components(&archive_path, ExtractionFormat::Tar).unwrap());
archive.drain(2 * 512..3 * 512);
fs::write(&archive_path, &archive).unwrap();
assert!(inspect_tar_contents(&archive_path, ExtractionFormat::Tar).is_err());
}