use std::io::{Read as _, Write as _};
pub const BUNDLE_KIND: &str = "lineageBundle";
pub const DOMAIN_KIND: &str = "trustDomain";
pub fn closure(head: &str) -> Result<Vec<(String, std::path::PathBuf)>, String> {
let mut out: Vec<(String, std::path::PathBuf)> = Vec::new();
let mut current = std::path::PathBuf::from(head);
for _ in 0..1000 {
let name = current
.file_name()
.ok_or_else(|| format!("캡슐 경로가 이상합니다: {}", current.display()))?
.to_string_lossy()
.into_owned();
if out.iter().any(|(n, _)| *n == name) {
return Err(format!(
"폐쇄집합 파일명 충돌: {name} — 번들은 평면 구조라 같은 이름의 조상을 담을 수 없다"
));
}
let bytes = std::fs::read(¤t)
.map_err(|e| format!("캡슐을 읽을 수 없습니다 - {}: {e}", current.display()))?;
let capsule: serde_json::Value =
serde_json::from_slice(&bytes).map_err(|e| format!("{name}: 캡슐 파싱 실패 - {e}"))?;
out.push((name.clone(), current.clone()));
let parent = &capsule["parent"];
if parent.is_null() {
return Ok(out);
}
let pp = parent["capsule"]
.as_str()
.ok_or_else(|| format!("{name}: parent.capsule 없음"))?;
let pp_path = std::path::PathBuf::from(pp);
current = if pp_path.is_absolute() {
pp_path
} else {
current
.parent()
.unwrap_or(std::path::Path::new("."))
.join(pp_path)
};
}
Err("체인 길이 1000 초과 — 순환 의심".to_string())
}
pub fn zip_put<W: std::io::Write + std::io::Seek>(
zip: &mut zip::ZipWriter<W>,
path: &str,
bytes: &[u8],
) -> Result<(), String> {
zip.start_file::<_, ()>(path, zip::write::FileOptions::default())
.map_err(|e| format!("zip 항목 시작 실패 - {path}: {e}"))?;
zip.write_all(bytes)
.map_err(|e| format!("zip 쓰기 실패 - {path}: {e}"))
}
pub fn read_all(bundle_path: &str) -> Result<std::collections::BTreeMap<String, Vec<u8>>, String> {
let file = std::fs::File::open(bundle_path)
.map_err(|e| format!("번들을 열 수 없습니다 - {bundle_path}: {e}"))?;
let mut archive =
zip::ZipArchive::new(file).map_err(|e| format!("zip 파싱 실패 - {bundle_path}: {e}"))?;
let mut map = std::collections::BTreeMap::new();
for i in 0..archive.len() {
let mut entry = archive
.by_index(i)
.map_err(|e| format!("zip 항목 읽기 실패: {e}"))?;
if entry.is_dir() {
continue;
}
let name = entry
.name()
.map_err(|error| format!("zip 항목 이름 읽기 실패: {error}"))?
.replace('\\', "/");
let mut bytes = Vec::with_capacity(entry.size() as usize);
entry
.read_to_end(&mut bytes)
.map_err(|e| format!("zip 본문 읽기 실패 - {name}: {e}"))?;
map.insert(name, bytes);
}
Ok(map)
}
pub fn parse_trust_domain(
text: &str,
) -> Result<(String, serde_json::Value, Vec<serde_json::Value>), String> {
let v: serde_json::Value =
serde_json::from_str(text).map_err(|e| format!("trust-domain 파싱 실패 - {e}"))?;
if v["kind"] != DOMAIN_KIND {
return Err(format!("kind 가 {DOMAIN_KIND} 가 아닙니다"));
}
let domain = v["domain"].as_str().unwrap_or("(이름 없음)").to_string();
let keyring = v["keyring"].clone();
if keyring.is_null() {
return Err(
"trust-domain 에 keyring 이 필요합니다 (동봉 keyring 은 불신 — F2)".to_string(),
);
}
let checkpoints = v["checkpoints"].as_array().cloned().unwrap_or_default();
Ok((domain, keyring, checkpoints))
}