Skip to main content

nibkeep_node/library/trees/
diff.rs

1//! Diffs of a tree: the copy on this device against the tree, or two points of the tree's
2//! history, file by file, with unified diffs of text and only which versions differ for the
3//! rest ([technical design: trees]).
4//!
5//! [technical design: trees]: ../../../../../docs/Technical-design.md#15-trees
6
7use std::collections::BTreeSet;
8use std::io::Read;
9
10use nibkeep_base::{EntityId, Hash, SpaceId};
11
12use super::history::{READ_LIMIT, TreePoint};
13use super::index::Version;
14use super::walk::open_found;
15use super::{Change, TreeState, version_of};
16use crate::NodeError;
17use crate::library::Library;
18
19/// How many of a file's first bytes tell whether it is text: as many as Git reads.
20const TEXT_HEAD: usize = 8_000;
21
22/// How one file or link of a tree differs between two points.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct FileDiff {
25	/// Its path at the later point, or where it was, if it is gone then.
26	pub path: String,
27	/// What changed.
28	pub change: Change,
29	/// The unified diff of its text, if both versions are text that this device holds and
30	/// they differ.
31	pub patch: Option<String>,
32	/// Whether a version is no text, so that only which versions differ is told.
33	pub binary: bool,
34	/// Whether it is a secret file, whose lines a diff shows only when asked for, with the
35	/// secrets unlocked
36	/// ([technical design: secrets in trees](../../../docs/Technical-design.md#151-secrets-in-trees)).
37	pub secret: bool,
38}
39
40/// What one side of a diff holds at a path.
41enum Side<'a> {
42	/// Nothing.
43	Nothing,
44	/// A version that the library holds.
45	Version(&'a Version),
46	/// The copy on the disk, as it was found.
47	Copy(&'a super::walk::Found),
48}
49
50impl Library {
51	/// How a tree differs: with `between` given, from its first point to its second, as
52	/// each is read ([`TreePoint`]); without, the copy on this device from the tree as the
53	/// library has it now, what a commit would record. Files are paired by what they are,
54	/// so that a move shows as one.
55	///
56	/// # Errors
57	///
58	/// Returns [`NodeError::NoRevision`] if a revision is not the tree's,
59	/// [`NodeError::NoTreeHere`] if the copy is asked for and the tree has none here, and an
60	/// error if the space or the copy cannot be read.
61	pub fn tree_diff(
62		&self,
63		space: SpaceId,
64		tree: EntityId,
65		between: Option<(TreePoint, TreePoint)>,
66	) -> Result<Vec<FileDiff>, NodeError> {
67		self.tree_diff_with(space, tree, between, false)
68	}
69
70	/// How a tree differs, as [`Library::tree_diff`] tells it, with the lines of secret files
71	/// too if `secrets` says so, which this device reads with the secrets unlocked; without,
72	/// a secret file shows only that it changed.
73	///
74	/// # Errors
75	///
76	/// As [`Library::tree_diff`].
77	pub fn tree_diff_with(
78		&self,
79		space: SpaceId,
80		tree: EntityId,
81		between: Option<(TreePoint, TreePoint)>,
82		secrets: bool,
83	) -> Result<Vec<FileDiff>, NodeError> {
84		let mut diffs = match between {
85			Some((from, to)) => {
86				let before = self.tree_state_at(space, tree, from)?;
87				let after = self.tree_state_at(space, tree, to)?;
88				self.diff_states(space, (&before, &after), secrets)?
89			}
90			None => self.diff_copy(space, tree, secrets)?,
91		};
92		diffs.sort_by(|a, b| a.path.cmp(&b.path));
93		Ok(diffs)
94	}
95
96	/// What a revision changed, as `git show` shows a commit: from the tree as its author
97	/// had it without its commit's parts to the tree with them, so that changes made
98	/// meanwhile on other devices do not slip in. `None` if `revision` is no revision of a
99	/// tree.
100	///
101	/// # Errors
102	///
103	/// Returns an error if the space cannot be read.
104	pub fn revision_diff(
105		&self,
106		space: SpaceId,
107		revision: EntityId,
108		secrets: bool,
109	) -> Result<Option<Vec<FileDiff>>, NodeError> {
110		let Some(tree) = self.tree_of_revision(space, revision)? else {
111			return Ok(None);
112		};
113		let changes = self.revision_changes(space, tree, revision)?;
114		let Some(&last) = changes.last() else {
115			return Ok(None);
116		};
117		let parts: BTreeSet<_> = changes.iter().copied().collect();
118		let (after, before) = self.tree_states_of_changes(space, tree, last, &parts)?;
119		let mut diffs = self.diff_states(space, (&before, &after), secrets)?;
120		diffs.sort_by(|a, b| a.path.cmp(&b.path));
121		Ok(Some(diffs))
122	}
123
124	/// How the tree differs between two of its states.
125	fn diff_states(
126		&self,
127		space: SpaceId,
128		(before, after): (&TreeState, &TreeState),
129		secrets: bool,
130	) -> Result<Vec<FileDiff>, NodeError> {
131		let entities: BTreeSet<EntityId> = before
132			.by_entity
133			.keys()
134			.chain(after.by_entity.keys())
135			.copied()
136			.collect();
137		let mut diffs = Vec::new();
138		for entity in entities {
139			let (path, change, old, new) =
140				match (version_of(before, entity), version_of(after, entity)) {
141					(None, Some((path, new))) => (path, Change::New, None, new),
142					(Some((path, old)), None) => (path, Change::Deleted, old, None),
143					(Some((from, old)), Some((path, new))) => {
144						let change = if from != path {
145							Change::Moved { from }
146						} else if old == new {
147							continue;
148						} else {
149							Change::Edited
150						};
151						(path, change, old, new)
152					}
153					(None, None) => continue,
154				};
155			let secret = before.is_secret(entity) || after.is_secret(entity);
156			// With the secrets locked, a secret file's versions are known nowhere but in the
157			// copy, which stands in for now alone: it is left out.
158			if secret && !self.secrets_unlocked(space) {
159				continue;
160			}
161			let old = old.as_ref().map_or(Side::Nothing, Side::Version);
162			let new = new.as_ref().map_or(Side::Nothing, Side::Version);
163			let shown = (secret, secrets);
164			diffs.push(self.file_diff(space, (path, change), (&old, &new), shown)?);
165		}
166		Ok(diffs)
167	}
168
169	/// How the copy of a tree on this device differs from the tree as the library has it.
170	fn diff_copy(
171		&self,
172		space: SpaceId,
173		tree: EntityId,
174		secrets: bool,
175	) -> Result<Vec<FileDiff>, NodeError> {
176		let _locked = self.lock_trees()?;
177		let root = self.root_here(space, tree)?;
178		let index = self.index()?;
179		let purged = self.learn_purges(space, &index)?;
180		let state = self.tree_state(space, tree)?;
181		let compared = self.compare(space, (tree, &root), &state, &index, (&purged, false))?;
182		let mut diffs = Vec::new();
183		for pending in &compared.pending {
184			let base = pending.base.clone().or_else(|| {
185				pending
186					.entity
187					.and_then(|entity| state.by_entity.get(&entity))
188					.and_then(|path| state.by_path.get(path))
189					.and_then(|current| current.version.clone())
190			});
191			let old = match (&pending.change, &base) {
192				(Change::New, _) | (_, None) => Side::Nothing,
193				(_, Some(version)) => Side::Version(version),
194			};
195			let new = match &pending.found {
196				Some(found) => Side::Copy(found),
197				None => Side::Nothing,
198			};
199			let path = pending.path.clone();
200			let at = (path, pending.change.clone());
201			let shown = (pending.secret, secrets);
202			diffs.push(self.file_diff(space, at, (&old, &new), shown)?);
203		}
204		Ok(diffs)
205	}
206
207	/// How one file differs between two sides; of a secret file, only that it changed unless
208	/// `shown` asks for its lines.
209	fn file_diff(
210		&self,
211		space: SpaceId,
212		(path, change): (String, Change),
213		(old, new): (&Side<'_>, &Side<'_>),
214		(secret, shown): (bool, bool),
215	) -> Result<FileDiff, NodeError> {
216		if secret && !shown {
217			return Ok(FileDiff {
218				path,
219				change,
220				patch: None,
221				binary: false,
222				secret,
223			});
224		}
225		let old_bytes = self.side_bytes(space, old, secret)?;
226		let new_bytes = self.side_bytes(space, new, secret)?;
227		let binary = [&old_bytes, &new_bytes]
228			.iter()
229			.any(|bytes| bytes.as_ref().is_some_and(|bytes| !is_text(bytes)));
230		let unified = match (&old_bytes, &new_bytes) {
231			(Some(old_bytes), Some(new_bytes)) if !binary && old_bytes != new_bytes => {
232				let from = match &change {
233					Change::Moved { from } => from.as_str(),
234					_ => path.as_str(),
235				};
236				let old_text = String::from_utf8_lossy(old_bytes);
237				let new_text = String::from_utf8_lossy(new_bytes);
238				let made = diffy::DiffOptions::new()
239					.set_original_filename(format!("a/{from}"))
240					.set_modified_filename(format!("b/{path}"))
241					.create_patch(&old_text, &new_text)
242					.to_string();
243				Some(made)
244			}
245			_ => None,
246		};
247		Ok(FileDiff {
248			path,
249			change,
250			patch: unified,
251			binary,
252			secret,
253		})
254	}
255
256	/// What a side holds, as bytes: nothing as empty, a link as its target, a version as
257	/// this device holds its content, if it does and it is no larger than a diff reads, and
258	/// the copy as it is. A secret file's version is read only with the secrets unlocked.
259	fn side_bytes(
260		&self,
261		space: SpaceId,
262		side: &Side<'_>,
263		secret: bool,
264	) -> Result<Option<Vec<u8>>, NodeError> {
265		Ok(match side {
266			Side::Nothing => Some(Vec::new()),
267			Side::Version(Version::Link { target }) => Some(target.clone().into_bytes()),
268			Side::Version(Version::File { content, .. }) => {
269				self.version_bytes(space, content, secret)?
270			}
271			Side::Copy(found) => match &found.kind {
272				super::walk::FoundKind::Link(target) => Some(target.clone().into_bytes()),
273				super::walk::FoundKind::File => {
274					let mut bytes = Vec::new();
275					open_found(found)
276						.and_then(|file| file.take(READ_LIMIT + 1).read_to_end(&mut bytes))
277						.ok()
278						.filter(|_| bytes.len() as u64 <= READ_LIMIT)
279						.map(|_| bytes)
280				}
281			},
282		})
283	}
284
285	/// The content with the hash `content`, as this device holds it, if no larger than a
286	/// diff reads.
287	pub(super) fn content_bytes(
288		&self,
289		space: SpaceId,
290		content: &Hash,
291	) -> Result<Option<Vec<u8>>, NodeError> {
292		self.file_content(space, content, READ_LIMIT)
293	}
294}
295
296/// Whether content is text: its first 8,000 bytes hold no zero byte, as Git decides.
297pub(super) fn is_text(bytes: &[u8]) -> bool {
298	!bytes[..bytes.len().min(TEXT_HEAD)].contains(&0)
299}
300
301#[cfg(test)]
302mod tests {
303	use super::is_text;
304
305	#[test]
306	fn text_is_what_holds_no_zero_byte_in_its_first_eight_thousand() {
307		assert!(is_text(b"notes\n"));
308		assert!(is_text(&[0xff, 0xfe, b'a']));
309		assert!(!is_text(&[b'a', 0, b'b']));
310		let mut late = vec![b'a'; 8_000];
311		late.push(0);
312		assert!(is_text(&late));
313	}
314}