Implement includes and setting a time zone

This commit is contained in:
Joscha 2021-11-22 00:15:18 +01:00
parent b4b8dd53e0
commit 36aa6abcb9
3 changed files with 105 additions and 28 deletions

View file

@ -19,9 +19,16 @@ pub struct Files {
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{0}")]
IoError(#[from] io::Error),
Io(#[from] io::Error),
#[error("{0}")]
ParseError(#[from] parse::Error),
Parse(#[from] parse::Error),
#[error("{file1} has time zone {tz1} but {file2} has time zone {tz2}")]
TzConflict {
file1: PathBuf,
tz1: Tz,
file2: PathBuf,
tz2: Tz,
},
}
pub type Result<T> = result::Result<T, Error>;
@ -33,30 +40,56 @@ impl Files {
timezone: None,
};
new.load_file(path.to_owned())?;
new.load_file(path)?;
new.determine_timezone()?;
Ok(new)
}
fn load_file(&mut self, path: PathBuf) -> Result<()> {
fn load_file(&mut self, path: &Path) -> Result<()> {
let canon_path = path.canonicalize()?;
if self.files.contains_key(&canon_path) {
// We've already loaded this exact file.
return Ok(());
}
let content = fs::read_to_string(&path)?;
let content = fs::read_to_string(path)?;
let file = parse::parse(path, &content)?;
let includes = file.includes.clone();
self.files.insert(canon_path, file);
// TODO Also load all included files
for include in includes {
self.load_file(&include)?;
}
Ok(())
}
fn determine_timezone(&mut self) -> Result<()> {
// TODO Implement once files can specify time zones
let mut found: Option<(PathBuf, Tz)> = None;
for file in self.files.values() {
if let Some(file_tz) = file.timezone {
if let Some((found_name, found_tz)) = &found {
if *found_tz != file_tz {
return Err(Error::TzConflict {
file1: found_name.clone(),
tz1: *found_tz,
file2: file.name.clone(),
tz2: file_tz,
});
}
} else {
found = Some((file.name.clone(), file_tz));
}
}
}
if let Some((_, tz)) = found {
self.timezone = Some(tz);
}
Ok(())
}
}