use std::{fs, io, path::PathBuf};
use gix_path::realpath::MAX_SYMLINKS;
pub mod parse;
#[derive(thiserror::Error, Debug)]
#[allow(missing_docs)]
pub enum Error {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Realpath(#[from] gix_path::realpath::Error),
#[error(transparent)]
Parse(#[from] parse::Error),
#[error("Alternates form a cycle: {} -> {}", .0.iter().map(|p| format!("'{}'", p.display())).collect::<Vec<_>>().join(" -> "), .0.first().expect("more than one directories").display())]
Cycle(Vec<PathBuf>),
}
pub fn resolve(objects_directory: PathBuf, current_dir: &std::path::Path) -> Result<Vec<PathBuf>, Error> {
let mut dirs = vec![(0, objects_directory.clone())];
let mut out = Vec::new();
let mut seen = vec![gix_path::realpath_opts(&objects_directory, current_dir, MAX_SYMLINKS)?];
while let Some((depth, dir)) = dirs.pop() {
match fs::read(dir.join("info").join("alternates")) {
Ok(input) => {
for path in parse::content(&input)?.into_iter() {
let path = objects_directory.join(path);
let path_canonicalized = gix_path::realpath_opts(&path, current_dir, MAX_SYMLINKS)?;
if seen.contains(&path_canonicalized) {
return Err(Error::Cycle(seen));
}
seen.push(path_canonicalized);
dirs.push((depth + 1, path));
}
}
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(err) => return Err(err.into()),
}
if depth != 0 {
out.push(dir);
}
}
Ok(out)
}