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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
use gix_merge::blob::builtin_driver::text;
use gix_object::Write;
use crate::{
Error, Repository, Result,
config::{cache::util::ApplyLeniencyDefault, tree},
prelude::ObjectIdExt,
};
/// Merge-utilities
impl Repository {
/// Create a resource cache that can hold the three resources needed for a three-way merge. `worktree_roots`
/// determines which side of the merge is read from the worktree, or from which worktree.
///
/// The platform can be used to set up resources and finally perform a merge among blobs.
///
/// Note that the current index is used for attribute queries.
pub fn merge_resource_cache(
&self,
worktree_roots: gix_merge::blob::pipeline::WorktreeRoots,
) -> Result<gix_merge::blob::Platform> {
let index = self.index_or_load_from_head_or_empty()?;
let mode = {
let renormalize = tree::Merge::RENORMALIZE
.enrich_error(self.config.resolved.boolean(tree::Merge::RENORMALIZE))
.with_lenient_default(self.config.lenient_config)?
.unwrap_or_default();
if renormalize {
gix_merge::blob::pipeline::Mode::Renormalize
} else {
gix_merge::blob::pipeline::Mode::ToGit
}
};
let attrs = self
.attributes_only(
&index,
if worktree_roots.is_unset() {
gix_worktree::stack::state::attributes::Source::IdMapping
} else {
gix_worktree::stack::state::attributes::Source::WorktreeThenIdMapping
},
)?
.inner;
let filter = gix_filter::Pipeline::new(
self.command_context()?,
self.object_hash(),
crate::filter::Pipeline::options(self)?,
);
// Git's diff size threshold does not change how text is merged.
let filter = gix_merge::blob::Pipeline::new(worktree_roots, filter, Default::default());
let options = gix_merge::blob::platform::Options {
default_driver: self.config.resolved.string(tree::Merge::DEFAULT),
};
let drivers = self.config.merge_drivers()?;
Ok(gix_merge::blob::Platform::new(filter, mode, attrs, drivers, options))
}
/// Return options for use with [`gix_merge::blob::PlatformRef::merge()`], accessible through
/// [merge_resource_cache()](Self::merge_resource_cache).
pub fn blob_merge_options(&self) -> Result<gix_merge::blob::platform::merge::Options> {
Ok(gix_merge::blob::platform::merge::Options {
is_virtual_ancestor: false,
resolve_binary_with: None,
text: gix_merge::blob::builtin_driver::text::Options {
diff_algorithm: self.diff_algorithm()?,
conflict: text::Conflict::Keep {
style: self
.config
.resolved
.string(tree::Merge::CONFLICT_STYLE)
.map(|value| {
tree::Merge::CONFLICT_STYLE
.try_into_conflict_style(value)
.with_lenient_default(self.config.lenient_config)
})
.transpose()?
.unwrap_or_default(),
marker_size: text::Conflict::DEFAULT_MARKER_SIZE.try_into().unwrap(),
},
},
})
}
/// Read all relevant configuration options to instantiate options for use in [`merge_trees()`](Self::merge_trees).
pub fn tree_merge_options(&self) -> Result<crate::merge::tree::Options> {
let (mut rewrites, is_configured) = crate::diff::utils::new_rewrites_inner(
&self.config.resolved,
self.config.lenient_config,
&tree::Merge::RENAMES,
&tree::Merge::RENAME_LIMIT,
)?;
if !is_configured {
rewrites = Some(Default::default());
}
Ok(gix_merge::tree::Options {
rewrites,
directory_renames: if rewrites.is_some() {
tree::Merge::DIRECTORY_RENAMES
.try_into_directory_renames(self.config.resolved.boolean(tree::Merge::DIRECTORY_RENAMES))
.with_lenient_default(self.config.lenient_config)?
} else {
gix_merge::tree::DirectoryRenames::Disabled
},
blob_merge: self.blob_merge_options()?,
blob_merge_command_ctx: self.command_context()?,
fail_on_conflict: None,
marker_size_multiplier: 0,
symlink_conflicts: None,
tree_conflicts: None,
}
.into())
}
/// Merge `our_tree` and `their_tree` together, assuming they have the same `ancestor_tree`, to yield a new tree
/// which is provided as [tree editor](crate::object::tree::Editor) to inspect and finalize results at will.
/// No change to the worktree or index is made, but objects may be written to the object database as merge results
/// are stored.
/// If these changes should not be observable outside of this instance, consider [enabling object memory](Self::with_object_memory).
///
/// Note that `ancestor_tree` can be the [empty tree hash](gix_hash::ObjectId::empty_tree) to indicate no common ancestry.
///
/// Available local submodule repositories provide history for resolving gitlink updates. Missing repositories
/// or commits leave a submodule conflict; errors reading available history are returned.
///
/// `labels` are typically chosen to identify the refs or names for `our_tree` and `their_tree` and `ancestor_tree` respectively.
///
/// `options` should be initialized with [`tree_merge_options()`](Self::tree_merge_options()).
///
/// ### Performance
///
/// It's highly recommended to [set an object cache](Repository::compute_object_cache_size_for_tree_diffs)
/// to avoid extracting the same object multiple times.
pub fn merge_trees(
&self,
ancestor_tree: impl AsRef<gix_hash::oid>,
our_tree: impl AsRef<gix_hash::oid>,
their_tree: impl AsRef<gix_hash::oid>,
labels: gix_merge::blob::builtin_driver::text::Labels<'_>,
options: crate::merge::tree::Options,
) -> Result<crate::merge::tree::Outcome<'_>> {
let mut diff_cache = self.diff_resource_cache_for_tree_diff()?;
let mut blob_merge = self.merge_resource_cache(Default::default())?;
let mut submodule = submodule::query(self);
let context = gix_merge::tree::Context {
submodule: Some(&mut submodule),
};
let gix_merge::tree::Outcome {
tree,
index,
conflicts,
failed_on_first_unresolved_conflict,
} = gix_merge::tree(
ancestor_tree.as_ref(),
our_tree.as_ref(),
their_tree.as_ref(),
labels,
self,
|buf| self.write_buf(gix_object::Kind::Blob, buf),
&mut Default::default(),
&mut diff_cache,
&mut blob_merge,
context,
options.into(),
)?;
let validate = self.config.protect_options()?;
Ok(crate::merge::tree::Outcome {
tree: crate::object::tree::Editor {
inner: tree,
validate,
repo: self,
},
index,
conflicts,
failed_on_first_unresolved_conflict,
})
}
/// Merge `our_commit` and `their_commit` together to yield a new tree which is provided as [tree editor](crate::object::tree::Editor)
/// to inspect and finalize results at will. The merge-base will be determined automatically between both commits, along with special
/// handling in case there are multiple merge-bases.
/// No change to the worktree or index is made, but objects may be written to the object database as merge results
/// are stored.
/// If these changes should not be observable outside of this instance, consider [enabling object memory](Self::with_object_memory).
///
/// `labels` are typically chosen to identify the refs or names for `our_commit` and `their_commit`, with the ancestor being set
/// automatically as part of the merge-base handling.
///
/// Submodule histories are resolved as in [`Self::merge_trees()`], including while constructing virtual merge-bases.
///
/// `options` should be initialized with [`Repository::tree_merge_options().into()`](Self::tree_merge_options()).
///
/// ### Performance
///
/// It's highly recommended to [set an object cache](Repository::compute_object_cache_size_for_tree_diffs)
/// to avoid extracting the same object multiple times.
pub fn merge_commits(
&self,
our_commit: impl Into<gix_hash::ObjectId>,
their_commit: impl Into<gix_hash::ObjectId>,
labels: gix_merge::blob::builtin_driver::text::Labels<'_>,
options: crate::merge::commit::Options,
) -> Result<crate::merge::commit::Outcome<'_>> {
let mut diff_cache = self.diff_resource_cache_for_tree_diff()?;
let mut blob_merge = self.merge_resource_cache(Default::default())?;
let commit_graph = self.commit_graph_if_enabled()?;
let mut graph = self.revision_graph(commit_graph.as_ref());
let mut submodule = submodule::query(self);
let context = gix_merge::tree::Context {
submodule: Some(&mut submodule),
};
let gix_merge::commit::Outcome {
tree_merge:
gix_merge::tree::Outcome {
tree,
index,
conflicts,
failed_on_first_unresolved_conflict,
},
merge_base_tree_id,
merge_bases,
virtual_merge_bases,
} = gix_merge::commit(
our_commit.into(),
their_commit.into(),
labels,
&mut graph,
&mut diff_cache,
&mut blob_merge,
self,
&mut |id| id.to_owned().attach(self).shorten_or_id().to_string(),
context,
options.into(),
)?;
let validate = self.config.protect_options()?;
let tree_merge = crate::merge::tree::Outcome {
tree: crate::object::tree::Editor {
inner: tree,
validate,
repo: self,
},
index,
conflicts,
failed_on_first_unresolved_conflict,
};
Ok(crate::merge::commit::Outcome {
tree_merge,
merge_base_tree_id,
merge_bases,
virtual_merge_bases,
})
}
/// Create a single virtual merge-base by merging all `merge_bases` into one.
/// If the list is empty, an error will be returned as the histories are then unrelated.
/// If there is only one commit in the list, it is returned directly with this case clearly marked in the outcome.
///
/// Note that most of `options` are overwritten to match the requirements of a merge-base merge, but they can be useful
/// to control the diff algorithm or rewrite tracking, for example.
///
/// This method is useful in conjunction with [`Self::merge_trees()`], as the ancestor tree can be produced here.
// TODO: test
pub fn virtual_merge_base(
&self,
merge_bases: impl IntoIterator<Item = impl Into<gix_hash::ObjectId>>,
options: crate::merge::tree::Options,
) -> Result<crate::merge::virtual_merge_base::Outcome<'_>> {
let commit_graph = self.commit_graph_if_enabled()?;
let mut graph = self.revision_graph(commit_graph.as_ref());
self.virtual_merge_base_with_graph(merge_bases, &mut graph, options)
}
/// Like [`Self::virtual_merge_base()`], but also allows to reuse a `graph` for faster merge-base calculation,
/// particularly if `graph` was used to find the `merge_bases`.
pub fn virtual_merge_base_with_graph(
&self,
merge_bases: impl IntoIterator<Item = impl Into<gix_hash::ObjectId>>,
graph: &mut gix_revwalk::Graph<'_, '_, gix_revwalk::graph::Commit<gix_revision::merge_base::Flags>>,
options: crate::merge::tree::Options,
) -> Result<crate::merge::virtual_merge_base::Outcome<'_>> {
let mut merge_bases: Vec<_> = merge_bases.into_iter().map(Into::into).collect();
let first = merge_bases
.pop()
.ok_or_else(|| Error::from_error(gix_error::message("No commit was provided as merge-base")))?;
let Some(second) = merge_bases.pop() else {
let tree_id = self.find_commit(first)?.tree_id()?;
let commit_id = first.attach(self);
return Ok(crate::merge::virtual_merge_base::Outcome {
virtual_merge_bases: Vec::new(),
commit_id,
tree_id,
});
};
let mut diff_cache = self.diff_resource_cache_for_tree_diff()?;
let mut blob_merge = self.merge_resource_cache(Default::default())?;
let mut submodule = submodule::query(self);
let context = gix_merge::tree::Context {
submodule: Some(&mut submodule),
};
let gix_merge::commit::virtual_merge_base::Outcome {
virtual_merge_bases,
commit_id,
tree_id,
} = gix_merge::commit::virtual_merge_base(
first,
second,
merge_bases,
graph,
&mut diff_cache,
&mut blob_merge,
self,
&mut |id| id.to_owned().attach(self).shorten_or_id().to_string(),
context,
options.into(),
)?;
Ok(crate::merge::virtual_merge_base::Outcome {
virtual_merge_bases: virtual_merge_bases.into_iter().map(|id| id.attach(self)).collect(),
commit_id: commit_id.attach(self),
tree_id: tree_id.attach(self),
})
}
}
mod submodule {
use std::{collections::HashMap, ops::ControlFlow};
use crate::{
Repository, Result,
bstr::{BStr, BString, ByteSlice},
};
pub(super) fn query(
repo: &Repository,
) -> impl FnMut(&BStr, gix_merge::submodule::Query<'_>) -> Result<Option<bool>> + '_ {
let mut repositories = HashMap::<BString, Option<Repository>>::new();
move |path, query| {
if !repositories.contains_key(path) {
repositories.insert(path.to_owned(), open(repo, path)?);
}
let Some(repo) = repositories.get(path).and_then(Option::as_ref) else {
return Ok(None);
};
Ok(Some(match query {
gix_merge::submodule::Query::CommitsAvailable(commit_ids) => {
for commit_id in commit_ids {
let Some(object) = repo
.try_find_object(commit_id.to_owned())?
.filter(|object| object.kind.is_commit())
else {
return Ok(Some(false));
};
object.try_into_commit()?.decode()?;
}
true
}
gix_merge::submodule::Query::IsAncestor { ancestor, descendant } => {
let cache = repo.commit_graph_if_enabled()?;
let mut graph = gix_revwalk::Graph::new(
crate::revision::walk::Objects {
repo,
shallow: repo.shallow_commits()?,
},
cache.as_ref(),
);
gix_revision::merge_base::is_ancestor(ancestor.to_owned(), descendant.to_owned(), &mut graph)?
}
}))
}
}
fn open(repo: &Repository, path: &BStr) -> Result<Option<Repository>> {
// Git tries the checkout first, including unregistered or renamed submodules.
if let Some(worktree_gitdir) = crate::submodule::worktree_gitdir(repo, path)?
&& let Some(git_dir) = crate::submodule::git_dir_from_worktree_gitdir(&worktree_gitdir, true)?
{
match crate::submodule::open(repo, &git_dir, path)? {
ControlFlow::Break(_) => return Ok(None),
ControlFlow::Continue(Some(subrepo)) => return Ok(Some(subrepo)),
ControlFlow::Continue(None) => {}
}
}
if let Some(submodules) = repo.submodules()? {
for submodule in submodules {
if submodule
.try_path()?
.is_some_and(|configured_path| configured_path.as_bstr() == path)
{
return submodule.open();
}
}
}
Ok(None)
}
}