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
use crate::commit::Commit;
use crate::commit_builder::CommitBuilder;
use crate::repo::{MutableRepo, RepoRef};
use crate::repo_path::DirRepoPath;
use crate::settings::UserSettings;
use crate::tree::Tree;
use crate::trees::merge_trees;
pub fn merge_commit_trees(repo: RepoRef, commits: &[Commit]) -> Tree {
let store = repo.store();
if commits.is_empty() {
store
.get_tree(&DirRepoPath::root(), store.empty_tree_id())
.unwrap()
} else {
let index = repo.index();
let mut new_tree = commits[0].tree();
let commit_ids: Vec<_> = commits.iter().map(|commit| commit.id().clone()).collect();
for (i, other_commit) in commits.iter().enumerate().skip(1) {
let ancestors = index.common_ancestors(&commit_ids[0..i], &[commit_ids[i].clone()]);
let ancestor = store.get_commit(&ancestors[0]).unwrap();
let new_tree_id =
merge_trees(&new_tree, &ancestor.tree(), &other_commit.tree()).unwrap();
new_tree = store.get_tree(&DirRepoPath::root(), &new_tree_id).unwrap();
}
new_tree
}
}
pub fn rebase_commit(
settings: &UserSettings,
mut_repo: &mut MutableRepo,
old_commit: &Commit,
new_parents: &[Commit],
) -> Commit {
let store = mut_repo.store();
let old_base_tree = merge_commit_trees(mut_repo.as_repo_ref(), &old_commit.parents());
let new_base_tree = merge_commit_trees(mut_repo.as_repo_ref(), &new_parents);
let new_tree_id = merge_trees(&new_base_tree, &old_base_tree, &old_commit.tree()).unwrap();
let new_parent_ids = new_parents
.iter()
.map(|commit| commit.id().clone())
.collect();
CommitBuilder::for_rewrite_from(settings, store, &old_commit)
.set_parents(new_parent_ids)
.set_tree(new_tree_id)
.write_to_repo(mut_repo)
}
pub fn back_out_commit(
settings: &UserSettings,
mut_repo: &mut MutableRepo,
old_commit: &Commit,
new_parents: &[Commit],
) -> Commit {
let store = mut_repo.store();
let old_base_tree = merge_commit_trees(mut_repo.as_repo_ref(), &old_commit.parents());
let new_base_tree = merge_commit_trees(mut_repo.as_repo_ref(), &new_parents);
let new_tree_id = merge_trees(&new_base_tree, &old_commit.tree(), &old_base_tree).unwrap();
let new_parent_ids = new_parents
.iter()
.map(|commit| commit.id().clone())
.collect();
CommitBuilder::for_new_commit(settings, store, new_tree_id)
.set_parents(new_parent_ids)
.set_description(format!(
"backout of commit {}",
hex::encode(&old_commit.id().0)
))
.write_to_repo(mut_repo)
}