aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-12-01 05:13:36 +0000
committertv <tv@krebsco.de>2026-12-01 05:13:36 +0000
commit60da3a663ed070c1e6c5d2a1b171e316a0395bbd (patch)
treec11fcce3cb5480413dce3d1aefa7d05b681b3df6 /src
parentcd06c0a8ed52e9c251a5f2c0debb6f263ce74705 (diff)
enstate: --pack --dry-run, every problem of a source list
Reads every source and writes nothing: every problem, not just the first, by address, with kind, location and variables, and the source, as text or JSON (--json): an item the schema has no slot for, a record in a type without records, a required slot without an item, a location that doesn't exist, a source that can't be read (with what it said), a record that isn't JSON. Exit status 1 if there are problems. --pack itself refuses with the same list; --out isn't for a dry run, --json only for one. The completion offers accordingly.
Diffstat (limited to 'src')
-rw-r--r--src/main.rs65
-rw-r--r--src/pack.rs405
2 files changed, 334 insertions, 136 deletions
diff --git a/src/main.rs b/src/main.rs
index 2df4c78..ca7d0df 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -147,13 +147,13 @@ fn command() -> Command {
Arg::new("json")
.long("json")
.action(ArgAction::SetTrue)
- .help("Print JSON (--plan, --apply, --stage, --status, --materialize, --migrate)"),
+ .help("Print JSON (--plan, --apply, --stage, --status, --materialize, --migrate, --pack --dry-run)"),
)
.arg(
Arg::new("dry-run")
.long("dry-run")
.action(ArgAction::SetTrue)
- .help("With --migrate: say what it would do, changing nothing"),
+ .help("With --migrate, --pack: say what it would do, or what keeps it from it, changing nothing"),
)
.arg(
Arg::new("out")
@@ -229,11 +229,12 @@ fn run() -> Result<ExitCode> {
if out.is_some() && command != "pack" {
bail!("--out is for --pack only");
}
- if matches.get_flag("dry-run") && command != "migrate" {
- bail!("--dry-run is for --migrate only");
+ let dry_run = matches.get_flag("dry-run");
+ if dry_run && !matches!(command, "migrate" | "pack") {
+ bail!("--dry-run is for --migrate and --pack only");
}
- if json && command == "pack" {
- bail!("--json is not for --pack");
+ if json && command == "pack" && !dry_run {
+ bail!("--json is for --pack only with --dry-run");
}
// A setting given as an argument that the command doesn't use is an error; from a
// configuration file, which holds them for every command, it isn't.
@@ -245,9 +246,26 @@ fn run() -> Result<ExitCode> {
}
}
if command == "pack" {
- let out = out.context("--pack needs --out DIR")?;
let schema = settings.schema.as_deref().map(Schema::load).transpose()?;
- for warning in enstate::pack::pack(path.as_deref().unwrap(), &out, schema.as_ref())? {
+ let path = path.as_deref().unwrap();
+ if dry_run {
+ if out.is_some() {
+ bail!("--out is not for a dry run");
+ }
+ let report = enstate::pack::dry_run(path, schema.as_ref())?;
+ if json {
+ println!("{}", serde_json::to_string_pretty(&report)?);
+ } else {
+ print_report(&report)?;
+ }
+ return Ok(if report.problems.is_empty() {
+ ExitCode::SUCCESS
+ } else {
+ ExitCode::from(1)
+ });
+ }
+ let out = out.context("--pack needs --out DIR, or --dry-run")?;
+ for warning in enstate::pack::pack(path, &out, schema.as_ref())? {
eprintln!("enstate: warning: {warning}");
}
return Ok(ExitCode::SUCCESS);
@@ -321,13 +339,8 @@ fn run() -> Result<ExitCode> {
Ok(ExitCode::SUCCESS)
}
"migrate" => {
- let migration = enstate::migrate::migrate(
- &schema,
- &schema_bytes,
- &store,
- matches.get_flag("dry-run"),
- &systemctl,
- )?;
+ let migration =
+ enstate::migrate::migrate(&schema, &schema_bytes, &store, dry_run, &systemctl)?;
if json {
println!("{}", serde_json::to_string_pretty(&migration)?);
} else {
@@ -662,3 +675,25 @@ fn uses(command: &str, setting: &str) -> bool {
_ => true,
}
}
+
+fn print_report(report: &enstate::pack::Report) -> Result<()> {
+ let style = Style::new();
+ let mut out = std::io::stdout().lock();
+ for warning in &report.warnings {
+ writeln!(out, "{} {warning}", style.paint("33", "warning:"))?;
+ }
+ for problem in &report.problems {
+ writeln!(out, "{problem}")?;
+ }
+ let verdict = if report.problems.is_empty() {
+ style.paint("32", "nothing missing")
+ } else {
+ style.paint("31", &format!("{} problems", report.problems.len()))
+ };
+ writeln!(
+ out,
+ "channel {}: {} items, {verdict}",
+ report.channel, report.items
+ )?;
+ Ok(())
+}
diff --git a/src/pack.rs b/src/pack.rs
index 5bbed1d..7870bd0 100644
--- a/src/pack.rs
+++ b/src/pack.rs
@@ -32,7 +32,7 @@ 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::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::content;
@@ -173,98 +173,83 @@ fn include_locations(
Ok(())
}
-/// 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. Returns warnings: an
-/// entry whose source is text with placeholders loses its trailing line breaks.
-pub fn pack(path: &Path, out: &Path, schema: Option<&Schema>) -> Result<Vec<String>> {
- let list = SourceList::load(path)?;
- let dir = dir_of(path);
- 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.source.is_some() && item.location.is_some() {
- bail!("item {key}: give a source or a location, not both");
- }
- if item.location.is_none() && !item.variables.is_empty() {
- let fields: Vec<_> = item.variables.keys().map(String::as_str).collect();
- bail!(
- "item {key}: unknown fields {} (variables are for an item with a location)",
- fields.join(", ")
- );
- }
- if item.remove == (item.source.is_some() || item.location.is_some()) {
- bail!("item {key}: give either a source (or a location) 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();
- let mut warnings = Vec::new();
- for (address, item) in &items {
- // The item's own source, or its location's with its variables.
- let source = match (&item.source, &item.location) {
- (Some(source), _) => Some((source, dir.as_path(), None)),
- (None, Some(name)) => {
- let location = list
- .locations
- .get(name)
- .with_context(|| format!("item {address}: no location {name}"))?;
- Some((&location.source, location.dir.as_path(), Some(name)))
- }
- (None, None) => None,
- };
- if let Some((source, source_dir, location)) = source {
- let what = match location {
- Some(name) => format!("item {address} (location {name})"),
- None => format!("item {address}"),
- };
- let importer = importer(source, source_dir, address.key.is_none())
- .with_context(|| what.clone())?;
- if address.key.is_none() && importer.is_interpolation() {
- warnings.push(format!(
- "{what}: its source is text with placeholders, which loses \
- trailing line breaks; for the entry as it is, a whole-value source \
- (cmd:…, file:…, or a table) takes it byte-exact"
- ));
- }
- let variables = variables(item).with_context(|| what.clone())?;
- let imported = importer
- .fetch_with(&variables)
- .with_context(|| format!("{what}: {}", 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);
- }
+/// One thing that keeps a source list from making a submission: what, where, and, for
+/// an item read by a location, which location with which variables.
+#[derive(Debug, Clone, Serialize)]
+pub struct Problem {
+ /// `CHANNEL/SLOT` or `CHANNEL/SLOT/KEY`; the channel alone for the channel's.
+ pub address: String,
+ /// What kind: `no-channel`, `not-in-schema`, `no-records`, `no-item`, `item`,
+ /// `no-location`, `source`, `unreadable`, `not-json`, `whole-and-records`.
+ pub problem: &'static str,
+ pub message: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub location: Option<String>,
+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]
+ pub variables: BTreeMap<String, String>,
+ /// The source, as written (its placeholders not replaced).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub source: Option<String>,
+}
+
+impl std::fmt::Display for Problem {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.address)?;
+ if let Some(location) = &self.location {
+ write!(f, " (location {location}")?;
+ for (name, value) in &self.variables {
+ write!(f, ", {name} {value}")?;
}
+ write!(f, ")")?;
}
- specs.push(ItemSpec {
- address: address.clone(),
- op: if item.remove { Op::Remove } else { Op::Set },
- required: item.required,
- group: item.group.clone(),
- });
+ write!(f, ": {}", self.message)
}
- if let Some(slot) = records.keys().find(|slot| entries.contains_key(*slot)) {
- bail!("slot {slot} is given both as a whole and by records");
+}
+
+/// What a source list would make, and what keeps it from it.
+#[derive(Debug, Clone, Serialize)]
+pub struct Report {
+ pub channel: String,
+ /// Its items.
+ pub items: usize,
+ pub problems: Vec<Problem>,
+ pub warnings: Vec<String>,
+}
+
+/// A source list read, its sources fetched.
+struct Gathered {
+ list: SourceList,
+ report: Report,
+ entries: BTreeMap<String, Vec<u8>>,
+ records: BTreeMap<String, Map<String, Value>>,
+ specs: Vec<ItemSpec>,
+}
+
+/// Reads the source list at `path` and every source in it, checked against `schema` if
+/// one is given, and writes nothing: every problem, not just the first.
+pub fn dry_run(path: &Path, schema: Option<&Schema>) -> Result<Report> {
+ Ok(gather(path, schema)?.report)
+}
+
+/// 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; refused, with every
+/// problem, if there are any. Returns warnings: an entry whose source is text with
+/// placeholders loses its trailing line breaks.
+pub fn pack(path: &Path, out: &Path, schema: Option<&Schema>) -> Result<Vec<String>> {
+ let Gathered {
+ list,
+ report,
+ entries,
+ records,
+ specs,
+ } = gather(path, schema)?;
+ if !report.problems.is_empty() {
+ let problems: Vec<String> = report.problems.iter().map(|p| format!(" {p}")).collect();
+ bail!(
+ "{} can't make a submission:\n{}",
+ path.display(),
+ problems.join("\n")
+ );
}
let manifest = Manifest {
submission: submission::VERSION,
@@ -297,7 +282,215 @@ pub fn pack(path: &Path, out: &Path, schema: Option<&Schema>) -> Result<Vec<Stri
content::write_file(&out.join(submission::MANIFEST), &manifest_bytes, 0o600)?;
// What was written is a submission the receptor reads.
submission::Submission::load(out)?;
- Ok(warnings)
+ Ok(report.warnings)
+}
+
+fn gather(path: &Path, schema: Option<&Schema>) -> Result<Gathered> {
+ let list = SourceList::load(path)?;
+ let dir = dir_of(path);
+ name::check("channel", &list.channel)?;
+ let mut problems = Vec::new();
+ let problem = |address: String, problem: &'static str, message: String| Problem {
+ address,
+ problem,
+ message,
+ location: None,
+ variables: BTreeMap::new(),
+ source: None,
+ };
+ let mut items = Vec::new();
+ for (key, item) in &list.items {
+ let written = format!("{}/{key}", list.channel);
+ let address: Address = match written.parse() {
+ Ok(address) => address,
+ Err(error) => {
+ problems.push(problem(written, "item", format!("{error:#}")));
+ continue;
+ }
+ };
+ let mistake = if item.source.is_some() && item.location.is_some() {
+ Some("give a source or a location, not both".to_owned())
+ } else if item.location.is_none() && !item.variables.is_empty() {
+ let fields: Vec<_> = item.variables.keys().map(String::as_str).collect();
+ Some(format!(
+ "unknown fields {} (variables are for an item with a location)",
+ fields.join(", ")
+ ))
+ } else if item.remove == (item.source.is_some() || item.location.is_some()) {
+ Some("give either a source (or a location) or \"remove\": true".to_owned())
+ } else {
+ None
+ };
+ match mistake {
+ Some(message) => problems.push(problem(address.to_string(), "item", message)),
+ None => items.push((address, item)),
+ }
+ }
+ // Against the schema.
+ let mut unusable: Vec<Address> = Vec::new();
+ if let Some(schema) = schema {
+ match schema.channel(&list.channel) {
+ None => problems.push(problem(
+ list.channel.clone(),
+ "no-channel",
+ format!("the schema has no channel {}", list.channel),
+ )),
+ Some(channel) => {
+ for (address, _) in &items {
+ match channel.slots.get(&address.slot) {
+ None => {
+ problems.push(problem(
+ address.to_string(),
+ "not-in-schema",
+ format!("the schema has no slot {}", address.of_entry()),
+ ));
+ unusable.push(address.clone());
+ }
+ Some(slot)
+ if address.key.is_some() && !crate::media::keyed(&slot.media_type) =>
+ {
+ problems.push(problem(
+ address.to_string(),
+ "no-records",
+ format!("type {} holds no records", slot.media_type),
+ ));
+ unusable.push(address.clone());
+ }
+ Some(_) => {}
+ }
+ }
+ 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 {
+ problems.push(problem(
+ format!("{}/{slot}", list.channel),
+ "no-item",
+ "required by the schema, but the source list, which is \
+ complete, has no item for it"
+ .to_owned(),
+ ));
+ }
+ }
+ }
+ }
+ }
+ }
+ // Every source, even after a problem, so that all of them show.
+ let mut entries: BTreeMap<String, Vec<u8>> = BTreeMap::new();
+ let mut records: BTreeMap<String, Map<String, Value>> = BTreeMap::new();
+ let mut specs = Vec::new();
+ let mut warnings = Vec::new();
+ for (address, item) in &items {
+ specs.push(ItemSpec {
+ address: address.clone(),
+ op: if item.remove { Op::Remove } else { Op::Set },
+ required: item.required,
+ group: item.group.clone(),
+ });
+ if unusable.contains(address) {
+ continue;
+ }
+ let mut problem_here = |kind: &'static str, message: String, source: Option<String>| {
+ let mut found = problem(address.to_string(), kind, message);
+ found.location = item.location.clone();
+ found.variables = item
+ .variables
+ .iter()
+ .map(|(name, value)| match value {
+ Value::String(text) => (name.clone(), text.clone()),
+ other => (name.clone(), other.to_string()),
+ })
+ .collect();
+ found.source = source;
+ problems.push(found);
+ };
+ // The item's own source, or its location's with its variables.
+ let (source, source_dir) = match (&item.source, &item.location) {
+ (Some(source), _) => (source, dir.as_path()),
+ (None, Some(name)) => match list.locations.get(name) {
+ Some(location) => (&location.source, location.dir.as_path()),
+ None => {
+ problem_here("no-location", format!("no location {name}"), None);
+ continue;
+ }
+ },
+ (None, None) => continue,
+ };
+ let importer = match importer(source, source_dir, address.key.is_none()) {
+ Ok(importer) => importer,
+ Err(error) => {
+ problem_here("source", format!("{error:#}"), None);
+ continue;
+ }
+ };
+ if address.key.is_none() && importer.is_interpolation() {
+ warnings.push(format!(
+ "item {address}: its source is text with placeholders, which loses \
+ trailing line breaks; for the entry as it is, a whole-value source \
+ (cmd:…, file:…, or a table) takes it byte-exact"
+ ));
+ }
+ let fetched = variables(item).and_then(|variables| importer.fetch_with(&variables));
+ let imported = match fetched {
+ Ok(imported) => imported,
+ Err(error) => {
+ problem_here(
+ "unreadable",
+ format!("can't be read: {error:#}"),
+ Some(importer.describe()),
+ );
+ continue;
+ }
+ };
+ match &address.key {
+ None => {
+ entries.insert(address.slot.clone(), bytes(imported));
+ }
+ Some(key) => {
+ let value = match imported {
+ Imported::Json(value) => value,
+ other => match serde_json::from_slice(&bytes(other)) {
+ Ok(value) => value,
+ Err(error) => {
+ problem_here(
+ "not-json",
+ format!("not JSON: {error}"),
+ Some(importer.describe()),
+ );
+ continue;
+ }
+ },
+ };
+ records
+ .entry(address.slot.clone())
+ .or_default()
+ .insert(key.clone(), value);
+ }
+ }
+ }
+ for slot in records.keys().filter(|slot| entries.contains_key(*slot)) {
+ problems.push(problem(
+ format!("{}/{slot}", list.channel),
+ "whole-and-records",
+ "given both as a whole and by records".to_owned(),
+ ));
+ }
+ let report = Report {
+ channel: list.channel.clone(),
+ items: list.items.len(),
+ problems,
+ warnings,
+ };
+ Ok(Gathered {
+ list,
+ report,
+ entries,
+ records,
+ specs,
+ })
}
/// The importer `source` describes, in `dir`: raw for an entry, JSON for a record.
@@ -330,36 +523,6 @@ fn bytes(imported: Imported) -> Vec<u8> {
}
}
-/// 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(())
-}
-
/// An item's variables, for its location's placeholders: its other fields, which must
/// be text.
fn variables(item: &ItemSource) -> Result<import::Variables> {