1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// SPDX-License-Identifier: Apache-2.0
//! Shared tree-to-tree diffing implementation.
//!
//! This module provides a generic tree diffing algorithm that can be used
//! by both `repo` and `semantic` crates.
use std::ops::ControlFlow;
#[cfg(feature = "async-source")]
use super::AsyncObjectSource;
use super::{ContentHash, DiffKind, FileChange, FileChangeSet, ObjectSource, Tree};
struct DiffFrame {
from: Option<Tree>,
to: Option<Tree>,
prefix: String,
from_index: usize,
to_index: usize,
}
enum DiffStep {
Emit(FileChange),
Descend {
from_hash: Option<ContentHash>,
to_hash: Option<ContentHash>,
name: String,
},
Done,
}
fn advance_merge(frame: &mut DiffFrame) -> DiffStep {
let from_entries = frame.from.as_ref().map_or(&[][..], Tree::entries);
let to_entries = frame.to.as_ref().map_or(&[][..], Tree::entries);
loop {
match (
from_entries.get(frame.from_index),
to_entries.get(frame.to_index),
) {
(Some(from_entry), Some(to_entry)) => match from_entry.name().cmp(to_entry.name()) {
std::cmp::Ordering::Less => {
frame.from_index += 1;
if let Some(from_hash) = from_entry.tree_hash() {
return DiffStep::Descend {
from_hash: Some(from_hash),
to_hash: None,
name: from_entry.name().to_owned(),
};
}
return DiffStep::Emit(FileChange::new(
child_path(&frame.prefix, from_entry.name()),
DiffKind::Deleted,
));
}
std::cmp::Ordering::Greater => {
frame.to_index += 1;
if let Some(to_hash) = to_entry.tree_hash() {
return DiffStep::Descend {
from_hash: None,
to_hash: Some(to_hash),
name: to_entry.name().to_owned(),
};
}
return DiffStep::Emit(FileChange::new(
child_path(&frame.prefix, to_entry.name()),
DiffKind::Added,
));
}
std::cmp::Ordering::Equal => {
frame.from_index += 1;
frame.to_index += 1;
if from_entry.target() == to_entry.target() {
continue;
}
if let (Some(from_hash), Some(to_hash)) =
(from_entry.tree_hash(), to_entry.tree_hash())
{
return DiffStep::Descend {
from_hash: Some(from_hash),
to_hash: Some(to_hash),
name: to_entry.name().to_owned(),
};
}
return DiffStep::Emit(FileChange::new(
child_path(&frame.prefix, to_entry.name()),
DiffKind::Modified,
));
}
},
(Some(from_entry), None) => {
frame.from_index += 1;
if let Some(from_hash) = from_entry.tree_hash() {
return DiffStep::Descend {
from_hash: Some(from_hash),
to_hash: None,
name: from_entry.name().to_owned(),
};
}
return DiffStep::Emit(FileChange::new(
child_path(&frame.prefix, from_entry.name()),
DiffKind::Deleted,
));
}
(None, Some(to_entry)) => {
frame.to_index += 1;
if let Some(to_hash) = to_entry.tree_hash() {
return DiffStep::Descend {
from_hash: None,
to_hash: Some(to_hash),
name: to_entry.name().to_owned(),
};
}
return DiffStep::Emit(FileChange::new(
child_path(&frame.prefix, to_entry.name()),
DiffKind::Added,
));
}
(None, None) => return DiffStep::Done,
}
}
}
/// Collect all file changes between two trees.
///
/// This is the materializing variant: it walks the trees via
/// [`diff_trees_visit`] and collects every [`FileChange`] into a
/// [`FileChangeSet`]. Streaming or early-exit consumers should prefer
/// [`diff_trees_visit`], which avoids allocating the full change list.
pub fn diff_trees<S: ObjectSource + ?Sized>(
store: &S,
from: &crate::object::ContentHash,
to: &crate::object::ContentHash,
) -> Result<FileChangeSet, anyhow::Error> {
let mut changes = FileChangeSet::new();
// The visitor never short-circuits here, so the `ControlFlow` result is
// always `Continue(())`; we ignore it and return the collected set.
let _ = diff_trees_visit(store, from, to, |change| {
changes.push(change);
ControlFlow::<()>::Continue(())
})?;
Ok(changes)
}
/// Diff two trees with internal iteration, invoking `visitor` for each
/// [`FileChange`] in traversal order.
///
/// This is the streaming counterpart to [`diff_trees`]. The visitor returns a
/// [`ControlFlow`]: `Continue(())` keeps walking, while `Break(value)` stops
/// the traversal immediately — no further subtrees are loaded and no further
/// changes are produced. Early-exit consumers (e.g. "does anything under path
/// X differ?", first-N, quick-status checks) use this to avoid materializing
/// the entire change list.
///
/// On early exit the carried `B` is returned as `Ok(ControlFlow::Break(b))`;
/// on full completion it returns `Ok(ControlFlow::Continue(()))`. Changes are
/// emitted in exactly the same order as [`diff_trees`] collects them, so the
/// two paths are behavior-identical.
pub fn diff_trees_visit<S, V, B>(
store: &S,
from: &crate::object::ContentHash,
to: &crate::object::ContentHash,
mut visitor: V,
) -> Result<ControlFlow<B>, anyhow::Error>
where
S: ObjectSource + ?Sized,
V: FnMut(FileChange) -> ControlFlow<B>,
{
if from == to {
return Ok(ControlFlow::Continue(()));
}
let from_tree = store.get_tree(from)?;
let to_tree = store.get_tree(to)?;
let mut stack = vec![DiffFrame {
from: from_tree,
to: to_tree,
prefix: String::new(),
from_index: 0,
to_index: 0,
}];
while !stack.is_empty() {
match advance_merge(stack.last_mut().expect("stack is not empty")) {
DiffStep::Emit(change) => {
if let ControlFlow::Break(b) = visitor(change) {
return Ok(ControlFlow::Break(b));
}
}
DiffStep::Descend {
from_hash,
to_hash,
name,
} => {
let from_subtree = from_hash
.map(|hash| store.get_tree(&hash))
.transpose()?
.flatten();
let to_subtree = to_hash
.map(|hash| store.get_tree(&hash))
.transpose()?
.flatten();
let prefix = child_path(
&stack.last().expect("parent frame remains on stack").prefix,
&name,
);
stack.push(DiffFrame {
from: from_subtree,
to: to_subtree,
prefix,
from_index: 0,
to_index: 0,
});
}
DiffStep::Done => {
stack.pop();
}
}
}
Ok(ControlFlow::Continue(()))
}
#[cfg(feature = "async-source")]
pub async fn diff_trees_visit_async<S, V, B>(
store: &S,
from: &crate::object::ContentHash,
to: &crate::object::ContentHash,
mut visitor: V,
) -> Result<ControlFlow<B>, anyhow::Error>
where
S: AsyncObjectSource + Sync + ?Sized,
V: FnMut(FileChange) -> ControlFlow<B> + Send,
B: Send,
{
if from == to {
return Ok(ControlFlow::Continue(()));
}
let from_tree = store.get_tree(from).await?;
let to_tree = store.get_tree(to).await?;
let mut stack = vec![DiffFrame {
from: from_tree,
to: to_tree,
prefix: String::new(),
from_index: 0,
to_index: 0,
}];
while !stack.is_empty() {
match advance_merge(stack.last_mut().expect("stack is not empty")) {
DiffStep::Emit(change) => {
if let ControlFlow::Break(b) = visitor(change) {
return Ok(ControlFlow::Break(b));
}
}
DiffStep::Descend {
from_hash,
to_hash,
name,
} => {
let from_subtree = match from_hash {
Some(hash) => store.get_tree(&hash).await?,
None => None,
};
let to_subtree = match to_hash {
Some(hash) => store.get_tree(&hash).await?,
None => None,
};
let prefix = child_path(
&stack.last().expect("parent frame remains on stack").prefix,
&name,
);
stack.push(DiffFrame {
from: from_subtree,
to: to_subtree,
prefix,
from_index: 0,
to_index: 0,
});
}
DiffStep::Done => {
stack.pop();
}
}
}
Ok(ControlFlow::Continue(()))
}
fn child_path(prefix: &str, name: &str) -> String {
if prefix.is_empty() {
name.to_owned()
} else {
let mut path = String::with_capacity(prefix.len() + 1 + name.len());
path.push_str(prefix);
path.push('/');
path.push_str(name);
path
}
}