diff options
| author | tv <tv@krebsco.de> | 2026-11-29 14:21:34 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-30 14:59:15 +0000 |
| commit | eaac60ba88728bb582778c726e5798156dddfc45 (patch) | |
| tree | 557f4709762f95a7a440d1fa919dcce3bbf83cb4 /src/content.rs | |
| parent | 70367d17613ebe501fb2d3e9fa72b16c2eb9c2bd (diff) | |
enstate: the receptor and the provider, a first version
One program on a library: --plan and --apply of submissions (complete and
partial, items required and optional, groups, removal, the chain as
order), validators of types and across slots, views put in place by
replacing a link, their reactions by systemctl; --status, --materialize;
and --pack, a submission from a source list in JSON or TOML, by the
config crate's sources. Programs by the protocol of design.md 5.2;
tests with shell scripts as validators and renderers.
Diffstat (limited to 'src/content.rs')
| -rw-r--r-- | src/content.rs | 105 |
1 files changed, 105 insertions, 0 deletions
diff --git a/src/content.rs b/src/content.rs new file mode 100644 index 0000000..4dce0e7 --- /dev/null +++ b/src/content.rs @@ -0,0 +1,105 @@ +//! 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<String, Vec<u8>>; + +/// The entries in `dir`: one file per slot. A missing directory holds none. +pub fn read_dir(dir: &Path) -> Result<Content> { + 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<Map<String, Value>> { + 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<String, Value>) -> Vec<u8> { + 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); + } +} |
