1use 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
19const TEXT_HEAD: usize = 8_000;
21
22#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct FileDiff {
25 pub path: String,
27 pub change: Change,
29 pub patch: Option<String>,
32 pub binary: bool,
34 pub secret: bool,
38}
39
40enum Side<'a> {
42 Nothing,
44 Version(&'a Version),
46 Copy(&'a super::walk::Found),
48}
49
50impl Library {
51 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 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 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 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 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 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 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 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 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
296pub(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}