//! The entries of one channel, by slot, and the records in keyed ones. use std::collections::BTreeMap; use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; use std::path::Path; use anyhow::{Context, Result, bail}; use serde_json::{Map, Value}; use crate::name; /// Entries by slot name, each exactly as stored. pub type Content = BTreeMap>; /// The entries in `dir`: one file per slot. A missing directory holds none. pub fn read_dir(dir: &Path) -> Result { let mut content = Content::new(); let entries = match std::fs::read_dir(dir) { Ok(entries) => entries, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(content), Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())), }; for entry in entries { let entry = entry?; let slot = entry .file_name() .into_string() .ok() .filter(|slot| name::is_name(slot)); let Some(slot) = slot else { bail!("{}: not a slot's name", entry.path().display()); }; if !entry.file_type()?.is_file() { bail!("{}: not a regular file", entry.path().display()); } let bytes = std::fs::read(entry.path()) .with_context(|| format!("reading {}", entry.path().display()))?; content.insert(slot, bytes); } Ok(content) } /// Writes `content` into `dir`, which is created, with files of `mode` (and /// directories that can be entered where the files can be read). pub fn write_dir(content: &Content, dir: &Path, mode: u32) -> Result<()> { std::fs::DirBuilder::new() .recursive(true) .mode(directory_mode(mode)) .create(dir) .with_context(|| format!("creating {}", dir.display()))?; for (slot, bytes) in content { write_file(&dir.join(slot), bytes, mode)?; } Ok(()) } pub fn write_file(path: &Path, bytes: &[u8], mode: u32) -> Result<()> { use std::io::Write; let mut file = std::fs::OpenOptions::new() .write(true) .create_new(true) .mode(mode) .open(path) .with_context(|| format!("creating {}", path.display()))?; file.write_all(bytes) .with_context(|| format!("writing {}", path.display())) } /// The mode of a directory holding files of `mode`: searchable by whoever can read. pub fn directory_mode(mode: u32) -> u32 { mode | ((mode & 0o444) >> 2) } /// The records of a keyed entry. pub fn records(bytes: &[u8]) -> Result> { match serde_json::from_slice(bytes).context("not JSON")? { Value::Object(records) => Ok(records), _ => bail!("not a JSON object, whose keys would be records"), } } /// A keyed entry holding `records`, in a normal form: keys sorted, indented, a line /// break at the end. pub fn from_records(records: &Map) -> Vec { let mut bytes = serde_json::to_vec_pretty(records).expect("JSON values serialize"); bytes.push(b'\n'); bytes } #[cfg(test)] mod tests { use super::*; #[test] fn records_in_normal_form() { let records = records(br#"{"b": 1, "a": {"x": [1]}}"#).unwrap(); assert_eq!( String::from_utf8(from_records(&records)).unwrap(), "{\n \"a\": {\n \"x\": [\n 1\n ]\n },\n \"b\": 1\n}\n" ); assert!(super::records(b"[1]").is_err()); assert_eq!(directory_mode(0o600), 0o700); assert_eq!(directory_mode(0o644), 0o755); } }