aboutsummaryrefslogtreecommitdiffstats
path: root/src/view.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/view.rs')
-rw-r--r--src/view.rs181
1 files changed, 181 insertions, 0 deletions
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"));
+ }
+}