use std::io::Read;
use camino::Utf8PathBuf;
use crate::{Content, Decoder};
#[derive(Debug)]
pub enum ReadContent {
Directory,
Symlink {
target: Utf8PathBuf,
},
File {
executable: bool,
size: u64,
offset: u64,
data: Vec<u8>,
},
}
#[allow(clippy::needless_pass_by_value)]
pub fn pretty_print_nar_content<R: Read>(dec: Decoder<R>) -> String {
use ReadContent as RC;
let mut res = vec![];
for (path, content) in decode_nar(&dec) {
let path = match path {
None => "ROOT".into(),
Some(path) => {
let path = path.to_string();
let components: Vec<&str> =
path.split(std::path::MAIN_SEPARATOR).collect();
match components.last() {
Some(basename) => {
let depth = components.len();
let mut indented = String::new();
for _ in 0..depth - 1 {
indented.push_str("│ ");
}
indented.push_str("├── ");
indented.push_str(basename);
indented
}
None => String::new(),
}
}
};
res.push(match content {
RC::Directory => path,
RC::Symlink { target } => format!("{path} -> {target}"),
RC::File {
executable,
size,
offset,
data,
} => format!(
"{path}: executable={executable}, size={size}, offset={offset}, data='{}'",
std::str::from_utf8(&data)
.unwrap()
.escape_default()
),
});
}
res.join("\n")
}
fn decode_nar<R: Read>(dec: &Decoder<R>) -> Vec<(Option<Utf8PathBuf>, ReadContent)> {
let mut res = vec![];
for entry in dec.entries().unwrap() {
let entry = entry.unwrap();
let read_content = match entry.content {
Content::Symlink { target } => ReadContent::Symlink { target },
Content::Directory => ReadContent::Directory,
Content::File {
executable,
size,
offset,
mut data,
} => {
let mut read_data: Vec<u8> = vec![];
data.read_to_end(&mut read_data).unwrap();
ReadContent::File {
executable,
size,
offset,
data: read_data,
}
}
};
res.push((entry.path, read_content));
}
res
}