use std::io::Read;
use std::path::{Path, PathBuf};
use super::archive::trim_bom;
use super::{Chart, Error, File, flavor_of, load_files};
use crate::chart::ignore::{HELM_IGNORE, Rules};
pub(super) fn load_dir(dir: &Path, budget: i64) -> Result<Chart, Error> {
let chart_yaml = dir.join("Chart.yaml");
let data = std::fs::read(&chart_yaml).map_err(|source| Error::NoChart {
path: chart_yaml,
source,
})?;
let flavor = flavor_of(&data)?;
let ignore_file = dir.join(HELM_IGNORE);
let mut rules = if ignore_file.exists() {
let text = std::fs::read(&ignore_file).map_err(|source| Error::Io {
path: ignore_file,
source,
})?;
Rules::parse(&String::from_utf8_lossy(&text))?
} else {
Rules::empty()
};
let mut files = Vec::new();
let mut remaining = budget;
rules.add_defaults();
let mut ancestors = vec![dir.canonicalize().map_err(|source| Error::Io {
path: dir.to_owned(),
source,
})?];
walk(
dir,
"",
&rules,
(budget, &mut remaining),
&mut ancestors,
&mut files,
)?;
load_files(files, flavor)
}
fn walk(
dir: &Path,
prefix: &str,
rules: &Rules,
(budget, remaining): (i64, &mut i64),
ancestors: &mut Vec<PathBuf>,
files: &mut Vec<File>,
) -> Result<(), Error> {
let io = |path: &Path| {
let path = path.to_owned();
move |source| Error::Io { path, source }
};
let mut names: Vec<String> = std::fs::read_dir(dir)
.map_err(io(dir))?
.map(|e| e.map(|e| e.file_name().to_string_lossy().into_owned()))
.collect::<Result<_, _>>()
.map_err(io(dir))?;
names.sort();
for name in names {
let path = dir.join(&name);
let relative = format!("{prefix}{name}");
let meta = std::fs::metadata(&path).map_err(io(&path))?;
if meta.is_dir() {
if !rules.ignore(&relative, true) {
let real = path.canonicalize().map_err(io(&path))?;
if ancestors.contains(&real) {
return Err(Error::SymlinkCycle { path });
}
ancestors.push(real);
walk(
&path,
&format!("{relative}/"),
rules,
(budget, remaining),
ancestors,
files,
)?;
ancestors.pop();
}
continue;
}
if rules.ignore(&relative, false) {
continue;
}
if !meta.is_file() {
return Err(Error::Archive(format!(
"cannot load irregular file {} as it has file mode type bits set",
path.display()
)));
}
let size = i64::try_from(meta.len()).unwrap_or(i64::MAX);
let too_large = || {
Error::Archive(format!(
"error reading {relative}: chart exceeds maximum decompressed size of {budget} bytes"
))
};
if size > *remaining {
return Err(too_large());
}
let mut data = Vec::new();
std::fs::File::open(&path)
.map_err(io(&path))?
.take(u64::try_from(*remaining).unwrap_or(0) + 1)
.read_to_end(&mut data)
.map_err(io(&path))?;
let read = i64::try_from(data.len()).unwrap_or(i64::MAX);
if read > *remaining {
return Err(too_large());
}
*remaining -= read;
files.push(File {
name: relative,
data: trim_bom(data),
mod_time: None,
});
}
Ok(())
}