use std::fs::{self, File};
use std::path::{Path, PathBuf};
use eyre::{Result, WrapErr};
#[tracing::instrument(skip_all, fields(into = %into.display()))]
pub fn extract_zip(zip_path: &Path, into: &Path, strip_prefix: &str) -> Result<()> {
let f = File::open(zip_path).wrap_err_with(|| format!("opening {}", zip_path.display()))?;
let mut archive =
zip::ZipArchive::new(f).wrap_err_with(|| format!("reading zip {}", zip_path.display()))?;
for i in 0..archive.len() {
let mut entry = archive
.by_index(i)
.wrap_err_with(|| format!("reading zip entry {i}"))?;
let Some(raw) = entry.enclosed_name() else {
continue;
};
let Some(rewritten) = rewrite_archive_path(&raw, strip_prefix) else {
continue;
};
let dest = into.join(&rewritten);
if entry.is_dir() {
fs::create_dir_all(&dest).wrap_err_with(|| format!("creating {}", dest.display()))?;
continue;
}
if let Some(parent) = dest.parent() {
fs::create_dir_all(parent)
.wrap_err_with(|| format!("creating {}", parent.display()))?;
}
let mut out =
File::create(&dest).wrap_err_with(|| format!("creating {}", dest.display()))?;
std::io::copy(&mut entry, &mut out)
.wrap_err_with(|| format!("writing {}", dest.display()))?;
#[cfg(unix)]
if let Some(mode) = entry.unix_mode() {
use std::os::unix::fs::PermissionsExt;
let _ = fs::set_permissions(&dest, fs::Permissions::from_mode(mode));
}
}
Ok(())
}
pub fn detect_zip_top_level(zip_path: &Path) -> Result<String> {
let f = File::open(zip_path).wrap_err_with(|| format!("opening {}", zip_path.display()))?;
let mut archive =
zip::ZipArchive::new(f).wrap_err_with(|| format!("reading zip {}", zip_path.display()))?;
let mut top: Option<String> = None;
for i in 0..archive.len() {
let entry = archive
.by_index(i)
.wrap_err_with(|| format!("reading zip entry {i}"))?;
let Some(raw) = entry.enclosed_name() else {
continue;
};
let Some(first) = raw.components().next() else {
continue;
};
let std::path::Component::Normal(os) = first else {
continue;
};
let Some(s) = os.to_str() else {
return Ok(String::new());
};
match &top {
None => top = Some(s.to_owned()),
Some(existing) if existing == s => {}
Some(_) => return Ok(String::new()),
}
}
Ok(top.unwrap_or_default())
}
fn rewrite_archive_path(path: &Path, strip_prefix: &str) -> Option<PathBuf> {
let rewritten = if strip_prefix.is_empty() {
path.to_path_buf()
} else {
match path.strip_prefix(strip_prefix) {
Ok(rest) => rest.to_path_buf(),
Err(_) => path.to_path_buf(),
}
};
if rewritten.as_os_str().is_empty() {
None
} else {
Some(rewritten)
}
}