aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/content.rs105
-rw-r--r--src/lib.rs42
-rw-r--r--src/main.rs505
-rw-r--r--src/media.rs92
-rw-r--r--src/name.rs140
-rw-r--r--src/pack.rs233
-rw-r--r--src/plan.rs566
-rw-r--r--src/program.rs201
-rw-r--r--src/schema.rs292
-rw-r--r--src/scratch.rs74
-rw-r--r--src/store.rs225
-rw-r--r--src/submission.rs219
-rw-r--r--src/view.rs181
13 files changed, 2875 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);
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..af7de7e
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,42 @@
+//! enstate: state next to the store (docs/design.md).
+//!
+//! * [`name`]: names of channels and slots, and addresses;
+//! * [`media`]: types, as media types;
+//! * [`schema`]: what a generation accepts;
+//! * [`content`]: the entries of one channel, and records in them;
+//! * [`submission`]: what gets handed to the host;
+//! * [`program`]: the protocol of validators, renderers, converters and steps;
+//! * [`view`]: rendering views, comparing them, installing them;
+//! * [`store`]: snapshots on disk, and the views in place;
+//! * [`plan`]: what a submission would do, and applying it;
+//! * [`pack`]: making a submission from a source list.
+
+pub mod content;
+pub mod media;
+pub mod name;
+pub mod pack;
+pub mod plan;
+pub mod program;
+pub mod schema;
+pub mod scratch;
+pub mod store;
+pub mod submission;
+pub mod view;
+
+/// A new identifier for a snapshot: a random UUID (version 4).
+pub fn new_id() -> anyhow::Result<String> {
+ use std::io::Read;
+ let mut bytes = [0u8; 16];
+ std::fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?;
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
+ let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
+ Ok(format!(
+ "{}-{}-{}-{}-{}",
+ &hex[0..8],
+ &hex[8..12],
+ &hex[12..16],
+ &hex[16..20],
+ &hex[20..32]
+ ))
+}
diff --git a/src/main.rs b/src/main.rs
new file mode 100644
index 0000000..16c553d
--- /dev/null
+++ b/src/main.rs
@@ -0,0 +1,505 @@
+//! `enstate`: the receptor's commands on a host (`--plan`, `--apply`, `--status`,
+//! `--materialize`), and the provider's (`--pack`). Commands are options, like every
+//! other, in any order.
+
+use std::io::{IsTerminal, Write};
+use std::path::{Path, PathBuf};
+use std::process::ExitCode;
+
+use anyhow::{Context, Result, bail};
+use clap::{Arg, ArgAction, ArgGroup, Command};
+use config::option::{Kind, OptionSpec, option};
+use serde::Deserialize;
+
+use enstate::plan::{self, Plan, ViewOutcome};
+use enstate::schema::Schema;
+use enstate::store::Store;
+use enstate::submission::Submission;
+use enstate::view;
+
+const OPTIONS: &[OptionSpec] = &[
+ option(
+ "state-dir",
+ Kind::Text,
+ "DIR",
+ Some("/var/lib/enstate"),
+ "Where snapshots are kept",
+ ),
+ option(
+ "run-dir",
+ Kind::Text,
+ "DIR",
+ Some("/run/enstate"),
+ "Where views are put",
+ ),
+ option(
+ "schema",
+ Kind::Text,
+ "PATH",
+ Some("/etc/enstate/schema.json"),
+ "The schema of the running generation; for --pack, one to check the source list against",
+ ),
+ OptionSpec {
+ hidden: true,
+ ..option(
+ "systemctl",
+ Kind::Text,
+ "PATH",
+ Some("systemctl"),
+ "What runs reactions",
+ )
+ },
+];
+
+const SETTINGS: config::option::Schema = config::option::Schema {
+ options: OPTIONS,
+ conflicts: &[],
+ gone: &[],
+};
+
+#[derive(Deserialize)]
+#[serde(rename_all = "kebab-case")]
+struct Settings {
+ state_dir: Option<PathBuf>,
+ run_dir: Option<PathBuf>,
+ schema: Option<PathBuf>,
+ systemctl: Option<PathBuf>,
+}
+
+const COMMANDS: &[(&str, &str)] = &[
+ (
+ "plan",
+ "Say what the submission in PATH would do, changing nothing",
+ ),
+ (
+ "apply",
+ "Apply the submission in PATH, if its plan is accepted",
+ ),
+ ("status", "Show the channels' snapshots and the views"),
+ (
+ "materialize",
+ "Put every view in place from the snapshots (at boot, after a switch)",
+ ),
+ (
+ "pack",
+ "Make a submission in --out from the source list in PATH",
+ ),
+];
+
+fn command() -> Command {
+ let mut command = Command::new("enstate")
+ .about("State next to the Nix store: plan, apply, and make submissions")
+ .disable_version_flag(true)
+ .disable_help_flag(true)
+ .next_help_heading("Commands");
+ for (name, help) in COMMANDS {
+ command = command.arg(
+ Arg::new(*name)
+ .long(*name)
+ .action(ArgAction::SetTrue)
+ .help(*help),
+ );
+ }
+ command = command
+ .group(
+ ArgGroup::new("command")
+ .args(COMMANDS.iter().map(|(name, _)| *name))
+ .required(true)
+ .multiple(false),
+ )
+ .next_help_heading("Options")
+ .arg(
+ Arg::new("help")
+ .long("help")
+ .short('h')
+ .action(ArgAction::Help)
+ .help("Print this help"),
+ )
+ .arg(
+ Arg::new("json")
+ .long("json")
+ .action(ArgAction::SetTrue)
+ .help("Print JSON (--plan, --apply, --status, --materialize)"),
+ )
+ .arg(
+ Arg::new("out")
+ .long("out")
+ .value_name("DIR")
+ .help("Where --pack writes the submission"),
+ )
+ .arg(
+ Arg::new("path")
+ .value_name("PATH")
+ .help("The submission (--plan, --apply) or source list (--pack)"),
+ )
+ .next_help_heading("Settings");
+ config::arguments::with_print_config(config::arguments::with_options(command, OPTIONS))
+}
+
+fn main() -> ExitCode {
+ match run() {
+ Ok(code) => code,
+ Err(error) => {
+ eprintln!("enstate: {error:#}");
+ ExitCode::from(2)
+ }
+ }
+}
+
+fn run() -> Result<ExitCode> {
+ config::arguments::refuse_gone(std::env::args().skip(1), &SETTINGS)?;
+ let matches = command().get_matches();
+ let (layer, files) = config::arguments::merged(&matches, &SETTINGS, &[])?;
+ if config::arguments::prints_config(&matches) {
+ let settings = layer
+ .iter()
+ .map(|(name, entry)| (name.clone(), entry.value.clone()))
+ .collect();
+ let origins = layer
+ .iter()
+ .map(|(name, entry)| (name.clone(), entry.origin.clone()))
+ .collect();
+ let report = config::report::report(
+ &SETTINGS,
+ &settings,
+ &origins,
+ &files,
+ config::report::Values::Interpolated,
+ );
+ println!("{}", serde_json::to_string_pretty(&report)?);
+ return Ok(ExitCode::SUCCESS);
+ }
+ let settings: Settings = config::layer::read(&layer)?;
+ let command = COMMANDS
+ .iter()
+ .map(|(name, _)| *name)
+ .find(|name| matches.get_flag(name))
+ .expect("clap requires one command");
+ let json = matches.get_flag("json");
+ let path = matches.get_one::<String>("path").map(PathBuf::from);
+ let out = matches.get_one::<String>("out").map(PathBuf::from);
+ // An option that isn't for the command is an error.
+ let takes_path = matches!(command, "plan" | "apply" | "pack");
+ match (&path, takes_path) {
+ (None, true) => bail!("--{command} needs a PATH"),
+ (Some(path), false) => bail!("--{command} takes no PATH ({})", path.display()),
+ _ => {}
+ }
+ if out.is_some() && command != "pack" {
+ bail!("--out is for --pack only");
+ }
+ if json && command == "pack" {
+ bail!("--json is not for --pack");
+ }
+ if command == "pack" {
+ let out = out.context("--pack needs --out DIR")?;
+ let schema = settings.schema.as_deref().map(Schema::load).transpose()?;
+ enstate::pack::pack(path.as_deref().unwrap(), &out, schema.as_ref())?;
+ return Ok(ExitCode::SUCCESS);
+ }
+ let store = Store::new(
+ settings
+ .state_dir
+ .as_deref()
+ .unwrap_or(Path::new("/var/lib/enstate")),
+ settings
+ .run_dir
+ .as_deref()
+ .unwrap_or(Path::new("/run/enstate")),
+ );
+ let schema_path = settings
+ .schema
+ .unwrap_or_else(|| PathBuf::from("/etc/enstate/schema.json"));
+ let schema_bytes = std::fs::read(&schema_path)
+ .with_context(|| format!("reading {}", schema_path.display()))?;
+ let schema = Schema::from_slice(&schema_bytes)
+ .with_context(|| format!("schema {}", schema_path.display()))?;
+ let systemctl = settings
+ .systemctl
+ .unwrap_or_else(|| PathBuf::from("systemctl"));
+ let _lock = store.lock()?;
+ match command {
+ "plan" | "apply" => {
+ let submission = Submission::load(path.as_deref().unwrap())?;
+ let planned = plan::plan(&schema, &store, &submission)?;
+ let plan = if command == "apply" {
+ planned.apply(&store, &schema_bytes, &systemctl)?
+ } else {
+ planned.plan
+ };
+ if json {
+ println!("{}", serde_json::to_string_pretty(&plan)?);
+ } else {
+ print_plan(&plan, command == "apply")?;
+ }
+ Ok(if !plan.accepted {
+ ExitCode::from(1)
+ } else if !plan.failed.is_empty() {
+ ExitCode::from(3)
+ } else {
+ ExitCode::SUCCESS
+ })
+ }
+ "materialize" => {
+ let views = plan::materialize(&schema, &store)?;
+ if json {
+ println!("{}", serde_json::to_string_pretty(&views)?);
+ } else {
+ print_views(&mut std::io::stdout().lock(), &views, false)?;
+ }
+ Ok(ExitCode::SUCCESS)
+ }
+ "status" => {
+ let status = status(&schema, &store)?;
+ if json {
+ println!("{}", serde_json::to_string_pretty(&status)?);
+ } else {
+ print_status(&status)?;
+ }
+ Ok(ExitCode::SUCCESS)
+ }
+ _ => unreachable!(),
+ }
+}
+
+/// Colors, on a terminal, and without `NO_COLOR`.
+struct Style {
+ on: bool,
+}
+
+impl Style {
+ fn new() -> Self {
+ Self {
+ on: std::io::stdout().is_terminal()
+ && std::env::var_os("NO_COLOR").is_none_or(|value| value.is_empty()),
+ }
+ }
+
+ fn paint(&self, code: &str, text: &str) -> String {
+ if self.on {
+ format!("\x1b[{code}m{text}\x1b[0m")
+ } else {
+ text.to_owned()
+ }
+ }
+}
+
+fn print_plan(plan: &Plan, applying: bool) -> Result<()> {
+ let style = Style::new();
+ let mut out = std::io::stdout().lock();
+ let verdict = if plan.accepted {
+ style.paint("32", "accepted")
+ } else {
+ style.paint("31", "refused")
+ };
+ writeln!(out, "channel {}: {verdict}", plan.channel)?;
+ writeln!(
+ out,
+ " current snapshot: {}",
+ plan.current.as_deref().unwrap_or("none")
+ )?;
+ if let Some(base) = &plan.base {
+ writeln!(out, " builds on: {base}")?;
+ }
+ for reason in &plan.refused {
+ writeln!(out, " {} {reason}", style.paint("31", "refused:"))?;
+ }
+ if !plan.items.is_empty() {
+ writeln!(out, "items:")?;
+ }
+ for item in &plan.items {
+ let mark = if item.goes_in {
+ style.paint("32", "+")
+ } else {
+ style.paint("33", "-")
+ };
+ let mut what = format!(
+ "{}, {}",
+ item.op,
+ if item.required {
+ "required"
+ } else {
+ "optional"
+ }
+ );
+ if let Some(group) = &item.group {
+ what.push_str(&format!(", group {group}"));
+ }
+ writeln!(out, " {mark} {} ({what})", item.address)?;
+ for reason in &item.reasons {
+ writeln!(out, " {reason}")?;
+ }
+ }
+ for warning in &plan.warnings {
+ writeln!(out, "{} {warning}", style.paint("33", "warning:"))?;
+ }
+ print_views(&mut out, &plan.views, true)?;
+ if !plan.reactions.restart.is_empty() {
+ writeln!(out, "restart: {}", plan.reactions.restart.join(" "))?;
+ }
+ if !plan.reactions.reload.is_empty() {
+ writeln!(out, "reload: {}", plan.reactions.reload.join(" "))?;
+ }
+ if plan.accepted && !plan.changes {
+ writeln!(out, "nothing changes")?;
+ }
+ if applying && plan.accepted {
+ match &plan.snapshot {
+ Some(id) => writeln!(out, "applied: snapshot {id}")?,
+ None if plan.changes => writeln!(out, "applied: the snapshot is unchanged")?,
+ None => {}
+ }
+ for failed in &plan.failed {
+ writeln!(out, "{} {failed}", style.paint("31", "failed:"))?;
+ }
+ }
+ Ok(())
+}
+
+fn print_views(out: &mut impl Write, views: &[ViewOutcome], only_changes: bool) -> Result<()> {
+ let style = Style::new();
+ let changing: Vec<_> = views
+ .iter()
+ .filter(|view| !only_changes || view.change != view::Change::Unchanged)
+ .collect();
+ if changing.is_empty() {
+ return Ok(());
+ }
+ writeln!(out, "views:")?;
+ for view in changing {
+ let change = match view.change {
+ view::Change::Unchanged => "unchanged",
+ view::Change::Added => "added",
+ view::Change::Removed => "removed",
+ view::Change::Changed => "changed",
+ };
+ let secret = if view.secret { " (secret)" } else { "" };
+ writeln!(out, " {}{secret}: {change}", view.name)?;
+ for file in &view.files {
+ for line in file.diff.lines() {
+ let painted = match line.chars().next() {
+ Some('+') if !line.starts_with("+++") => style.paint("32", line),
+ Some('-') if !line.starts_with("---") => style.paint("31", line),
+ _ => line.to_owned(),
+ };
+ writeln!(out, " {painted}")?;
+ }
+ }
+ }
+ Ok(())
+}
+
+#[derive(serde::Serialize)]
+struct Status {
+ channels: Vec<ChannelStatus>,
+ views: Vec<ViewStatus>,
+}
+
+#[derive(serde::Serialize)]
+struct ChannelStatus {
+ channel: String,
+ snapshot: Option<String>,
+ filled: Vec<String>,
+ unfilled: Vec<String>,
+ /// Required, and unfilled.
+ missing: Vec<String>,
+ /// Kept, but in no slot of the schema.
+ kept: Vec<String>,
+}
+
+#[derive(serde::Serialize)]
+struct ViewStatus {
+ view: String,
+ installed: bool,
+}
+
+fn status(schema: &Schema, store: &Store) -> Result<Status> {
+ let mut channels = Vec::new();
+ let mut names: Vec<String> = schema.channels.keys().cloned().collect();
+ for channel in store.channels()? {
+ if !names.contains(&channel) {
+ names.push(channel);
+ }
+ }
+ for channel in names {
+ let snapshot = store.current(&channel)?;
+ let content = snapshot
+ .as_ref()
+ .map(|snapshot| snapshot.content.clone())
+ .unwrap_or_default();
+ let slots = schema
+ .channel(&channel)
+ .map(|spec| spec.slots.clone())
+ .unwrap_or_default();
+ channels.push(ChannelStatus {
+ channel: channel.clone(),
+ snapshot: snapshot.map(|snapshot| snapshot.id),
+ filled: slots
+ .keys()
+ .filter(|slot| content.contains_key(*slot))
+ .cloned()
+ .collect(),
+ unfilled: slots
+ .keys()
+ .filter(|slot| !content.contains_key(*slot))
+ .cloned()
+ .collect(),
+ missing: slots
+ .iter()
+ .filter(|(slot, spec)| spec.required && !content.contains_key(*slot))
+ .map(|(slot, _)| slot.clone())
+ .collect(),
+ kept: content
+ .keys()
+ .filter(|slot| !slots.contains_key(*slot))
+ .cloned()
+ .collect(),
+ });
+ }
+ let views = schema
+ .views
+ .keys()
+ .map(|view| ViewStatus {
+ view: view.clone(),
+ installed: store.installed_view(view).is_some(),
+ })
+ .collect();
+ Ok(Status { channels, views })
+}
+
+fn print_status(status: &Status) -> Result<()> {
+ let style = Style::new();
+ let mut out = std::io::stdout().lock();
+ for channel in &status.channels {
+ writeln!(
+ out,
+ "channel {}: snapshot {}",
+ channel.channel,
+ channel.snapshot.as_deref().unwrap_or("none")
+ )?;
+ for slot in &channel.filled {
+ writeln!(out, " {} {slot}", style.paint("32", "filled"))?;
+ }
+ for slot in &channel.unfilled {
+ let missing = channel.missing.contains(slot);
+ let label = if missing {
+ style.paint("31", "missing")
+ } else {
+ "unfilled".to_owned()
+ };
+ writeln!(out, " {label} {slot}")?;
+ }
+ for slot in &channel.kept {
+ writeln!(out, " {} {slot}", style.paint("33", "kept"))?;
+ }
+ }
+ for view in &status.views {
+ let state = if view.installed {
+ style.paint("32", "in place")
+ } else {
+ style.paint("33", "not in place")
+ };
+ writeln!(out, "view {}: {state}", view.view)?;
+ }
+ Ok(())
+}
diff --git a/src/media.rs b/src/media.rs
new file mode 100644
index 0000000..c6b1c22
--- /dev/null
+++ b/src/media.rs
@@ -0,0 +1,92 @@
+//! Types, as media types (docs/design.md, 5.1): compared in a normal form, and keyed
+//! (holding records) where their top level is an object, which to start with means
+//! JSON.
+
+use anyhow::{Result, bail};
+
+/// `media_type` in its normal form: type and subtype and parameter names in lower
+/// case, parameters sorted by name, `; ` between them. Parameter values stay as they
+/// are, but for the quotes around a quoted one that needs none.
+pub fn normalize(media_type: &str) -> Result<String> {
+ let mut parts = media_type.split(';');
+ let essence = parts.next().unwrap_or_default().trim().to_ascii_lowercase();
+ let Some((kind, subtype)) = essence.split_once('/') else {
+ bail!("type {media_type:?} is not a media type (TYPE/SUBTYPE)");
+ };
+ if !is_token(kind) || !is_token(subtype) {
+ bail!("type {media_type:?} is not a media type (TYPE/SUBTYPE)");
+ }
+ let mut parameters = Vec::new();
+ for parameter in parts {
+ let Some((name, value)) = parameter.split_once('=') else {
+ bail!("type {media_type:?}: parameter {parameter:?} is not NAME=VALUE");
+ };
+ let name = name.trim().to_ascii_lowercase();
+ let mut value = value.trim().to_owned();
+ if value.len() >= 2 && value.starts_with('"') && value.ends_with('"') {
+ let inner = &value[1..value.len() - 1];
+ if is_token(inner) {
+ value = inner.to_owned();
+ }
+ }
+ if !is_token(&name) || value.is_empty() {
+ bail!("type {media_type:?}: parameter {parameter:?} is not NAME=VALUE");
+ }
+ if parameters.iter().any(|(other, _)| *other == name) {
+ bail!("type {media_type:?}: parameter {name} is given twice");
+ }
+ parameters.push((name, value));
+ }
+ parameters.sort();
+ let mut normal = essence;
+ for (name, value) in parameters {
+ normal.push_str(&format!("; {name}={value}"));
+ }
+ Ok(normal)
+}
+
+/// Whether entries of `media_type` (normalized) are keyed: JSON objects, whose keys are
+/// records.
+pub fn keyed(media_type: &str) -> bool {
+ let essence = media_type.split(';').next().unwrap_or_default();
+ let subtype = essence
+ .split_once('/')
+ .map(|(_, subtype)| subtype)
+ .unwrap_or_default();
+ subtype == "json" || subtype.ends_with("+json")
+}
+
+fn is_token(text: &str) -> bool {
+ !text.is_empty()
+ && text
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || b"!#$&-^_.+".contains(&byte))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn normal_forms() {
+ assert_eq!(
+ normalize("Application/X-OpenSSH-Private-Key;Algorithm=\"ed25519\"").unwrap(),
+ "application/x-openssh-private-key; algorithm=ed25519"
+ );
+ assert_eq!(
+ normalize("text/plain; b=2; a=1").unwrap(),
+ "text/plain; a=1; b=2"
+ );
+ assert!(normalize("text").is_err());
+ assert!(normalize("text/plain; a").is_err());
+ assert!(normalize("text/plain; a=1; A=2").is_err());
+ }
+
+ #[test]
+ fn keyed_types() {
+ assert!(keyed("application/x-enstate-hosts+json"));
+ assert!(keyed("application/json"));
+ assert!(!keyed("application/octet-stream"));
+ assert!(!keyed("application/x-pem-file; x=json"));
+ }
+}
diff --git a/src/name.rs b/src/name.rs
new file mode 100644
index 0000000..a1ed0e4
--- /dev/null
+++ b/src/name.rs
@@ -0,0 +1,140 @@
+//! Names of channels and slots, and addresses (docs/design.md, 5.1).
+
+use std::fmt;
+use std::str::FromStr;
+
+use anyhow::{Result, anyhow, bail};
+
+/// Whether `name` is a portable filename (POSIX.1-2017, 3.281) not starting with a
+/// hyphen, and neither `.` nor `..`: `[0-9A-Za-z._][0-9A-Za-z._-]*`.
+pub fn is_name(name: &str) -> bool {
+ let mut chars = name.chars();
+ let portable = |c: char| c.is_ascii_alphanumeric() || c == '.' || c == '_';
+ match chars.next() {
+ Some(first) if portable(first) => {}
+ _ => return false,
+ }
+ chars.all(|c| portable(c) || c == '-') && name != "." && name != ".."
+}
+
+/// `name`, if it is one, else an error saying what it was meant to name.
+pub fn check(what: &str, name: &str) -> Result<()> {
+ if is_name(name) {
+ Ok(())
+ } else {
+ bail!(
+ "{what} {name:?} is not a portable filename ([0-9A-Za-z._][0-9A-Za-z._-]*, not . or ..)"
+ )
+ }
+}
+
+/// `CHANNEL/SLOT` for an entry, `CHANNEL/SLOT/KEY` for a record. A record's key is
+/// everything after the second `/`, so it may hold `/` itself.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub struct Address {
+ pub channel: String,
+ pub slot: String,
+ pub key: Option<String>,
+}
+
+impl Address {
+ pub fn entry(channel: &str, slot: &str) -> Self {
+ Self {
+ channel: channel.to_owned(),
+ slot: slot.to_owned(),
+ key: None,
+ }
+ }
+
+ /// The address of the entry this is, or holds this record.
+ pub fn of_entry(&self) -> Self {
+ Self::entry(&self.channel, &self.slot)
+ }
+
+ /// Whether one of the two is within the other: the same entry, or an entry and one
+ /// of its records, or the same record.
+ pub fn overlaps(&self, other: &Address) -> bool {
+ self.channel == other.channel
+ && self.slot == other.slot
+ && match (&self.key, &other.key) {
+ (Some(one), Some(other)) => one == other,
+ _ => true,
+ }
+ }
+}
+
+impl FromStr for Address {
+ type Err = anyhow::Error;
+
+ fn from_str(text: &str) -> Result<Self> {
+ let mut parts = text.splitn(3, '/');
+ let channel = parts.next().unwrap_or_default();
+ let slot = parts
+ .next()
+ .ok_or_else(|| anyhow!("address {text:?} is not CHANNEL/SLOT or CHANNEL/SLOT/KEY"))?;
+ check("channel", channel)?;
+ check("slot", slot)?;
+ let key = match parts.next() {
+ None => None,
+ Some("") => bail!("address {text:?} has an empty key"),
+ Some(key) => Some(key.to_owned()),
+ };
+ Ok(Self {
+ channel: channel.to_owned(),
+ slot: slot.to_owned(),
+ key,
+ })
+ }
+}
+
+impl fmt::Display for Address {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}/{}", self.channel, self.slot)?;
+ if let Some(key) = &self.key {
+ write!(f, "/{key}")?;
+ }
+ Ok(())
+ }
+}
+
+impl serde::Serialize for Address {
+ fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+ serializer.collect_str(self)
+ }
+}
+
+impl<'de> serde::Deserialize<'de> for Address {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let text = String::deserialize(deserializer)?;
+ text.parse().map_err(serde::de::Error::custom)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn names() {
+ for good in ["a", "retiolum.key", "_x", ".hidden", "a-b", "0"] {
+ assert!(is_name(good), "{good}");
+ }
+ for bad in ["", ".", "..", "-a", "a/b", "a b", "ä"] {
+ assert!(!is_name(bad), "{bad}");
+ }
+ }
+
+ #[test]
+ fn addresses() {
+ let record: Address = "fleet/hosts/a/b".parse().unwrap();
+ assert_eq!(record.key.as_deref(), Some("a/b"));
+ assert_eq!(record.to_string(), "fleet/hosts/a/b");
+ let entry: Address = "fleet/hosts".parse().unwrap();
+ assert!(entry.overlaps(&record) && record.overlaps(&entry));
+ let other: Address = "fleet/hosts/c".parse().unwrap();
+ assert!(!other.overlaps(&record));
+ assert!("fleet".parse::<Address>().is_err());
+ assert!("fleet/hosts/".parse::<Address>().is_err());
+ assert!("fleet/../x".parse::<Address>().is_err());
+ }
+}
diff --git a/src/pack.rs b/src/pack.rs
new file mode 100644
index 0000000..67603d6
--- /dev/null
+++ b/src/pack.rs
@@ -0,0 +1,233 @@
+//! Making a submission from a source list (docs/design.md, section 10).
+//!
+//! ```json
+//! {
+//! "channel": "secrets",
+//! "complete": true,
+//! "items": {
+//! "retiolum.key": { "source": "cmd:secrets ${env:HOST} show retiolum.ed25519_key.priv" },
+//! "tls.pem": { "source": { "file": "/etc/ssl/some.pem" }, "required": false },
+//! "hosts/ne": { "source": { "file": "ne.json" }, "group": "ne" },
+//! "hosts/wu": { "remove": true }
+//! },
+//! "groups": { "ne": { "required": false } }
+//! }
+//! ```
+//!
+//! An item is named `SLOT` (an entry) or `SLOT/KEY` (a record). Sources are those of
+//! continuum's `config` crate: `env:`, `file:`, `cmd:`, the tables `{ "env": … }`,
+//! `{ "file": … }`, `{ "command": … }`, and text with placeholders. An entry is taken
+//! byte-exact (as `+raw`), a record as JSON. Relative paths are relative to the
+//! source list, and commands run in its directory. JSON, or TOML by the extension
+//! `.toml`.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, anyhow, bail};
+use config::import::{self, Format, Imported, Importer, Raw, Source};
+use serde::Deserialize;
+use serde_json::{Map, Value};
+
+use crate::content;
+use crate::name::{self, Address};
+use crate::schema::Schema;
+use crate::submission::{self, GroupSpec, ItemSpec, Manifest, Op};
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct SourceList {
+ pub channel: String,
+ #[serde(default)]
+ pub complete: bool,
+ #[serde(default)]
+ pub base: Option<String>,
+ pub items: BTreeMap<String, ItemSource>,
+ #[serde(default)]
+ pub groups: BTreeMap<String, GroupSpec>,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ItemSource {
+ #[serde(default)]
+ pub source: Option<Value>,
+ #[serde(default)]
+ pub remove: bool,
+ #[serde(default)]
+ pub required: Option<bool>,
+ #[serde(default)]
+ pub group: Option<String>,
+}
+
+impl SourceList {
+ pub fn load(path: &Path) -> Result<Self> {
+ let text =
+ std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
+ let value: Value = if path
+ .extension()
+ .is_some_and(|extension| extension == "toml")
+ {
+ toml::from_str(&text).with_context(|| format!("source list {}", path.display()))?
+ } else {
+ serde_json::from_str(&text)
+ .with_context(|| format!("source list {}", path.display()))?
+ };
+ serde_json::from_value(value).with_context(|| format!("source list {}", path.display()))
+ }
+}
+
+/// Packs the source list at `path` into a submission in `out` (which must not exist,
+/// or be empty), checked against `schema` if one is given.
+pub fn pack(path: &Path, out: &Path, schema: Option<&Schema>) -> Result<()> {
+ let list = SourceList::load(path)?;
+ let dir = path
+ .parent()
+ .map(Path::to_owned)
+ .filter(|dir| !dir.as_os_str().is_empty())
+ .unwrap_or_else(|| PathBuf::from("."));
+ name::check("channel", &list.channel)?;
+ let mut items = Vec::new();
+ for (key, item) in &list.items {
+ let address: Address = format!("{}/{key}", list.channel)
+ .parse()
+ .with_context(|| format!("item {key}"))?;
+ if item.remove == item.source.is_some() {
+ bail!("item {key}: give either a source or \"remove\": true");
+ }
+ items.push((address, item));
+ }
+ if let Some(schema) = schema {
+ check(schema, &list, &items)?;
+ }
+ // Read every source before writing anything.
+ let mut entries: BTreeMap<String, Vec<u8>> = BTreeMap::new();
+ let mut records: BTreeMap<String, Map<String, Value>> = BTreeMap::new();
+ let mut specs = Vec::new();
+ for (address, item) in &items {
+ if let Some(source) = &item.source {
+ let importer = importer(source, &dir, address.key.is_none())
+ .with_context(|| format!("item {address}"))?;
+ let imported = importer
+ .fetch()
+ .with_context(|| format!("item {address}: {}", importer.describe()))?;
+ match &address.key {
+ None => {
+ entries.insert(address.slot.clone(), bytes(imported));
+ }
+ Some(key) => {
+ let value = match imported {
+ Imported::Json(value) => value,
+ other => serde_json::from_slice(&bytes(other))
+ .with_context(|| format!("item {address}: not JSON"))?,
+ };
+ records
+ .entry(address.slot.clone())
+ .or_default()
+ .insert(key.clone(), value);
+ }
+ }
+ }
+ specs.push(ItemSpec {
+ address: address.clone(),
+ op: if item.remove { Op::Remove } else { Op::Set },
+ required: item.required,
+ group: item.group.clone(),
+ });
+ }
+ if let Some(slot) = records.keys().find(|slot| entries.contains_key(*slot)) {
+ bail!("slot {slot} is given both as a whole and by records");
+ }
+ let manifest = Manifest {
+ submission: submission::VERSION,
+ channel: list.channel.clone(),
+ complete: list.complete,
+ base: list.base.clone(),
+ items: specs,
+ groups: list.groups,
+ };
+ match std::fs::read_dir(out) {
+ Ok(mut existing) => {
+ if existing.next().is_some() {
+ bail!("{} is not empty", out.display());
+ }
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error).with_context(|| format!("reading {}", out.display())),
+ }
+ let channel_dir = out.join(submission::CHANNELS).join(&list.channel);
+ content::write_dir(&entries, &channel_dir, 0o600)?;
+ for (slot, records) in &records {
+ content::write_file(
+ &channel_dir.join(slot),
+ &content::from_records(records),
+ 0o600,
+ )?;
+ }
+ let mut manifest_bytes = serde_json::to_vec_pretty(&manifest)?;
+ manifest_bytes.push(b'\n');
+ content::write_file(&out.join(submission::MANIFEST), &manifest_bytes, 0o600)?;
+ // What was written is a submission the receptor reads.
+ submission::Submission::load(out)?;
+ Ok(())
+}
+
+/// The importer `source` describes, in `dir`: raw for an entry, JSON for a record.
+fn importer(source: &Value, dir: &Path, entry: bool) -> Result<Importer> {
+ let mut importer = match source {
+ Value::String(text) => match import::parse_argument(text) {
+ Raw::Import(mut importer) => {
+ importer.dir = Some(dir.to_owned());
+ importer
+ }
+ Raw::Literal(_) => {
+ bail!("source {text:?} is neither env:, file:, cmd: nor text with placeholders")
+ }
+ },
+ Value::Object(table) => import::parse_table(table, dir)?
+ .ok_or_else(|| anyhow!("source is not a table of env, file or command"))?,
+ other => bail!("source {other} is neither a text nor a table"),
+ };
+ if !matches!(importer.source, Source::Template(_)) {
+ importer.format = if entry { Format::Raw } else { Format::Json };
+ }
+ Ok(importer)
+}
+
+fn bytes(imported: Imported) -> Vec<u8> {
+ match imported {
+ Imported::Raw(bytes) => bytes,
+ Imported::Text(text) => text.into_bytes(),
+ Imported::Json(value) => value.to_string().into_bytes(),
+ }
+}
+
+/// The source list against the schema: the channel, the slots, records only in keyed
+/// types, and for a complete submission every required slot given.
+fn check(schema: &Schema, list: &SourceList, items: &[(Address, &ItemSource)]) -> Result<()> {
+ let Some(channel) = schema.channel(&list.channel) else {
+ bail!("the schema has no channel {}", list.channel);
+ };
+ for (address, _) in items {
+ let Some(slot) = channel.slots.get(&address.slot) else {
+ bail!("the schema has no slot {}", address.of_entry());
+ };
+ if address.key.is_some() && !crate::media::keyed(&slot.media_type) {
+ bail!("item {address}: type {} holds no records", slot.media_type);
+ }
+ }
+ if list.complete {
+ for (slot, spec) in &channel.slots {
+ let given = items
+ .iter()
+ .any(|(address, item)| address.slot == *slot && !item.remove);
+ if spec.required && !given {
+ bail!(
+ "required slot {}/{slot} has no source, and the submission is complete",
+ list.channel
+ );
+ }
+ }
+ }
+ Ok(())
+}
diff --git a/src/plan.rs b/src/plan.rs
new file mode 100644
index 0000000..952f3aa
--- /dev/null
+++ b/src/plan.rs
@@ -0,0 +1,566 @@
+//! What a submission would do, and doing it (docs/design.md, 5.5).
+//!
+//! The plan: check the channel and the base; apply the items to a copy of the current
+//! snapshot; run the validators on it, leaving out optional items an objection names,
+//! with their groups, and refusing for a required one or for what is in place; check
+//! that every required slot is filled; render the views into scratch and compare.
+//! Applying: the same, then the new snapshot becomes current, the views that changed
+//! are put in place, and their reactions run, each unit once.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::Path;
+use std::process::Command;
+
+use anyhow::{Context, Result, anyhow};
+use serde::Serialize;
+
+use crate::content::{self, Content};
+use crate::media;
+use crate::name::Address;
+use crate::program::{self, Given, ProgramFailed, Role};
+use crate::schema::{Reactions, Schema};
+use crate::scratch::Scratch;
+use crate::store::Store;
+use crate::submission::{Change, Item, Submission};
+use crate::view::{self, FileChange};
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Plan {
+ pub channel: String,
+ /// The current snapshot's id.
+ pub current: Option<String>,
+ /// The snapshot the submission builds on, if it names one.
+ pub base: Option<String>,
+ pub accepted: bool,
+ /// Why not, if not.
+ pub refused: Vec<String>,
+ pub items: Vec<ItemOutcome>,
+ pub warnings: Vec<String>,
+ pub views: Vec<ViewOutcome>,
+ pub reactions: Reactions,
+ /// Whether the snapshot or a view would change.
+ pub changes: bool,
+ /// The new snapshot's id, once applied.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub snapshot: Option<String>,
+ /// Reactions that failed, once applied.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub failed: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ItemOutcome {
+ pub address: Address,
+ pub op: &'static str,
+ pub required: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub group: Option<String>,
+ pub goes_in: bool,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub reasons: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ViewOutcome {
+ pub name: String,
+ pub secret: bool,
+ pub change: view::Change,
+ pub files: Vec<FileChange>,
+}
+
+/// A plan, and what applying it needs.
+pub struct Planned {
+ pub plan: Plan,
+ content: Content,
+ content_changes: bool,
+ rendered: Vec<(String, Option<Scratch>, bool)>,
+}
+
+/// A plan refused: nothing to apply.
+fn refused(plan: Plan) -> Result<Planned> {
+ Ok(Planned {
+ plan,
+ content: Content::new(),
+ content_changes: false,
+ rendered: Vec::new(),
+ })
+}
+
+/// Plans `submission` against `schema` and what `store` holds.
+pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result<Planned> {
+ let channel = submission.channel.as_str();
+ let current = store.current(channel)?;
+ let mut plan = Plan {
+ channel: channel.to_owned(),
+ current: current.as_ref().map(|snapshot| snapshot.id.clone()),
+ base: submission.base.clone(),
+ accepted: false,
+ refused: Vec::new(),
+ items: submission
+ .items
+ .iter()
+ .map(|item| ItemOutcome {
+ address: item.address.clone(),
+ op: match item.change {
+ Change::Remove => "remove",
+ _ => "set",
+ },
+ required: item.required,
+ group: item.group.clone(),
+ goes_in: true,
+ reasons: Vec::new(),
+ })
+ .collect(),
+ warnings: Vec::new(),
+ views: Vec::new(),
+ reactions: Reactions::default(),
+ changes: false,
+ snapshot: None,
+ failed: Vec::new(),
+ };
+ let Some(channel_spec) = schema.channel(channel) else {
+ plan.refused
+ .push(format!("the schema has no channel {channel}"));
+ return refused(plan);
+ };
+ if let Some(base) = &submission.base {
+ let current_id = current.as_ref().map(|snapshot| snapshot.id.as_str());
+ if current_id != Some(base.as_str()) {
+ plan.refused.push(format!(
+ "the submission builds on {base}, but the current snapshot is {}",
+ current_id.unwrap_or("none")
+ ));
+ return refused(plan);
+ }
+ }
+ let empty = Content::new();
+ let base_content = match (&current, submission.complete) {
+ (Some(snapshot), false) => &snapshot.content,
+ _ => &empty,
+ };
+ // Other channels, for validators and views given their slots.
+ let mut others: BTreeMap<String, Content> = BTreeMap::new();
+ let mut other_channels: BTreeSet<&str> = BTreeSet::new();
+ for validator in schema.validators_of(channel) {
+ for address in validator.slots {
+ if address.channel != channel {
+ other_channels.insert(schema.channels.get_key_value(&address.channel).unwrap().0);
+ }
+ }
+ }
+ for (_, view) in schema.views_of(Some(channel)) {
+ for address in &view.from {
+ if address.channel != channel {
+ other_channels.insert(schema.channels.get_key_value(&address.channel).unwrap().0);
+ }
+ }
+ }
+ for other in other_channels {
+ let content = store
+ .current(other)?
+ .map(|snapshot| snapshot.content)
+ .unwrap_or_default();
+ others.insert(other.to_owned(), content);
+ }
+
+ let items = &submission.items;
+ // Items that can't go in, whatever the validators say.
+ let mut cannot: BTreeMap<usize, String> = BTreeMap::new();
+ for (index, item) in items.iter().enumerate() {
+ if let Some(reason) = unfit(schema, item, base_content) {
+ cannot.insert(index, reason);
+ }
+ }
+ let mut excluded: BTreeSet<usize> = BTreeSet::new();
+ let leave_out =
+ |plan: &mut Plan, excluded: &mut BTreeSet<usize>, index: usize, reason: String| -> bool {
+ // Whether it may be left out: else the submission is refused.
+ let item = &items[index];
+ if item.required {
+ plan.refused
+ .push(format!("required item {}: {reason}", item.address));
+ return false;
+ }
+ for (other, other_item) in items.iter().enumerate() {
+ let together =
+ other == index || (item.group.is_some() && other_item.group == item.group);
+ if together && excluded.insert(other) {
+ plan.items[other].goes_in = false;
+ let reason = if other == index {
+ reason.clone()
+ } else {
+ format!(
+ "its group {} can't go in",
+ item.group.as_deref().unwrap_or_default()
+ )
+ };
+ plan.warnings
+ .push(format!("left out: {}: {reason}", other_item.address));
+ plan.items[other].reasons.push(reason);
+ }
+ }
+ true
+ };
+ for (index, reason) in &cannot {
+ if !excluded.contains(index) && !leave_out(&mut plan, &mut excluded, *index, reason.clone())
+ {
+ return refused(plan);
+ }
+ }
+
+ let candidate = loop {
+ let candidate = apply_items(base_content, items, &excluded);
+ let mut blame: Vec<(usize, String)> = Vec::new();
+ // Required slots first: validators are given filled slots.
+ for (slot, spec) in &channel_spec.slots {
+ if !spec.required || candidate.contains_key(slot) {
+ continue;
+ }
+ let address = Address::entry(channel, slot);
+ let removals: Vec<usize> = (0..items.len())
+ .filter(|index| !excluded.contains(index))
+ .filter(|index| {
+ items[*index].address == address && items[*index].change == Change::Remove
+ })
+ .collect();
+ if removals.is_empty() {
+ plan.refused
+ .push(format!("required slot {address} is unfilled"));
+ }
+ blame.extend(
+ removals
+ .into_iter()
+ .map(|index| (index, format!("required slot {address} would be unfilled"))),
+ );
+ }
+ if !plan.refused.is_empty() {
+ return refused(plan);
+ }
+ if blame.is_empty() {
+ // Validators.
+ for validator in schema.validators_of(channel) {
+ let entry = |address: &Address| -> Option<&[u8]> {
+ if address.channel == channel {
+ candidate.get(&address.slot).map(Vec::as_slice)
+ } else {
+ others
+ .get(&address.channel)?
+ .get(&address.slot)
+ .map(Vec::as_slice)
+ }
+ };
+ if validator.of_type && entry(&validator.slots[0]).is_none() {
+ continue;
+ }
+ let given = Given {
+ slots: validator
+ .slots
+ .iter()
+ .map(|address| {
+ let media_type = schema
+ .slot(address)
+ .map(|slot| slot.media_type.as_str())
+ .unwrap_or_default();
+ (address.clone(), (media_type, entry(address)))
+ })
+ .collect(),
+ };
+ let outcome = match program::run(
+ &validator.program,
+ Role::Validator,
+ &validator.name,
+ &given,
+ &store.scratch(),
+ ) {
+ Ok(outcome) => outcome,
+ Err(error) => match error.downcast::<ProgramFailed>() {
+ Ok(failed) => {
+ plan.refused.push(failed.to_string());
+ return refused(plan);
+ }
+ Err(error) => return Err(error),
+ },
+ };
+ for objection in outcome.objections {
+ let said = format!(
+ "{}: {} (validator {})",
+ objection.address, objection.message, validator.name
+ );
+ let blamed: Vec<usize> = (0..items.len())
+ .filter(|index| !excluded.contains(index))
+ .filter(|index| items[*index].address.overlaps(&objection.address))
+ .collect();
+ if blamed.is_empty() {
+ plan.refused
+ .push(format!("objection to what is in place: {said}"));
+ }
+ blame.extend(blamed.into_iter().map(|index| (index, said.clone())));
+ }
+ }
+ if !plan.refused.is_empty() {
+ return refused(plan);
+ }
+ }
+ if blame.is_empty() {
+ break candidate;
+ }
+ for (index, reason) in blame {
+ if !excluded.contains(&index) && !leave_out(&mut plan, &mut excluded, index, reason) {
+ return refused(plan);
+ }
+ }
+ };
+ for slot in candidate.keys() {
+ if !channel_spec.slots.contains_key(slot) {
+ plan.warnings.push(format!(
+ "kept, but in no slot of the schema: {channel}/{slot}"
+ ));
+ }
+ }
+
+ // Views.
+ let mut rendered_views = Vec::new();
+ let mut entries: view::Entries = others
+ .iter()
+ .map(|(name, content)| (name.as_str(), content))
+ .collect();
+ entries.insert(channel, &candidate);
+ for (name, view_spec) in schema.views_of(Some(channel)) {
+ let secret = schema.view_is_secret(view_spec);
+ let rendered = match view::render(schema, name, view_spec, &entries, &store.scratch()) {
+ Ok(rendered) => rendered,
+ Err(error) => match error.downcast::<ProgramFailed>() {
+ Ok(failed) => {
+ plan.refused.push(failed.to_string());
+ return refused(plan);
+ }
+ Err(error) => return Err(error),
+ },
+ };
+ let installed = store.installed_view(name);
+ let (change, files) = view::compare(
+ installed.as_deref(),
+ rendered.as_ref().map(Scratch::path),
+ secret,
+ )?;
+ if change != view::Change::Unchanged {
+ plan.reactions
+ .restart
+ .extend(view_spec.reactions.restart.iter().cloned());
+ plan.reactions
+ .reload
+ .extend(view_spec.reactions.reload.iter().cloned());
+ }
+ plan.views.push(ViewOutcome {
+ name: name.clone(),
+ secret,
+ change,
+ files,
+ });
+ rendered_views.push((name.clone(), rendered, secret));
+ }
+ let restart: BTreeSet<String> = std::mem::take(&mut plan.reactions.restart)
+ .into_iter()
+ .collect();
+ let reload: BTreeSet<String> = std::mem::take(&mut plan.reactions.reload)
+ .into_iter()
+ .filter(|unit| !restart.contains(unit))
+ .collect();
+ plan.reactions = Reactions {
+ restart: restart.into_iter().collect(),
+ reload: reload.into_iter().collect(),
+ };
+ let content_changes = current.as_ref().map(|snapshot| &snapshot.content) != Some(&candidate);
+ plan.changes = content_changes
+ || plan
+ .views
+ .iter()
+ .any(|view| view.change != view::Change::Unchanged);
+ plan.accepted = true;
+ Ok(Planned {
+ plan,
+ content: candidate,
+ content_changes,
+ rendered: rendered_views,
+ })
+}
+
+/// Why `item` can't go in, whatever the validators say: no such slot, a record in an
+/// entry that holds none.
+fn unfit(schema: &Schema, item: &Item, base: &Content) -> Option<String> {
+ let Some(slot) = schema.slot(&item.address) else {
+ return Some(format!(
+ "the schema has no slot {}",
+ item.address.of_entry()
+ ));
+ };
+ if item.address.key.is_some() {
+ if !media::keyed(&slot.media_type) {
+ return Some(format!("type {} holds no records", slot.media_type));
+ }
+ if let Some(bytes) = base.get(&item.address.slot)
+ && let Err(error) = content::records(bytes)
+ {
+ return Some(format!("the entry in place holds no records: {error}"));
+ }
+ }
+ None
+}
+
+/// `base` with the items not `excluded` applied.
+fn apply_items(base: &Content, items: &[Item], excluded: &BTreeSet<usize>) -> Content {
+ let mut content = base.clone();
+ for (index, item) in items.iter().enumerate() {
+ if excluded.contains(&index) {
+ continue;
+ }
+ let slot = &item.address.slot;
+ match (&item.address.key, &item.change) {
+ (None, Change::Entry(bytes)) => {
+ content.insert(slot.clone(), bytes.clone());
+ }
+ (None, Change::Remove) => {
+ content.remove(slot);
+ }
+ (Some(key), change) => {
+ // `unfit` made sure an entry in place holds records.
+ let mut records = content
+ .get(slot)
+ .and_then(|bytes| content::records(bytes).ok())
+ .unwrap_or_default();
+ match change {
+ Change::Record(value) => {
+ records.insert(key.clone(), value.clone());
+ }
+ Change::Remove => {
+ records.remove(key);
+ }
+ Change::Entry(_) => unreachable!("an entry's item has no key"),
+ }
+ content.insert(slot.clone(), content::from_records(&records));
+ }
+ (None, Change::Record(_)) => unreachable!("a record's item has a key"),
+ }
+ }
+ content
+}
+
+impl Planned {
+ /// Applies the plan, if it was accepted: the new snapshot, the views that change,
+ /// and their reactions, by `systemctl`.
+ pub fn apply(self, store: &Store, schema_bytes: &[u8], systemctl: &Path) -> Result<Plan> {
+ let mut plan = self.plan;
+ if !plan.accepted {
+ return Ok(plan);
+ }
+ if self.content_changes {
+ plan.snapshot = Some(store.commit(
+ &plan.channel,
+ &self.content,
+ plan.current.as_deref(),
+ schema_bytes,
+ )?);
+ }
+ for ((name, rendered, secret), outcome) in self.rendered.into_iter().zip(&plan.views) {
+ if outcome.change != view::Change::Unchanged {
+ store
+ .install_view(&name, rendered, secret)
+ .with_context(|| format!("view {name}"))?;
+ }
+ }
+ plan.failed = react(&plan.reactions, systemctl);
+ Ok(plan)
+ }
+}
+
+/// Runs `reactions`; what failed.
+pub fn react(reactions: &Reactions, systemctl: &Path) -> Vec<String> {
+ let mut failed = Vec::new();
+ for (verb, units) in [
+ ("restart", &reactions.restart),
+ ("reload", &reactions.reload),
+ ] {
+ if units.is_empty() {
+ continue;
+ }
+ let result = Command::new(systemctl)
+ .arg(verb)
+ .args(units)
+ .status()
+ .map_err(|error| anyhow!("{error}"))
+ .and_then(|status| {
+ if status.success() {
+ Ok(())
+ } else {
+ Err(anyhow!("{status}"))
+ }
+ });
+ if let Err(error) = result {
+ failed.push(format!(
+ "{} {verb} {}: {error}",
+ systemctl.display(),
+ units.join(" ")
+ ));
+ }
+ }
+ failed
+}
+
+/// Renders every view of `schema` from the current snapshots, puts those that differ
+/// from what is in place there, and takes away views the schema doesn't have: at boot,
+/// and after a generation change. Runs no reactions. Returns how each view changed.
+pub fn materialize(schema: &Schema, store: &Store) -> Result<Vec<ViewOutcome>> {
+ let mut contents: BTreeMap<String, Content> = BTreeMap::new();
+ for channel in schema.channels.keys() {
+ if let Some(snapshot) = store.current(channel)? {
+ contents.insert(channel.clone(), snapshot.content);
+ }
+ }
+ let entries: view::Entries = contents
+ .iter()
+ .map(|(name, content)| (name.as_str(), content))
+ .collect();
+ let mut outcomes = Vec::new();
+ for (name, view_spec) in schema.views_of(None) {
+ let secret = schema.view_is_secret(view_spec);
+ let rendered = view::render(schema, name, view_spec, &entries, &store.scratch())
+ .with_context(|| format!("view {name}"))?;
+ let installed = store.installed_view(name);
+ let (change, files) = view::compare(
+ installed.as_deref(),
+ rendered.as_ref().map(Scratch::path),
+ secret,
+ )?;
+ if change != view::Change::Unchanged {
+ store.install_view(name, rendered, secret)?;
+ }
+ outcomes.push(ViewOutcome {
+ name: name.clone(),
+ secret,
+ change,
+ files,
+ });
+ }
+ let views = store.run.join("views");
+ if let Ok(entries) = std::fs::read_dir(&views) {
+ for entry in entries {
+ let name = entry?.file_name().to_string_lossy().into_owned();
+ if name == ".generations"
+ || name.ends_with(".new-link")
+ || schema.views.contains_key(&name)
+ {
+ continue;
+ }
+ if store.installed_view(&name).is_some() {
+ store.install_view(&name, None, false)?;
+ outcomes.push(ViewOutcome {
+ name,
+ secret: false,
+ change: view::Change::Removed,
+ files: Vec::new(),
+ });
+ }
+ }
+ }
+ Ok(outcomes)
+}
diff --git a/src/program.rs b/src/program.rs
new file mode 100644
index 0000000..8c4a565
--- /dev/null
+++ b/src/program.rs
@@ -0,0 +1,201 @@
+//! The protocol of validators, renderers, converters and steps (docs/design.md, 5.2).
+//!
+//! `PROGRAM IN OUT`, standard input `/dev/null`, an empty environment, in `IN`. `IN`
+//! holds `invocation.json` and the slots given at `channels/CHANNEL/SLOT`; `OUT` is
+//! empty. Objections are JSON lines on standard output; an exit status but 0 is a
+//! failure.
+//!
+//! `IN` is read-only (for its owner, as root ignores modes). Not yet: a sandbox (no
+//! network, nothing writable but `OUT`).
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+
+use anyhow::{Context, Result, anyhow, bail};
+use serde::{Deserialize, Serialize};
+
+use crate::content;
+use crate::name::Address;
+use crate::scratch::Scratch;
+
+pub const PROTOCOL: u32 = 1;
+pub const INVOCATION: &str = "invocation.json";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Role {
+ Validator,
+ Renderer,
+ Converter,
+ Step,
+}
+
+/// What a program is given: slots, by address, with their types and entries (none for
+/// an unfilled one).
+pub struct Given<'a> {
+ pub slots: BTreeMap<Address, (&'a str, Option<&'a [u8]>)>,
+}
+
+#[derive(Serialize)]
+struct Invocation<'a> {
+ protocol: u32,
+ program: Role,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ view: Option<&'a str>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ validator: Option<&'a str>,
+ slots: BTreeMap<String, SlotType<'a>>,
+ produces: BTreeMap<String, SlotType<'a>>,
+}
+
+#[derive(Serialize)]
+struct SlotType<'a> {
+ #[serde(rename = "type")]
+ media_type: &'a str,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Objection {
+ pub address: Address,
+ pub message: String,
+}
+
+/// What a program did: its objections, and what it wrote, in `OUT`.
+pub struct Outcome {
+ pub objections: Vec<Objection>,
+ pub out: Scratch,
+}
+
+/// Runs `program` as `role`, named `name` (a view's or validator's), on `given`, in a
+/// scratch directory below `scratch`.
+pub fn run(
+ program: &Path,
+ role: Role,
+ name: &str,
+ given: &Given,
+ scratch: &Path,
+) -> Result<Outcome> {
+ let what = format!("{} {name} ({})", role_name(role), program.display());
+ let input = Scratch::new(scratch, "in-")?;
+ let out = Scratch::new(scratch, "out-")?;
+ let invocation = Invocation {
+ protocol: PROTOCOL,
+ program: role,
+ view: (role == Role::Renderer).then_some(name),
+ validator: (role == Role::Validator).then_some(name),
+ slots: given
+ .slots
+ .iter()
+ .map(|(address, (media_type, _))| (address.to_string(), SlotType { media_type }))
+ .collect(),
+ produces: BTreeMap::new(),
+ };
+ content::write_file(
+ &input.path().join(INVOCATION),
+ &serde_json::to_vec_pretty(&invocation)?,
+ 0o600,
+ )?;
+ for (address, (_, bytes)) in &given.slots {
+ let Some(bytes) = bytes else { continue };
+ let dir = input.path().join("channels").join(&address.channel);
+ std::fs::create_dir_all(&dir)?;
+ content::write_file(&dir.join(&address.slot), bytes, 0o600)?;
+ }
+ input.set_modes(0o400)?;
+ let program = std::path::absolute(program).unwrap_or_else(|_| program.to_owned());
+ let output = Command::new(&program)
+ .arg(input.path())
+ .arg(out.path())
+ .current_dir(input.path())
+ .env_clear()
+ .stdin(Stdio::null())
+ .output()
+ .with_context(|| format!("running {what}"))?;
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ if !output.status.success() {
+ return Err(ProgramFailed {
+ what,
+ status: output.status.to_string(),
+ stderr: stderr.trim_end().to_owned(),
+ }
+ .into());
+ }
+ let mut objections = Vec::new();
+ let stdout = String::from_utf8(output.stdout)
+ .map_err(|_| anyhow!("{what}: its standard output is not UTF-8"))?;
+ for line in stdout.lines().filter(|line| !line.trim().is_empty()) {
+ let objection: Objection = serde_json::from_str(line)
+ .with_context(|| format!("{what}: not an objection: {line}"))?;
+ if !given
+ .slots
+ .keys()
+ .any(|address| address.overlaps(&objection.address))
+ {
+ bail!(
+ "{what} objects to {}, which it wasn't given",
+ objection.address
+ );
+ }
+ objections.push(objection);
+ }
+ Ok(Outcome { objections, out })
+}
+
+fn role_name(role: Role) -> &'static str {
+ match role {
+ Role::Validator => "validator",
+ Role::Renderer => "renderer",
+ Role::Converter => "converter",
+ Role::Step => "step",
+ }
+}
+
+/// A program that didn't exit with 0: no item is to blame.
+#[derive(Debug)]
+pub struct ProgramFailed {
+ pub what: String,
+ pub status: String,
+ pub stderr: String,
+}
+
+impl std::fmt::Display for ProgramFailed {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{} failed ({})", self.what, self.status)?;
+ if !self.stderr.is_empty() {
+ write!(f, ":\n{}", self.stderr)?;
+ }
+ Ok(())
+ }
+}
+
+impl std::error::Error for ProgramFailed {}
+
+/// The regular files below `dir`, by path relative to it; anything but regular files
+/// and directories is an error.
+pub fn files_below(dir: &Path) -> Result<BTreeMap<PathBuf, Vec<u8>>> {
+ let mut files = BTreeMap::new();
+ let mut pending = vec![PathBuf::new()];
+ while let Some(relative) = pending.pop() {
+ let path = dir.join(&relative);
+ for entry in
+ std::fs::read_dir(&path).with_context(|| format!("reading {}", path.display()))?
+ {
+ let entry = entry?;
+ let kind = entry.file_type()?;
+ let relative = relative.join(entry.file_name());
+ if kind.is_dir() {
+ pending.push(relative);
+ } else if kind.is_file() {
+ files.insert(relative, std::fs::read(entry.path())?);
+ } else {
+ bail!(
+ "{}: neither a regular file nor a directory",
+ entry.path().display()
+ );
+ }
+ }
+ }
+ Ok(files)
+}
diff --git a/src/schema.rs b/src/schema.rs
new file mode 100644
index 0000000..a44f6f8
--- /dev/null
+++ b/src/schema.rs
@@ -0,0 +1,292 @@
+//! What a generation accepts (docs/design.md, 5.1 to 5.3): its channels and their
+//! slots, the types' validators and the schema's own, and the views. A JSON file in
+//! the system, which the NixOS module writes.
+//!
+//! ```json
+//! {
+//! "schema": 1,
+//! "types": { "application/x-enstate-hosts+json": { "validator": "/nix/store/…" } },
+//! "channels": {
+//! "secrets": { "slots": { "retiolum.key": { "type": "…", "secret": true } } }
+//! },
+//! "validators": { "key-pair": { "slots": ["secrets/a.key", "secrets/a.pub"], "program": "…" } },
+//! "views": {
+//! "known-hosts": { "from": ["fleet/hosts"], "renderer": "…", "reactions": { "reload": [] } },
+//! "retiolum.key": { "from": ["secrets/retiolum.key"] }
+//! }
+//! }
+//! ```
+//!
+//! Slots are required unless they say otherwise. A view without a renderer is the one
+//! entry it is from. A view is secret if one of the slots it is from is, unless it
+//! says it isn't.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+
+use crate::media;
+use crate::name::{self, Address};
+
+pub const VERSION: u32 = 1;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Schema {
+ pub schema: u32,
+ #[serde(default)]
+ pub types: BTreeMap<String, TypeSpec>,
+ pub channels: BTreeMap<String, ChannelSpec>,
+ #[serde(default)]
+ pub validators: BTreeMap<String, ValidatorSpec>,
+ #[serde(default)]
+ pub views: BTreeMap<String, ViewSpec>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct TypeSpec {
+ pub validator: Option<PathBuf>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ChannelSpec {
+ pub slots: BTreeMap<String, SlotSpec>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields, rename_all = "camelCase")]
+pub struct SlotSpec {
+ #[serde(rename = "type")]
+ pub media_type: String,
+ #[serde(default = "yes")]
+ pub required: bool,
+ #[serde(default)]
+ pub secret: bool,
+}
+
+fn yes() -> bool {
+ true
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ValidatorSpec {
+ pub slots: Vec<Address>,
+ pub program: PathBuf,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ViewSpec {
+ pub from: Vec<Address>,
+ pub renderer: Option<PathBuf>,
+ pub secret: Option<bool>,
+ #[serde(default)]
+ pub reactions: Reactions,
+}
+
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Reactions {
+ #[serde(default)]
+ pub restart: Vec<String>,
+ #[serde(default)]
+ pub reload: Vec<String>,
+}
+
+impl Schema {
+ /// The schema in `path`, checked, its types normalized.
+ pub fn load(path: &Path) -> Result<Self> {
+ let bytes = std::fs::read(path).with_context(|| format!("reading {}", path.display()))?;
+ Self::from_slice(&bytes).with_context(|| format!("schema {}", path.display()))
+ }
+
+ pub fn from_slice(bytes: &[u8]) -> Result<Self> {
+ let mut schema: Schema = serde_json::from_slice(bytes)?;
+ schema.check()?;
+ Ok(schema)
+ }
+
+ fn check(&mut self) -> Result<()> {
+ if self.schema != VERSION {
+ bail!("schema version {} is not {VERSION}", self.schema);
+ }
+ self.types = std::mem::take(&mut self.types)
+ .into_iter()
+ .map(|(media_type, spec)| Ok((media::normalize(&media_type)?, spec)))
+ .collect::<Result<_>>()?;
+ for (channel, spec) in &mut self.channels {
+ name::check("channel", channel)?;
+ for (slot, spec) in &mut spec.slots {
+ name::check("slot", slot)?;
+ spec.media_type = media::normalize(&spec.media_type)
+ .with_context(|| format!("slot {channel}/{slot}"))?;
+ }
+ }
+ for (name, validator) in &self.validators {
+ if validator.slots.is_empty() {
+ bail!("validator {name} is given no slots");
+ }
+ for address in &validator.slots {
+ self.entry_slot(address)
+ .with_context(|| format!("validator {name}"))?;
+ }
+ }
+ for (name, view) in &self.views {
+ name::check("view", name)?;
+ if view.from.is_empty() {
+ bail!("view {name} is made from no slots");
+ }
+ for address in &view.from {
+ self.entry_slot(address)
+ .with_context(|| format!("view {name}"))?;
+ }
+ if view.renderer.is_none() && view.from.len() != 1 {
+ bail!("view {name} has no renderer, so it must be made from one slot");
+ }
+ }
+ Ok(())
+ }
+
+ /// The slot `address` names, which must be an entry's address.
+ fn entry_slot(&self, address: &Address) -> Result<&SlotSpec> {
+ if address.key.is_some() {
+ bail!("{address} is a record's address, not a slot's");
+ }
+ self.slot(address)
+ .with_context(|| format!("no slot {address}"))
+ }
+
+ /// The slot of the entry `address` is, or is in.
+ pub fn slot(&self, address: &Address) -> Option<&SlotSpec> {
+ self.channels
+ .get(&address.channel)?
+ .slots
+ .get(&address.slot)
+ }
+
+ pub fn channel(&self, channel: &str) -> Option<&ChannelSpec> {
+ self.channels.get(channel)
+ }
+
+ /// The validators that see `channel`: each slot's type's own, for that slot, and
+ /// the schema's that are given one of its slots.
+ pub fn validators_of(&self, channel: &str) -> Vec<Validator> {
+ let mut validators = Vec::new();
+ if let Some(spec) = self.channels.get(channel) {
+ for (slot, slot_spec) in &spec.slots {
+ if let Some(program) = self
+ .types
+ .get(&slot_spec.media_type)
+ .and_then(|spec| spec.validator.as_ref())
+ {
+ validators.push(Validator {
+ name: format!("type {}", slot_spec.media_type),
+ slots: vec![Address::entry(channel, slot)],
+ program: program.clone(),
+ of_type: true,
+ });
+ }
+ }
+ }
+ for (name, spec) in &self.validators {
+ if spec.slots.iter().any(|address| address.channel == channel) {
+ validators.push(Validator {
+ name: name.clone(),
+ slots: spec.slots.clone(),
+ program: spec.program.clone(),
+ of_type: false,
+ });
+ }
+ }
+ validators
+ }
+
+ /// The views made from one of `channel`'s slots, or all views.
+ pub fn views_of(&self, channel: Option<&str>) -> impl Iterator<Item = (&String, &ViewSpec)> {
+ self.views.iter().filter(move |(_, view)| match channel {
+ None => true,
+ Some(channel) => view.from.iter().any(|address| address.channel == channel),
+ })
+ }
+
+ pub fn view_is_secret(&self, view: &ViewSpec) -> bool {
+ view.secret.unwrap_or_else(|| {
+ view.from
+ .iter()
+ .any(|address| self.slot(address).is_some_and(|slot| slot.secret))
+ })
+ }
+}
+
+/// A validator to run: a type's, for one slot, or the schema's.
+#[derive(Debug, Clone)]
+pub struct Validator {
+ pub name: String,
+ pub slots: Vec<Address>,
+ pub program: PathBuf,
+ /// A type's own: an unfilled slot isn't checked.
+ pub of_type: bool,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_schema() {
+ let schema = Schema::from_slice(
+ br#"{
+ "schema": 1,
+ "types": { "Application/X-Hosts+JSON": { "validator": "/bin/check" } },
+ "channels": {
+ "fleet": { "slots": { "hosts": { "type": "application/x-hosts+json" } } },
+ "secrets": { "slots": { "a.key": { "type": "application/octet-stream", "secret": true, "required": false } } }
+ },
+ "validators": { "both": { "slots": ["fleet/hosts", "secrets/a.key"], "program": "/bin/both" } },
+ "views": {
+ "hosts": { "from": ["fleet/hosts"], "renderer": "/bin/render" },
+ "a.key": { "from": ["secrets/a.key"] }
+ }
+ }"#,
+ )
+ .unwrap();
+ let validators = schema.validators_of("fleet");
+ assert_eq!(validators.len(), 2);
+ assert_eq!(validators[0].name, "type application/x-hosts+json");
+ assert!(schema.view_is_secret(&schema.views["a.key"]));
+ assert!(!schema.view_is_secret(&schema.views["hosts"]));
+ assert!(schema.channels["fleet"].slots["hosts"].required);
+ }
+
+ #[test]
+ fn mistakes() {
+ for (bad, said) in [
+ (r#"{"schema": 2, "channels": {}}"#, "version"),
+ (
+ r#"{"schema": 1, "channels": {"-x": {"slots": {}}}}"#,
+ "portable",
+ ),
+ (
+ r#"{"schema": 1, "channels": {"c": {"slots": {"s": {"type": "text"}}}}}"#,
+ "media type",
+ ),
+ (
+ r#"{"schema": 1, "channels": {}, "views": {"v": {"from": ["c/s"]}}}"#,
+ "no slot c/s",
+ ),
+ (
+ r#"{"schema": 1, "channels": {"c": {"slots": {"s": {"type": "a/b"}, "t": {"type": "a/b"}}}},
+ "views": {"v": {"from": ["c/s", "c/t"]}}}"#,
+ "no renderer",
+ ),
+ ] {
+ let error = format!("{:#}", Schema::from_slice(bad.as_bytes()).unwrap_err());
+ assert!(error.contains(said), "{bad}: {error}");
+ }
+ }
+}
diff --git a/src/scratch.rs b/src/scratch.rs
new file mode 100644
index 0000000..dddd91b
--- /dev/null
+++ b/src/scratch.rs
@@ -0,0 +1,74 @@
+//! Scratch directories, removed when dropped.
+
+use std::os::unix::fs::PermissionsExt;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result};
+
+#[derive(Debug)]
+pub struct Scratch {
+ path: PathBuf,
+ keep: bool,
+}
+
+impl Scratch {
+ /// A new directory below `parent`, readable by its owner only.
+ pub fn new(parent: &Path, prefix: &str) -> Result<Self> {
+ use std::os::unix::fs::DirBuilderExt;
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(0o700)
+ .create(parent)
+ .with_context(|| format!("creating {}", parent.display()))?;
+ let path = parent.join(format!("{prefix}{}", crate::new_id()?));
+ std::fs::DirBuilder::new()
+ .mode(0o700)
+ .create(&path)
+ .with_context(|| format!("creating {}", path.display()))?;
+ Ok(Self { path, keep: false })
+ }
+
+ pub fn path(&self) -> &Path {
+ &self.path
+ }
+
+ /// Its path, no longer removed when dropped: it has been moved, or is kept.
+ pub fn keep(mut self) -> PathBuf {
+ self.keep = true;
+ self.path.clone()
+ }
+
+ /// Gives the files below it `mode`, and the directories (it too) the mode to reach
+ /// them: `0o400` makes it read-only, `0o644` readable by all.
+ pub fn set_modes(&self, mode: u32) -> Result<()> {
+ set_modes(&self.path, mode)
+ }
+}
+
+impl Drop for Scratch {
+ fn drop(&mut self) {
+ if !self.keep {
+ // A read-only directory's entries can't be removed: writable first.
+ let _ = set_modes(&self.path, 0o600);
+ let _ = std::fs::remove_dir_all(&self.path);
+ }
+ }
+}
+
+/// Files below `dir` get `mode`, directories (`dir` too) the mode to reach them, set
+/// on the way down so each can still be entered.
+pub fn set_modes(dir: &Path, mode: u32) -> Result<()> {
+ let directory = crate::content::directory_mode(mode) | 0o100;
+ let reach = std::fs::Permissions::from_mode(directory | 0o700);
+ std::fs::set_permissions(dir, reach).with_context(|| format!("chmod {}", dir.display()))?;
+ for entry in std::fs::read_dir(dir)? {
+ let entry = entry?;
+ if entry.file_type()?.is_dir() {
+ set_modes(&entry.path(), mode)?;
+ } else {
+ std::fs::set_permissions(entry.path(), std::fs::Permissions::from_mode(mode))?;
+ }
+ }
+ std::fs::set_permissions(dir, std::fs::Permissions::from_mode(directory))?;
+ Ok(())
+}
diff --git a/src/store.rs b/src/store.rs
new file mode 100644
index 0000000..b25495e
--- /dev/null
+++ b/src/store.rs
@@ -0,0 +1,225 @@
+//! Snapshots on disk, and the views in place (docs/design.md, 5.8).
+//!
+//! ```text
+//! STATE/lock
+//! STATE/channels/CHANNEL/current -> snapshots/ID
+//! STATE/channels/CHANNEL/snapshots/ID/snapshot.json id, and the id it was built on
+//! STATE/channels/CHANNEL/snapshots/ID/schema.json the schema it was accepted under
+//! STATE/channels/CHANNEL/snapshots/ID/entries/SLOT
+//! RUN/views/VIEW -> .generations/VIEW.ID
+//! RUN/tmp/ scratch
+//! ```
+//!
+//! Entries are root's (mode 0600). A new snapshot or view generation is written
+//! next to the old one and put in place by replacing a symbolic link, so a reader
+//! sees one or the other, never a mix.
+
+use std::fs::File;
+use std::os::unix::fs::DirBuilderExt;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+
+use crate::content::{self, Content};
+use crate::scratch::Scratch;
+
+pub struct Store {
+ pub state: PathBuf,
+ pub run: PathBuf,
+}
+
+#[derive(Debug, Clone)]
+pub struct Snapshot {
+ pub id: String,
+ pub base: Option<String>,
+ pub content: Content,
+ /// The schema it was accepted under, as it was.
+ pub schema: Vec<u8>,
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct SnapshotFile {
+ id: String,
+ channel: String,
+ base: Option<String>,
+}
+
+/// Held while the store is used; released when dropped.
+pub struct Lock(#[allow(dead_code)] File);
+
+impl Store {
+ /// The store in `state` and `run`, made absolute: programs run in a directory of
+ /// their own.
+ pub fn new(state: &Path, run: &Path) -> Self {
+ let absolute = |path: &Path| std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
+ Self {
+ state: absolute(state),
+ run: absolute(run),
+ }
+ }
+
+ /// Waits for, and takes, the store's lock: one receptor at a time.
+ pub fn lock(&self) -> Result<Lock> {
+ create_dir(&self.state, 0o700)?;
+ let path = self.state.join("lock");
+ let file = File::options()
+ .create(true)
+ .truncate(false)
+ .write(true)
+ .open(&path)
+ .with_context(|| format!("opening {}", path.display()))?;
+ file.lock()
+ .with_context(|| format!("locking {}", path.display()))?;
+ Ok(Lock(file))
+ }
+
+ /// Where programs get their scratch directories.
+ pub fn scratch(&self) -> PathBuf {
+ self.run.join("tmp")
+ }
+
+ fn channel_dir(&self, channel: &str) -> PathBuf {
+ self.state.join("channels").join(channel)
+ }
+
+ /// The channels that have a snapshot.
+ pub fn channels(&self) -> Result<Vec<String>> {
+ let dir = self.state.join("channels");
+ let mut channels = Vec::new();
+ match std::fs::read_dir(&dir) {
+ Ok(entries) => {
+ for entry in entries {
+ if let Ok(name) = entry?.file_name().into_string() {
+ channels.push(name);
+ }
+ }
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())),
+ }
+ channels.sort();
+ Ok(channels)
+ }
+
+ /// The current snapshot of `channel`, if there is one.
+ pub fn current(&self, channel: &str) -> Result<Option<Snapshot>> {
+ let link = self.channel_dir(channel).join("current");
+ let target = match std::fs::read_link(&link) {
+ Ok(target) => target,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
+ Err(error) => return Err(error).with_context(|| format!("reading {}", link.display())),
+ };
+ let dir = self.channel_dir(channel).join(target);
+ let path = dir.join("snapshot.json");
+ let file: SnapshotFile = serde_json::from_slice(
+ &std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?,
+ )
+ .with_context(|| format!("reading {}", path.display()))?;
+ if file.channel != channel {
+ bail!("{} is of channel {}", path.display(), file.channel);
+ }
+ let schema = std::fs::read(dir.join("schema.json"))
+ .with_context(|| format!("reading {}", dir.join("schema.json").display()))?;
+ Ok(Some(Snapshot {
+ id: file.id,
+ base: file.base,
+ content: content::read_dir(&dir.join("entries"))?,
+ schema,
+ }))
+ }
+
+ /// Makes `content` the current snapshot of `channel`, accepted under `schema`,
+ /// built on `base`; returns its id. The snapshot it replaces is removed.
+ pub fn commit(
+ &self,
+ channel: &str,
+ content: &Content,
+ base: Option<&str>,
+ schema: &[u8],
+ ) -> Result<String> {
+ let id = crate::new_id()?;
+ let snapshots = self.channel_dir(channel).join("snapshots");
+ create_dir(&snapshots, 0o700)?;
+ let new = snapshots.join(format!(".{id}.new"));
+ create_dir(&new, 0o700)?;
+ let file = SnapshotFile {
+ id: id.clone(),
+ channel: channel.to_owned(),
+ base: base.map(str::to_owned),
+ };
+ content::write_file(
+ &new.join("snapshot.json"),
+ &serde_json::to_vec_pretty(&file)?,
+ 0o600,
+ )?;
+ content::write_file(&new.join("schema.json"), schema, 0o600)?;
+ content::write_dir(content, &new.join("entries"), 0o600)?;
+ std::fs::rename(&new, snapshots.join(&id))?;
+ let old = std::fs::read_link(self.channel_dir(channel).join("current")).ok();
+ replace_link(
+ &self.channel_dir(channel).join("current"),
+ &Path::new("snapshots").join(&id),
+ )?;
+ if let Some(old) = old {
+ std::fs::remove_dir_all(self.channel_dir(channel).join(old))?;
+ }
+ Ok(id)
+ }
+
+ /// The directory the view `name` is in place at, if it is.
+ pub fn installed_view(&self, name: &str) -> Option<PathBuf> {
+ let link = self.run.join("views").join(name);
+ std::fs::read_link(&link).ok()?;
+ Some(link)
+ }
+
+ /// Puts what was rendered for the view `name` in place (or, if nothing was, takes
+ /// it away), readable by root only if it is secret.
+ pub fn install_view(&self, name: &str, rendered: Option<Scratch>, secret: bool) -> Result<()> {
+ let views = self.run.join("views");
+ create_dir(&views, 0o755)?;
+ let link = views.join(name);
+ let old = std::fs::read_link(&link).ok();
+ match rendered {
+ Some(rendered) => {
+ let generations = views.join(".generations");
+ create_dir(&generations, 0o755)?;
+ let mode = if secret { 0o600 } else { 0o644 };
+ rendered.set_modes(mode)?;
+ let target = Path::new(".generations").join(format!("{name}.{}", crate::new_id()?));
+ std::fs::rename(rendered.path(), views.join(&target))
+ .with_context(|| format!("moving view {name} in place"))?;
+ rendered.keep();
+ replace_link(&link, &target)?;
+ }
+ None => {
+ if old.is_some() {
+ std::fs::remove_file(&link)?;
+ }
+ }
+ }
+ if let Some(old) = old {
+ std::fs::remove_dir_all(views.join(old))?;
+ }
+ Ok(())
+ }
+}
+
+fn create_dir(path: &Path, mode: u32) -> Result<()> {
+ std::fs::DirBuilder::new()
+ .recursive(true)
+ .mode(mode)
+ .create(path)
+ .with_context(|| format!("creating {}", path.display()))
+}
+
+/// Points the symbolic link `link` at `target`, atomically.
+fn replace_link(link: &Path, target: &Path) -> Result<()> {
+ let name = link.file_name().unwrap_or_default().to_string_lossy();
+ let new = link.with_file_name(format!(".{name}.new-link"));
+ let _ = std::fs::remove_file(&new);
+ std::os::unix::fs::symlink(target, &new)?;
+ std::fs::rename(&new, link).with_context(|| format!("replacing {}", link.display()))
+}
diff --git a/src/submission.rs b/src/submission.rs
new file mode 100644
index 0000000..1958909
--- /dev/null
+++ b/src/submission.rs
@@ -0,0 +1,219 @@
+//! What gets handed to the host (docs/design.md, 5.4): a directory with a manifest,
+//! and the entries and records its items set at `channels/CHANNEL/SLOT`.
+//!
+//! ```json
+//! {
+//! "submission": 1,
+//! "channel": "fleet",
+//! "complete": false,
+//! "base": "4f0c…",
+//! "items": [
+//! { "address": "fleet/hosts/ne", "op": "set", "group": "ne" },
+//! { "address": "fleet/users/tv", "op": "set", "required": false },
+//! { "address": "fleet/hosts/wu", "op": "remove" }
+//! ],
+//! "groups": { "ne": { "required": true } }
+//! }
+//! ```
+//!
+//! Items and groups are required unless they say otherwise; an item in a group is as
+//! required as its group, and says nothing of its own. An item setting records has
+//! them in its entry's file, as an object holding just the records set.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use crate::content;
+use crate::name::Address;
+
+pub const VERSION: u32 = 1;
+pub const MANIFEST: &str = "manifest.json";
+pub const CHANNELS: &str = "channels";
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Manifest {
+ pub submission: u32,
+ pub channel: String,
+ #[serde(default)]
+ pub complete: bool,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub base: Option<String>,
+ pub items: Vec<ItemSpec>,
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub groups: BTreeMap<String, GroupSpec>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct ItemSpec {
+ pub address: Address,
+ pub op: Op,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub required: Option<bool>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub group: Option<String>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Op {
+ Set,
+ Remove,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct GroupSpec {
+ #[serde(default = "yes")]
+ pub required: bool,
+}
+
+fn yes() -> bool {
+ true
+}
+
+/// A submission, read.
+#[derive(Debug, Clone)]
+pub struct Submission {
+ pub dir: PathBuf,
+ pub channel: String,
+ pub complete: bool,
+ pub base: Option<String>,
+ pub items: Vec<Item>,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct Item {
+ pub address: Address,
+ pub required: bool,
+ pub group: Option<String>,
+ pub change: Change,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum Change {
+ Entry(Vec<u8>),
+ Record(Value),
+ Remove,
+}
+
+impl Submission {
+ pub fn load(dir: &Path) -> Result<Self> {
+ let path = dir.join(MANIFEST);
+ let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?;
+ let manifest: Manifest = serde_json::from_slice(&bytes)
+ .with_context(|| format!("manifest {}", path.display()))?;
+ Self::from_manifest(dir, manifest).with_context(|| format!("submission {}", dir.display()))
+ }
+
+ fn from_manifest(dir: &Path, manifest: Manifest) -> Result<Self> {
+ if manifest.submission != VERSION {
+ bail!(
+ "submission version {} is not {VERSION}",
+ manifest.submission
+ );
+ }
+ crate::name::check("channel", &manifest.channel)?;
+ let files = dir.join(CHANNELS).join(&manifest.channel);
+ let mut seen: Vec<&Address> = Vec::new();
+ let mut used = BTreeSet::new();
+ let mut items = Vec::new();
+ for spec in &manifest.items {
+ let address = &spec.address;
+ if address.channel != manifest.channel {
+ bail!("item {address} is not of channel {}", manifest.channel);
+ }
+ if let Some(other) = seen.iter().find(|other| other.overlaps(address)) {
+ bail!("items {other} and {address} overlap");
+ }
+ seen.push(address);
+ let required = match (&spec.group, spec.required) {
+ (Some(group), None) => match manifest.groups.get(group) {
+ Some(group) => group.required,
+ None => bail!("item {address}: no group {group}"),
+ },
+ (Some(_), Some(_)) => {
+ bail!("item {address} is in a group, which says whether it is required")
+ }
+ (None, required) => required.unwrap_or(true),
+ };
+ let change = match (spec.op, &address.key) {
+ (Op::Remove, _) => Change::Remove,
+ (Op::Set, None) => {
+ used.insert(address.slot.clone());
+ let path = files.join(&address.slot);
+ Change::Entry(
+ std::fs::read(&path).with_context(|| {
+ format!("item {address}: reading {}", path.display())
+ })?,
+ )
+ }
+ (Op::Set, Some(key)) => {
+ used.insert(address.slot.clone());
+ let path = files.join(&address.slot);
+ let bytes = std::fs::read(&path)
+ .with_context(|| format!("item {address}: reading {}", path.display()))?;
+ let records = content::records(&bytes)
+ .with_context(|| format!("item {address}: {}", path.display()))?;
+ match records.get(key) {
+ Some(value) => Change::Record(value.clone()),
+ None => bail!("item {address}: no record {key:?} in {}", path.display()),
+ }
+ }
+ };
+ items.push(Item {
+ address: address.clone(),
+ required,
+ group: spec.group.clone(),
+ change,
+ });
+ }
+ // Records a file holds that no item sets, and files no item reads, would be
+ // handed over and silently ignored.
+ for slot in &used {
+ let records_set: BTreeSet<&str> = items
+ .iter()
+ .filter(|item| item.address.slot == *slot)
+ .filter_map(|item| item.address.key.as_deref())
+ .collect();
+ if records_set.is_empty() {
+ continue;
+ }
+ let path = files.join(slot);
+ let records = content::records(&std::fs::read(&path)?)?;
+ if let Some(key) = records
+ .keys()
+ .find(|key| !records_set.contains(key.as_str()))
+ {
+ bail!(
+ "{} holds record {key:?}, which no item sets",
+ path.display()
+ );
+ }
+ }
+ for (slot, _) in content::read_dir(&files)? {
+ if !used.contains(&slot) {
+ bail!("{} is set by no item", files.join(slot).display());
+ }
+ }
+ if let Some(group) = manifest
+ .groups
+ .keys()
+ .find(|group| !items.iter().any(|item| item.group.as_ref() == Some(*group)))
+ {
+ bail!("group {group} has no items");
+ }
+ Ok(Self {
+ dir: dir.to_owned(),
+ channel: manifest.channel,
+ complete: manifest.complete,
+ base: manifest.base,
+ items,
+ })
+ }
+}
diff --git a/src/view.rs b/src/view.rs
new file mode 100644
index 0000000..b7bab6c
--- /dev/null
+++ b/src/view.rs
@@ -0,0 +1,181 @@
+//! Views (docs/design.md, 5.3): rendered into scratch, compared with what is in
+//! place, and how they changed.
+
+use std::collections::BTreeMap;
+use std::path::{Path, PathBuf};
+
+use anyhow::Result;
+use serde::Serialize;
+
+use crate::content::Content;
+use crate::name::Address;
+use crate::program::{self, Given, Role};
+use crate::schema::{Schema, ViewSpec};
+use crate::scratch::Scratch;
+
+/// The entries of every channel a view may be made from: the one being planned as it
+/// would be, the others as they are.
+pub type Entries<'a> = BTreeMap<&'a str, &'a Content>;
+
+/// Renders the view `name` from `entries` into scratch below `scratch`; nothing if it
+/// is an entry's own and that entry isn't there.
+pub fn render(
+ schema: &Schema,
+ name: &str,
+ view: &ViewSpec,
+ entries: &Entries,
+ scratch: &Path,
+) -> Result<Option<Scratch>> {
+ let entry = |address: &Address| {
+ entries
+ .get(address.channel.as_str())
+ .and_then(|content| content.get(&address.slot))
+ };
+ match &view.renderer {
+ None => {
+ let address = &view.from[0];
+ let Some(bytes) = entry(address) else {
+ return Ok(None);
+ };
+ let out = Scratch::new(scratch, "view-")?;
+ crate::content::write_file(&out.path().join(&address.slot), bytes, 0o600)?;
+ Ok(Some(out))
+ }
+ Some(renderer) => {
+ let given = Given {
+ slots: view
+ .from
+ .iter()
+ .map(|address| {
+ let media_type = schema
+ .slot(address)
+ .map(|slot| slot.media_type.as_str())
+ .unwrap_or_default();
+ (
+ address.clone(),
+ (media_type, entry(address).map(Vec::as_slice)),
+ )
+ })
+ .collect(),
+ };
+ let outcome = program::run(renderer, Role::Renderer, name, &given, scratch)?;
+ // What it can't render, it fails on; and it may write regular files and
+ // directories only.
+ program::files_below(outcome.out.path())?;
+ Ok(Some(outcome.out))
+ }
+ }
+}
+
+/// How a view changes.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Change {
+ Unchanged,
+ Added,
+ Removed,
+ Changed,
+}
+
+/// One file of a view that changes.
+#[derive(Debug, Clone, Serialize)]
+pub struct FileChange {
+ pub path: PathBuf,
+ pub change: Change,
+ /// As diffutils says it (`diff`).
+ pub diff: String,
+}
+
+/// How what is in place (`old`) would become what was rendered (`new`): the view as a
+/// whole, and its files. A secret view's files are named, but no diff is made.
+pub fn compare(
+ old: Option<&Path>,
+ new: Option<&Path>,
+ secret: bool,
+) -> Result<(Change, Vec<FileChange>)> {
+ let read = |dir: Option<&Path>| -> Result<BTreeMap<PathBuf, Vec<u8>>> {
+ match dir {
+ Some(dir) => program::files_below(dir),
+ None => Ok(BTreeMap::new()),
+ }
+ };
+ let (old_files, new_files) = (read(old)?, read(new)?);
+ let mut files = Vec::new();
+ for (path, bytes) in &new_files {
+ match old_files.get(path) {
+ Some(old) if old == bytes => {}
+ Some(old) => files.push(FileChange {
+ path: path.clone(),
+ change: Change::Changed,
+ diff: diff(path, Some(old), Some(bytes), secret),
+ }),
+ None => files.push(FileChange {
+ path: path.clone(),
+ change: Change::Added,
+ diff: diff(path, None, Some(bytes), secret),
+ }),
+ }
+ }
+ for (path, bytes) in &old_files {
+ if !new_files.contains_key(path) {
+ files.push(FileChange {
+ path: path.clone(),
+ change: Change::Removed,
+ diff: diff(path, Some(bytes), None, secret),
+ });
+ }
+ }
+ let change = match (old, new) {
+ (None, None) => Change::Unchanged,
+ (None, Some(_)) => Change::Added,
+ (Some(_), None) => Change::Removed,
+ (Some(_), Some(_)) if files.is_empty() => Change::Unchanged,
+ (Some(_), Some(_)) => Change::Changed,
+ };
+ Ok((change, files))
+}
+
+/// How a file changes, as diffutils' `diff -ru a b` says it: a unified diff for text in
+/// a public view; for a secret view, or bytes that aren't text, only that the file
+/// differs, or is only on one side.
+fn diff(path: &Path, old: Option<&[u8]>, new: Option<&[u8]>, secret: bool) -> String {
+ let name = path.display().to_string();
+ let text = |bytes: Option<&[u8]>| match bytes {
+ None => Some(String::new()),
+ Some(bytes) => std::str::from_utf8(bytes).ok().map(str::to_owned),
+ };
+ let (old_text, new_text) = (text(old), text(new));
+ match (old_text, new_text) {
+ (Some(old), Some(new)) if !secret => similar::TextDiff::from_lines(&old, &new)
+ .unified_diff()
+ .header(&format!("a/{name}"), &format!("b/{name}"))
+ .to_string(),
+ _ => match (old, new) {
+ (None, _) => format!("Only in b: {name}\n"),
+ (_, None) => format!("Only in a: {name}\n"),
+ _ if secret => format!("Files a/{name} and b/{name} differ\n"),
+ _ => format!("Binary files a/{name} and b/{name} differ\n"),
+ },
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn diffs_as_diffutils_says_them() {
+ let path = Path::new("f");
+ assert_eq!(
+ diff(path, Some(b"a\n"), Some(b"b\n"), true),
+ "Files a/f and b/f differ\n"
+ );
+ assert_eq!(
+ diff(path, Some(b"\xff"), Some(b"\xfe"), false),
+ "Binary files a/f and b/f differ\n"
+ );
+ assert_eq!(diff(path, None, Some(b"k"), true), "Only in b: f\n");
+ assert_eq!(diff(path, Some(b"\xff"), None, false), "Only in a: f\n");
+ assert!(diff(path, Some(b"a\n"), Some(b"b\n"), false).contains("-a\n+b\n"));
+ }
+}