diff options
Diffstat (limited to 'src/pack.rs')
| -rw-r--r-- | src/pack.rs | 405 |
1 files changed, 284 insertions, 121 deletions
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> { |
