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
//! Working-tree absorption rewrites on VcsManager.
//! History surgery (jj-style): amend, reword, squash, move, abandon, fold,
//! revert, absorb, and other commit-rewriting operations on VcsManager.
use crate::error::{Context, Result};
use super::objects::{Tree, TreeEntry, Commit};
use super::manager::{commit_tree_entries, AbsorbResult, VcsManager};
impl VcsManager {
/// Absorb uncommitted working-tree changes into the best-matching commit
/// in the current branch's history (Sapling-style). Returns the new HEAD
/// commit hash and a description of what was absorbed.
///
/// Algorithm:
/// 1. Walk the working tree and compute modified files (vs HEAD tree).
/// 2. Walk back through commits on the current branch (HEAD, HEAD~1, …).
/// 3. For each commit, compute its changed files (diff vs its parent).
/// 4. Pick the commit with the most file overlap with the working tree.
/// 5. Amend that commit's tree with the new content for overlapping files.
/// 6. Rebuild descendants: for each file in the absorbed set, if the
/// descendant didn't change it, take the new version; otherwise keep
/// the descendant's version.
/// 7. Update the branch ref, sync index + working tree to new HEAD.
pub async fn absorb(&self) -> Result<AbsorbResult> {
let repo = self.repo.clone();
let repo_path = self.repo_path.clone();
tokio::task::spawn_blocking(move || -> Result<AbsorbResult> {
let mgr = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };
// 1. Compute working-tree modified files (path -> new blob id).
let head_tree = mgr.head_tree()?;
let head_map: std::collections::HashMap<String, String> = head_tree
.entries
.iter()
.map(|e| (e.name.clone(), e.id.clone()))
.collect();
let wt_files = mgr.walk_working_tree(&repo_path)?;
let mut wt_changes: Vec<(String, String)> = Vec::new(); // (path, new_blob_id)
for file in &wt_files {
let relative = file.strip_prefix(&repo_path).unwrap_or(file);
let relative_str = relative.to_string_lossy().to_string();
let content = std::fs::read(file)
.with_context(|| format!("absorb: read wt file {:?}", file))?;
let blob_id = repo.write_blob(&content)?;
match head_map.get(&relative_str) {
Some(h) if *h == blob_id => {} // unchanged
_ => wt_changes.push((relative_str, blob_id)),
}
}
// Deleted files (in HEAD but not in working tree)
let wt_set: std::collections::HashSet<&str> =
wt_files.iter().map(|f| f.strip_prefix(&repo_path).unwrap_or(f).to_str().unwrap()).collect();
for name in head_map.keys() {
if !wt_set.contains(name.as_str()) {
wt_changes.push((name.clone(), String::new())); // empty = deleted
}
}
if wt_changes.is_empty() {
bail!("No uncommitted changes to absorb");
}
let wt_files_set: std::collections::HashSet<&str> =
wt_changes.iter().map(|(p, _)| p.as_str()).collect();
// 2. Walk back through commits, collecting (commit_hash, changed_files).
let head_id = repo.refs().resolve_head()?.context("HEAD does not point to a commit")?;
let mut commits: Vec<(String, Vec<String>)> = Vec::new();
let mut current = head_id.clone();
for _ in 0..50 {
let commit = repo.read_commit(¤t)?;
let parent_tree = if !commit.parents.is_empty() {
let parent = repo.read_commit(&commit.parents[0])?;
repo.read_tree(&parent.tree)?
} else {
Tree::new(vec![])
};
let changed: Vec<String> = {
let parent_set: std::collections::HashMap<&String, &String> = parent_tree
.entries.iter().map(|e| (&e.name, &e.id)).collect();
let mut files = Vec::new();
for entry in &commit_tree_entries(&repo, ¤t)? {
match parent_set.get(&entry.name) {
Some(h) if **h != entry.id => files.push(entry.name.clone()),
None => files.push(entry.name.clone()),
_ => {}
}
}
for name in parent_tree.entries.iter().map(|e| &e.name) {
if !commit_tree_entries(&repo, ¤t)?.iter().any(|e| &e.name == name) {
files.push(name.clone());
}
}
files
};
commits.push((current.clone(), changed));
if commit.parents.is_empty() {
break;
}
current = commit.parents[0].clone();
}
// 3. Find the commit with the most overlap.
let mut best_idx = 0usize;
let mut best_overlap = 0usize;
for (i, (_, changed)) in commits.iter().enumerate() {
let overlap = changed.iter().filter(|f| wt_files_set.contains(f.as_str())).count();
if overlap > best_overlap {
best_overlap = overlap;
best_idx = i;
}
}
if best_overlap == 0 {
// No commit has overlap — amend HEAD as fallback.
best_idx = 0;
}
let (target_hash, _) = &commits[best_idx];
let target_hash = target_hash.clone();
// 4. Build the new target tree: start from target's tree, apply
// working-tree changes for overlapping files.
let target_commit = repo.read_commit(&target_hash)?;
let target_tree = repo.read_tree(&target_commit.tree)?;
let mut target_entries: Vec<TreeEntry> = target_tree.entries.clone();
let target_map: std::collections::HashMap<String, usize> = target_tree
.entries.iter().enumerate().map(|(i, e)| (e.name.clone(), i)).collect();
let mut absorbed_files = Vec::new();
for (path, new_blob) in &wt_changes {
if let Some(&idx) = target_map.get(path) {
if new_blob.is_empty() {
// File was deleted in working tree — remove from target tree
target_entries[idx] = TreeEntry { mode: 0, name: String::new(), id: String::new() };
} else {
target_entries[idx].id = new_blob.clone();
}
absorbed_files.push(path.clone());
} else if !new_blob.is_empty() {
// File is new (not in target tree) — add it only if the target
// is HEAD (otherwise it belongs to a later commit).
if best_idx == 0 {
target_entries.push(TreeEntry { mode: 0o100644, name: path.clone(), id: new_blob.clone() });
absorbed_files.push(path.clone());
}
}
}
// Remove deleted entries (mode 0 = marker for deletion)
target_entries.retain(|e| e.mode != 0);
let new_target_tree = Tree::new(target_entries);
let new_target_tree_id = repo.write_tree(&new_target_tree)?;
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let new_target_commit = Commit::new(
new_target_tree_id,
target_commit.parents.clone(),
target_commit.author.clone(),
target_commit.message.clone(),
timestamp,
);
let new_target_id = repo.write_commit(&new_target_commit)?;
// 5. Rebuild descendants (commits newer than the target).
// `commits` is ordered newest-to-oldest, so descendants are
// `commits[0..best_idx]` — iterate in reverse (oldest descendant first).
let mut new_parent = new_target_id.clone();
let absorbed_set: std::collections::HashSet<&str> =
absorbed_files.iter().map(|s| s.as_str()).collect();
for i in (0..best_idx).rev() {
let (old_hash, _) = &commits[i];
let old_commit = repo.read_commit(old_hash)?;
let old_tree = repo.read_tree(&old_commit.tree)?;
// For each absorbed file: if the descendant didn't change it
// (same blob as the original target), update it to the new
// version from the amended target tree.
let mut new_entries = old_tree.entries.clone();
let old_tree_map: std::collections::HashMap<String, usize> = old_tree
.entries.iter().enumerate().map(|(i, e)| (e.name.clone(), i)).collect();
for (path, new_blob) in &wt_changes {
if !absorbed_set.contains(path.as_str()) {
continue;
}
if let Some(&idx) = old_tree_map.get(path) {
// Check if the descendant changed this file vs the target
let target_blob = target_tree.entries.iter()
.find(|e| e.name == *path)
.map(|e| e.id.clone());
if old_tree.entries[idx].id == target_blob.unwrap_or_default() {
// Descendant didn't change it — update to new version
if new_blob.is_empty() {
new_entries[idx] = TreeEntry { mode: 0, name: String::new(), id: String::new() };
} else {
new_entries[idx].id = new_blob.clone();
}
}
}
}
new_entries.retain(|e| e.mode != 0);
let new_tree = Tree::new(new_entries);
let new_tree_id = repo.write_tree(&new_tree)?;
let new_commit = Commit::new(
new_tree_id,
vec![new_parent.clone()],
old_commit.author.clone(),
old_commit.message.clone(),
timestamp,
);
new_parent = repo.write_commit(&new_commit)?;
}
// 6. Update branch ref to the new HEAD.
let branch = repo.refs().current_branch()?.context("No current branch")?;
repo.refs().set_branch(&branch, &new_parent)?;
// 7. Sync index + working tree to new HEAD.
let mgr2 = VcsManager { repo: repo.clone(), repo_path: repo_path.clone(), max_file_size: 0, merge_drivers: std::collections::HashMap::new() };
mgr2.sync_index_to_commit(&new_parent)
.context("absorb: sync index")?;
mgr2.restore_working_tree_pub(&new_parent)
.context("absorb: restore working tree")?;
Ok(AbsorbResult {
new_head: new_parent,
target_commit: target_hash,
absorbed_files,
was_head: best_idx == 0,
})
})
.await?
}
/// Soft reset to parent of HEAD (undo last commit, keep changes staged).
pub async fn reset_soft_parent(&self) -> Result<()> {
let head_id = self
.repo
.refs()
.resolve_head()?
.context("HEAD does not point to a commit")?;
let head_commit = self.repo.read_commit(&head_id)?;
if head_commit.parents.is_empty() {
bail!("No parent commit to reset to");
}
let parent_id = &head_commit.parents[0];
// Update branch ref to parent
if let Some(branch) = self.repo.refs().current_branch()? {
self.repo.refs().set_branch(&branch, parent_id)?;
}
// Restore index to match parent commit's tree
let parent_commit = self.repo.read_commit(parent_id)?;
let tree = self.repo.read_tree(&parent_commit.tree)?;
let mut index = self.repo.load_index()?;
index.clear();
for entry in &tree.entries {
index.add(&entry.name, &entry.id);
}
index.save()?;
Ok(())
}
// ── Status ─────────────────────────────────────────────────────
}