use std::{
borrow::Cow,
fs::File,
io::{self, Read},
path::Path,
};
pub fn definition(bytes: &[u8]) -> Cow<'_, [u8]> {
let Ok(source) = std::str::from_utf8(bytes) else {
return Cow::Borrowed(bytes);
};
let Ok(mut document) = toml::from_str::<toml::Table>(source) else {
return Cow::Borrowed(bytes);
};
document.remove("annotations");
Cow::Owned(
toml::to_string(&canonical(toml::Value::Table(document)))
.expect("a parsed TOML table serializes")
.into_bytes(),
)
}
fn canonical(value: toml::Value) -> toml::Value {
match value {
toml::Value::Table(table) => toml::Value::Table(
table
.into_iter()
.map(|(key, value)| (key, canonical(value)))
.collect::<std::collections::BTreeMap<_, _>>()
.into_iter()
.collect(),
),
toml::Value::Array(values) => {
toml::Value::Array(values.into_iter().map(canonical).collect())
}
value => value,
}
}
const DOCUMENT_BYTES: u64 = 8 * 1024 * 1024;
const OVERFLOW_PROBE_BYTES: u64 = 1;
pub(crate) fn reader(file: File, path: &Path) -> io::Result<Box<dyn Read>> {
if !path.extension().is_some_and(|ext| ext == "artf")
&& !path.file_name().is_some_and(|name| name == ".artf")
{
return Ok(Box::new(file));
}
let mut bytes = Vec::new();
file.take(DOCUMENT_BYTES + OVERFLOW_PROBE_BYTES)
.read_to_end(&mut bytes)?;
if bytes.len() as u64 > DOCUMENT_BYTES {
return Err(io::Error::other(
"Artifact definition exceeds the 8 MiB file-tool bound.",
));
}
Ok(Box::new(io::Cursor::new(definition(&bytes).into_owned())))
}