use std::path::{Path, PathBuf};
use indexmap::IndexMap;
use crate::{
Error, Result,
load::{is_cicada_path, is_missing, read_file},
};
pub(crate) fn read_includes(
folder: &Path,
include_file_name: &str,
) -> Result<Vec<PathBuf>> {
if include_file_name.is_empty() {
return Ok(Vec::new());
}
let contents = match read_file(&folder.join(include_file_name)) {
Ok(contents) => contents,
Err(Error::FileOpen { ref e, .. }) if is_missing(e) => {
return Ok(Vec::new());
}
Err(e) => return Err(e),
};
let lines = contents
.split('\n')
.map(|line| line.trim())
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.map(|line| {
line
.split_once(" #")
.or_else(|| line.split_once("\t#"))
.map(|res| res.0.trim())
.unwrap_or(line)
});
let mut includes = IndexMap::<PathBuf, PathBuf>::new();
for line in lines {
if is_cicada_path(Path::new(line)) {
let path = PathBuf::from(line);
includes.entry(path.clone()).or_insert(path);
continue;
}
let path = folder.join(line);
let key = match path.canonicalize() {
Ok(key) => key,
Err(e) if is_missing(&e) => continue,
Err(e) => return Err(Error::ReadPathMetaData { path, e }),
};
includes.entry(key).or_insert(path);
}
Ok(includes.into_values().collect())
}