//! The store: `directory.json`, `devices.json` and `roads/` (docs/FORMATS.md, "The store"). use crate::id::RoadId; use crate::problem::Problem; use crate::road::Road; use crate::rules as r; use crate::snapshot::{DEVICES_FILE, DIRECTORY_FILE, Devices, Directory}; use std::collections::BTreeMap; use std::path::Path; pub const ROADS_DIR: &str = "roads"; pub const MAX_ROADS: usize = 10_000; /// Everything the compiler reads, already parsed. Roads with errors are not in `roads`; their problems are. #[derive(Debug, Clone, Default)] pub struct Store { pub roads: Vec, pub directory: Option, pub devices: Option, pub problems: Vec, } impl Store { /// Builds a store from bytes: `(file name inside roads/, contents)`, and the two snapshots (`None`: missing). pub fn from_parts( road_files: &[(String, Vec)], directory: Option<&[u8]>, devices: Option<&[u8]>, ) -> Store { let mut store = Store::default(); match directory { None => store.problems.push(Problem::error( DIRECTORY_FILE, None, r::SNAPSHOT_JSON, "missing", )), Some(b) => match Directory::parse(b) { Ok((d, dangling)) => { store.directory = Some(d); store.problems.extend(dangling); } Err(p) => store.problems.extend(p), }, } match devices { None => store.problems.push(Problem::error( DEVICES_FILE, None, r::SNAPSHOT_JSON, "missing", )), Some(b) => match Devices::parse(b, store.directory.as_ref()) { Ok((d, dangling)) => { store.devices = Some(d); store.problems.extend(dangling); } Err(p) => store.problems.extend(p), }, } let mut files: Vec<&(String, Vec)> = road_files.iter().collect(); files.sort_by(|a, b| a.0.cmp(&b.0)); if files.len() > MAX_ROADS { store.problems.push(Problem::error( ROADS_DIR, None, r::FILE_COUNT, format!("more than {MAX_ROADS} road files"), )); return store; } let mut by_id: BTreeMap> = BTreeMap::new(); for (name, bytes) in files { let path = format!("{ROADS_DIR}/{name}"); match Road::parse(&path, bytes) { Ok(road) => by_id.entry(road.id.clone()).or_default().push(road), Err(p) => store.problems.extend(p), } } for (id, roads) in by_id { if roads.len() == 1 { store.roads.extend(roads); continue; } let paths: Vec<&str> = roads.iter().map(|r| r.path.as_str()).collect(); for road in &roads { store.problems.push( Problem::error( &road.path, Some("id"), r::ID_DUPLICATE, format!( "id {id} is used by {}; none of them grants anything", paths.join(" and ") ), ) .at(road.line_of("id")), ); } } store } /// Reads a store folder. Only the three names are read; anything that is not a regular `.md` file inside /// `roads/` is a problem and is not read. pub fn load_dir(root: &Path) -> std::io::Result { let directory = read_optional(&root.join(DIRECTORY_FILE))?; let devices = read_optional(&root.join(DEVICES_FILE))?; let mut files = Vec::new(); let mut problems = Vec::new(); let roads = root.join(ROADS_DIR); // A missing roads/ folder means no road grants anything, kill switches included: say so (QA F-07). The // folder itself is never followed through a symbolic link, like the entries inside it. let readable = match std::fs::symlink_metadata(&roads) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => { problems.push(Problem::error( ROADS_DIR, None, r::STORE_ROADS, "missing: there is no roads/ folder, so no road grants anything and no kill switch is on", )); false } Err(e) => return Err(e), Ok(m) if !m.file_type().is_dir() => { let what = if m.file_type().is_symlink() { "a symbolic link" } else { "not a folder" }; problems.push(Problem::error( ROADS_DIR, None, r::STORE_ROADS, format!("{what}; roads/ must be a real folder, so no road was read"), )); false } Ok(_) => true, }; if readable { for entry in std::fs::read_dir(&roads)? { let entry = entry?; let name = entry.file_name().to_string_lossy().into_owned(); let ty = entry.file_type()?; let path = format!("{ROADS_DIR}/{name}"); if !ty.is_file() { let what = if ty.is_symlink() { "a symbolic link" } else { "not a regular file" }; problems.push(Problem::error( &path, None, r::FILE_KIND, format!("{what}; roads/ holds only road files"), )); continue; } if !name.ends_with(".md") { problems.push(Problem::error( &path, None, r::FILE_KIND, "not a road file (.md); roads/ holds only road files", )); continue; } if entry.metadata()?.len() > crate::road::MAX_FILE as u64 { problems.push(Problem::error( &path, None, r::FILE_SIZE, format!("larger than {} KiB", crate::road::MAX_FILE / 1024), )); continue; } files.push((name, std::fs::read(entry.path())?)); } } let mut store = Store::from_parts(&files, directory.as_deref(), devices.as_deref()); store.problems.extend(problems); store.problems.sort(); Ok(store) } } fn read_optional(path: &Path) -> std::io::Result>> { match std::fs::read(path) { Ok(b) => Ok(Some(b)), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e), } }