]> git.ipfire.org Git - thirdparty/git.git/blame - merge-ort.c
merge-ort: add a handle_deferred_entries() helper function
[thirdparty/git.git] / merge-ort.c
CommitLineData
17e5574b
EN
1/*
2 * "Ostensibly Recursive's Twin" merge strategy, or "ort" for short. Meant
3 * as a drop-in replacement for the "recursive" merge strategy, allowing one
4 * to replace
5 *
6 * git merge [-s recursive]
7 *
8 * with
9 *
10 * git merge -s ort
11 *
12 * Note: git's parser allows the space between '-s' and its argument to be
13 * missing. (Should I have backronymed "ham", "alsa", "kip", "nap, "alvo",
14 * "cale", "peedy", or "ins" instead of "ort"?)
15 */
16
17#include "cache.h"
18#include "merge-ort.h"
19
4296d8f1 20#include "alloc.h"
ea305a68 21#include "attr.h"
67845745 22#include "blob.h"
ef2b3693 23#include "cache-tree.h"
4296d8f1 24#include "commit.h"
67845745 25#include "commit-reach.h"
e4171b1b
EN
26#include "diff.h"
27#include "diffcore.h"
6681ce5c 28#include "dir.h"
7bec8e7f 29#include "entry.h"
f591c472 30#include "ll-merge.h"
ee4012dc 31#include "object-store.h"
2bff554b 32#include "promisor-remote.h"
4204cd59 33#include "revision.h"
5b59c3db 34#include "strmap.h"
c73cda76 35#include "submodule.h"
231e2dd4 36#include "tree.h"
6681ce5c 37#include "unpack-trees.h"
c8017176 38#include "xdiff-interface.h"
5b59c3db 39
d2bc1994
EN
40/*
41 * We have many arrays of size 3. Whenever we have such an array, the
42 * indices refer to one of the sides of the three-way merge. This is so
43 * pervasive that the constants 0, 1, and 2 are used in many places in the
44 * code (especially in arithmetic operations to find the other side's index
45 * or to compute a relevant mask), but sometimes these enum names are used
46 * to aid code clarity.
47 *
48 * See also 'filemask' and 'dirmask' in struct conflict_info; the "ith side"
49 * referred to there is one of these three sides.
50 */
51enum merge_side {
52 MERGE_BASE = 0,
53 MERGE_SIDE1 = 1,
54 MERGE_SIDE2 = 2
55};
56
19ceb486
EN
57static unsigned RESULT_INITIALIZED = 0x1abe11ed; /* unlikely accidental value */
58
beb06145
EN
59struct traversal_callback_data {
60 unsigned long mask;
61 unsigned long dirmask;
62 struct name_entry names[3];
63};
64
d478f567
EN
65struct deferred_traversal_data {
66 /*
67 * possible_trivial_merges: directories to be explored only when needed
68 *
69 * possible_trivial_merges is a map of directory names to
70 * dir_rename_mask. When we detect that a directory is unchanged on
71 * one side, we can sometimes resolve the directory without recursing
72 * into it. Renames are the only things that can prevent such an
73 * optimization. However, for rename sources:
74 * - If no parent directory needed directory rename detection, then
75 * no path under such a directory can be a relevant_source.
76 * and for rename destinations:
77 * - If no cached rename has a target path under the directory AND
78 * - If there are no unpaired relevant_sources elsewhere in the
79 * repository
80 * then we don't need any path under this directory for a rename
81 * destination. The only way to know the last item above is to defer
82 * handling such directories until the end of collect_merge_info(),
83 * in handle_deferred_entries().
84 *
85 * For each we store dir_rename_mask, since that's the only bit of
86 * information we need, other than the path, to resume the recursive
87 * traversal.
88 */
89 struct strintmap possible_trivial_merges;
90
91 /*
92 * trivial_merges_okay: if trivial directory merges are okay
93 *
94 * See possible_trivial_merges above. The "no unpaired
95 * relevant_sources elsewhere in the repository" is a single boolean
96 * per merge side, which we store here. Note that while 0 means no,
97 * 1 only means "maybe" rather than "yes"; we optimistically set it
98 * to 1 initially and only clear when we determine it is unsafe to
99 * do trivial directory merges.
100 */
101 unsigned trivial_merges_okay;
102
103 /*
104 * target_dirs: ancestor directories of rename targets
105 *
106 * target_dirs contains all directory names that are an ancestor of
107 * any rename destination.
108 */
109 struct strset target_dirs;
110};
111
864075ec 112struct rename_info {
c09376d5
EN
113 /*
114 * All variables that are arrays of size 3 correspond to data tracked
115 * for the sides in enum merge_side. Index 0 is almost always unused
116 * because we often only need to track information for MERGE_SIDE1 and
117 * MERGE_SIDE2 (MERGE_BASE can't have rename information since renames
118 * are determined relative to what changed since the MERGE_BASE).
119 */
120
864075ec
EN
121 /*
122 * pairs: pairing of filenames from diffcore_rename()
864075ec
EN
123 */
124 struct diff_queue_struct pairs[3];
125
c09376d5
EN
126 /*
127 * dirs_removed: directories removed on a given side of history.
fb52938e
EN
128 *
129 * The keys of dirs_removed[side] are the directories that were removed
130 * on the given side of history. The value of the strintmap for each
131 * directory is a value from enum dir_rename_relevance.
c09376d5 132 */
a49b55d5 133 struct strintmap dirs_removed[3];
c09376d5
EN
134
135 /*
136 * dir_rename_count: tracking where parts of a directory were renamed to
137 *
138 * When files in a directory are renamed, they may not all go to the
139 * same location. Each strmap here tracks:
140 * old_dir => {new_dir => int}
141 * That is, dir_rename_count[side] is a strmap to a strintmap.
142 */
143 struct strmap dir_rename_count[3];
144
145 /*
146 * dir_renames: computed directory renames
147 *
148 * This is a map of old_dir => new_dir and is derived in part from
149 * dir_rename_count.
150 */
151 struct strmap dir_renames[3];
152
32a56dfb 153 /*
ec59da60 154 * relevant_sources: deleted paths wanted in rename detection, and why
32a56dfb
EN
155 *
156 * relevant_sources is a set of deleted paths on each side of
157 * history for which we need rename detection. If a path is deleted
158 * on one side of history, we need to detect if it is part of a
159 * rename if either
32a56dfb 160 * * the file is modified/deleted on the other side of history
ec59da60 161 * * we need to detect renames for an ancestor directory
32a56dfb 162 * If neither of those are true, we can skip rename detection for
ec59da60
EN
163 * that path. The reason is stored as a value from enum
164 * file_rename_relevance, as the reason can inform the algorithm in
165 * diffcore_rename_extended().
32a56dfb 166 */
a49b55d5 167 struct strintmap relevant_sources[3];
32a56dfb 168
d478f567
EN
169 struct deferred_traversal_data deferred[3];
170
2fd9eda4
EN
171 /*
172 * dir_rename_mask:
173 * 0: optimization removing unmodified potential rename source okay
174 * 2 or 4: optimization okay, but must check for files added to dir
175 * 7: optimization forbidden; need rename source in case of dir rename
176 */
177 unsigned dir_rename_mask:3;
178
beb06145
EN
179 /*
180 * callback_data_*: supporting data structures for alternate traversal
181 *
182 * We sometimes need to be able to traverse through all the files
183 * in a given tree before all immediate subdirectories within that
184 * tree. Since traverse_trees() doesn't do that naturally, we have
185 * a traverse_trees_wrapper() that stores any immediate
186 * subdirectories while traversing files, then traverses the
187 * immediate subdirectories later. These callback_data* variables
188 * store the information for the subdirectories so that we can do
189 * that traversal order.
190 */
191 struct traversal_callback_data *callback_data;
192 int callback_data_nr, callback_data_alloc;
193 char *callback_data_traverse_path;
194
64aceb6d
EN
195 /*
196 * merge_trees: trees passed to the merge algorithm for the merge
197 *
198 * merge_trees records the trees passed to the merge algorithm. But,
199 * this data also is stored in merge_result->priv. If a sequence of
200 * merges are being done (such as when cherry-picking or rebasing),
201 * the next merge can look at this and re-use information from
202 * previous merges under certain circumstances.
203 *
204 * See also all the cached_* variables.
205 */
206 struct tree *merge_trees[3];
207
208 /*
209 * cached_pairs_valid_side: which side's cached info can be reused
210 *
211 * See the description for merge_trees. For repeated merges, at most
212 * only one side's cached information can be used. Valid values:
213 * MERGE_SIDE2: cached data from side2 can be reused
214 * MERGE_SIDE1: cached data from side1 can be reused
215 * 0: no cached data can be reused
216 */
217 int cached_pairs_valid_side;
218
d29bd6d7
EN
219 /*
220 * cached_pairs: Caching of renames and deletions.
221 *
222 * These are mappings recording renames and deletions of individual
223 * files (not directories). They are thus a map from an old
224 * filename to either NULL (for deletions) or a new filename (for
225 * renames).
226 */
227 struct strmap cached_pairs[3];
228
229 /*
230 * cached_target_names: just the destinations from cached_pairs
231 *
232 * We sometimes want a fast lookup to determine if a given filename
233 * is one of the destinations in cached_pairs. cached_target_names
234 * is thus duplicative information, but it provides a fast lookup.
235 */
236 struct strset cached_target_names[3];
237
238 /*
239 * cached_irrelevant: Caching of rename_sources that aren't relevant.
240 *
241 * If we try to detect a rename for a source path and succeed, it's
242 * part of a rename. If we try to detect a rename for a source path
243 * and fail, then it's a delete. If we do not try to detect a rename
244 * for a path, then we don't know if it's a rename or a delete. If
245 * merge-ort doesn't think the path is relevant, then we just won't
246 * cache anything for that path. But there's a slight problem in
247 * that merge-ort can think a path is RELEVANT_LOCATION, but due to
248 * commit 9bd342137e ("diffcore-rename: determine which
249 * relevant_sources are no longer relevant", 2021-03-13),
250 * diffcore-rename can downgrade the path to RELEVANT_NO_MORE. To
251 * avoid excessive calls to diffcore_rename_extended() we still need
252 * to cache such paths, though we cannot record them as either
253 * renames or deletes. So we cache them here as a "turned out to be
254 * irrelevant *for this commit*" as they are often also irrelevant
255 * for subsequent commits, though we will have to do some extra
256 * checking to see whether such paths become relevant for rename
257 * detection when cherry-picking/rebasing subsequent commits.
258 */
259 struct strset cached_irrelevant[3];
260
864075ec
EN
261 /*
262 * needed_limit: value needed for inexact rename detection to run
263 *
264 * If the current rename limit wasn't high enough for inexact
265 * rename detection to run, this records the limit needed. Otherwise,
266 * this value remains 0.
267 */
268 int needed_limit;
269};
270
5b59c3db
EN
271struct merge_options_internal {
272 /*
273 * paths: primary data structure in all of merge ort.
274 *
275 * The keys of paths:
276 * * are full relative paths from the toplevel of the repository
277 * (e.g. "drivers/firmware/raspberrypi.c").
278 * * store all relevant paths in the repo, both directories and
279 * files (e.g. drivers, drivers/firmware would also be included)
280 * * these keys serve to intern all the path strings, which allows
281 * us to do pointer comparison on directory names instead of
282 * strcmp; we just have to be careful to use the interned strings.
43c1dccb
EN
283 * (Technically paths_to_free may track some strings that were
284 * removed from froms paths.)
5b59c3db
EN
285 *
286 * The values of paths:
287 * * either a pointer to a merged_info, or a conflict_info struct
288 * * merged_info contains all relevant information for a
289 * non-conflicted entry.
290 * * conflict_info contains a merged_info, plus any additional
291 * information about a conflict such as the higher orders stages
292 * involved and the names of the paths those came from (handy
293 * once renames get involved).
294 * * a path may start "conflicted" (i.e. point to a conflict_info)
295 * and then a later step (e.g. three-way content merge) determines
296 * it can be cleanly merged, at which point it'll be marked clean
297 * and the algorithm will ignore any data outside the contained
298 * merged_info for that entry
299 * * If an entry remains conflicted, the merged_info portion of a
300 * conflict_info will later be filled with whatever version of
301 * the file should be placed in the working directory (e.g. an
302 * as-merged-as-possible variation that contains conflict markers).
303 */
304 struct strmap paths;
305
306 /*
307 * conflicted: a subset of keys->values from "paths"
308 *
309 * conflicted is basically an optimization between process_entries()
310 * and record_conflicted_index_entries(); the latter could loop over
311 * ALL the entries in paths AGAIN and look for the ones that are
312 * still conflicted, but since process_entries() has to loop over
313 * all of them, it saves the ones it couldn't resolve in this strmap
314 * so that record_conflicted_index_entries() can iterate just the
315 * relevant entries.
316 */
317 struct strmap conflicted;
318
43c1dccb
EN
319 /*
320 * paths_to_free: additional list of strings to free
321 *
322 * If keys are removed from "paths", they are added to paths_to_free
323 * to ensure they are later freed. We avoid free'ing immediately since
324 * other places (e.g. conflict_info.pathnames[]) may still be
325 * referencing these paths.
326 */
327 struct string_list paths_to_free;
328
c5a6f655
EN
329 /*
330 * output: special messages and conflict notices for various paths
331 *
332 * This is a map of pathnames (a subset of the keys in "paths" above)
333 * to strbufs. It gathers various warning/conflict/notice messages
334 * for later processing.
335 */
336 struct strmap output;
337
5b59c3db 338 /*
864075ec
EN
339 * renames: various data relating to rename detection
340 */
341 struct rename_info renames;
342
ea305a68
EN
343 /*
344 * attr_index: hacky minimal index used for renormalization
345 *
346 * renormalization code _requires_ an index, though it only needs to
347 * find a .gitattributes file within the index. So, when
348 * renormalization is important, we create a special index with just
349 * that one file.
350 */
351 struct index_state attr_index;
352
5b59c3db 353 /*
05b85c6e 354 * current_dir_name, toplevel_dir: temporary vars
5b59c3db 355 *
05b85c6e
EN
356 * These are used in collect_merge_info_callback(), and will set the
357 * various merged_info.directory_name for the various paths we get;
358 * see documentation for that variable and the requirements placed on
359 * that field.
5b59c3db
EN
360 */
361 const char *current_dir_name;
05b85c6e 362 const char *toplevel_dir;
5b59c3db
EN
363
364 /* call_depth: recursion level counter for merging merge bases */
365 int call_depth;
366};
367
368struct version_info {
369 struct object_id oid;
370 unsigned short mode;
371};
372
373struct merged_info {
374 /* if is_null, ignore result. otherwise result has oid & mode */
375 struct version_info result;
376 unsigned is_null:1;
377
378 /*
379 * clean: whether the path in question is cleanly merged.
380 *
381 * see conflict_info.merged for more details.
382 */
383 unsigned clean:1;
384
385 /*
386 * basename_offset: offset of basename of path.
387 *
388 * perf optimization to avoid recomputing offset of final '/'
389 * character in pathname (0 if no '/' in pathname).
390 */
391 size_t basename_offset;
392
393 /*
394 * directory_name: containing directory name.
395 *
396 * Note that we assume directory_name is constructed such that
397 * strcmp(dir1_name, dir2_name) == 0 iff dir1_name == dir2_name,
398 * i.e. string equality is equivalent to pointer equality. For this
399 * to hold, we have to be careful setting directory_name.
400 */
401 const char *directory_name;
402};
403
404struct conflict_info {
405 /*
406 * merged: the version of the path that will be written to working tree
407 *
408 * WARNING: It is critical to check merged.clean and ensure it is 0
409 * before reading any conflict_info fields outside of merged.
410 * Allocated merge_info structs will always have clean set to 1.
411 * Allocated conflict_info structs will have merged.clean set to 0
412 * initially. The merged.clean field is how we know if it is safe
413 * to access other parts of conflict_info besides merged; if a
414 * conflict_info's merged.clean is changed to 1, the rest of the
415 * algorithm is not allowed to look at anything outside of the
416 * merged member anymore.
417 */
418 struct merged_info merged;
419
420 /* oids & modes from each of the three trees for this path */
421 struct version_info stages[3];
422
423 /* pathnames for each stage; may differ due to rename detection */
424 const char *pathnames[3];
425
426 /* Whether this path is/was involved in a directory/file conflict */
427 unsigned df_conflict:1;
428
1c7873cd
EN
429 /*
430 * Whether this path is/was involved in a non-content conflict other
431 * than a directory/file conflict (e.g. rename/rename, rename/delete,
432 * file location based on possible directory rename).
433 */
434 unsigned path_conflict:1;
435
5b59c3db
EN
436 /*
437 * For filemask and dirmask, the ith bit corresponds to whether the
438 * ith entry is a file (filemask) or a directory (dirmask). Thus,
439 * filemask & dirmask is always zero, and filemask | dirmask is at
440 * most 7 but can be less when a path does not appear as either a
441 * file or a directory on at least one side of history.
442 *
443 * Note that these masks are related to enum merge_side, as the ith
444 * entry corresponds to side i.
445 *
446 * These values come from a traverse_trees() call; more info may be
447 * found looking at tree-walk.h's struct traverse_info,
448 * particularly the documentation above the "fn" member (note that
449 * filemask = mask & ~dirmask from that documentation).
450 */
451 unsigned filemask:3;
452 unsigned dirmask:3;
453
454 /*
455 * Optimization to track which stages match, to avoid the need to
456 * recompute it in multiple steps. Either 0 or at least 2 bits are
457 * set; if at least 2 bits are set, their corresponding stages match.
458 */
459 unsigned match_mask:3;
460};
461
04af1879
EN
462/*** Function Grouping: various utility functions ***/
463
98bf9841
EN
464/*
465 * For the next three macros, see warning for conflict_info.merged.
466 *
467 * In each of the below, mi is a struct merged_info*, and ci was defined
468 * as a struct conflict_info* (but we need to verify ci isn't actually
469 * pointed at a struct merged_info*).
470 *
471 * INITIALIZE_CI: Assign ci to mi but only if it's safe; set to NULL otherwise.
472 * VERIFY_CI: Ensure that something we assigned to a conflict_info* is one.
473 * ASSIGN_AND_VERIFY_CI: Similar to VERIFY_CI but do assignment first.
474 */
475#define INITIALIZE_CI(ci, mi) do { \
476 (ci) = (!(mi) || (mi)->clean) ? NULL : (struct conflict_info *)(mi); \
477} while (0)
478#define VERIFY_CI(ci) assert(ci && !ci->merged.clean);
479#define ASSIGN_AND_VERIFY_CI(ci, mi) do { \
480 (ci) = (struct conflict_info *)(mi); \
481 assert((ci) && !(mi)->clean); \
482} while (0)
483
89422d29
EN
484static void free_strmap_strings(struct strmap *map)
485{
486 struct hashmap_iter iter;
487 struct strmap_entry *entry;
488
489 strmap_for_each_entry(map, &iter, entry) {
490 free((char*)entry->key);
491 }
492}
493
43e9c4ee
EN
494static void clear_or_reinit_internal_opts(struct merge_options_internal *opti,
495 int reinitialize)
101bc5bc 496{
f5d9fbc2
EN
497 struct rename_info *renames = &opti->renames;
498 int i;
43e9c4ee
EN
499 void (*strmap_func)(struct strmap *, int) =
500 reinitialize ? strmap_partial_clear : strmap_clear;
a49b55d5
EN
501 void (*strintmap_func)(struct strintmap *) =
502 reinitialize ? strintmap_partial_clear : strintmap_clear;
d29bd6d7
EN
503 void (*strset_func)(struct strset *) =
504 reinitialize ? strset_partial_clear : strset_clear;
101bc5bc
EN
505
506 /*
507 * We marked opti->paths with strdup_strings = 0, so that we
508 * wouldn't have to make another copy of the fullpath created by
509 * make_traverse_path from setup_path_info(). But, now that we've
510 * used it and have no other references to these strings, it is time
511 * to deallocate them.
512 */
513 free_strmap_strings(&opti->paths);
43e9c4ee 514 strmap_func(&opti->paths, 1);
101bc5bc
EN
515
516 /*
517 * All keys and values in opti->conflicted are a subset of those in
518 * opti->paths. We don't want to deallocate anything twice, so we
519 * don't free the keys and we pass 0 for free_values.
520 */
43e9c4ee 521 strmap_func(&opti->conflicted, 0);
43c1dccb
EN
522
523 /*
524 * opti->paths_to_free is similar to opti->paths; we created it with
525 * strdup_strings = 0 to avoid making _another_ copy of the fullpath
526 * but now that we've used it and have no other references to these
527 * strings, it is time to deallocate them. We do so by temporarily
528 * setting strdup_strings to 1.
529 */
530 opti->paths_to_free.strdup_strings = 1;
531 string_list_clear(&opti->paths_to_free, 0);
532 opti->paths_to_free.strdup_strings = 0;
c5a6f655 533
1218b3ab 534 if (opti->attr_index.cache_nr) /* true iff opt->renormalize */
ea305a68
EN
535 discard_index(&opti->attr_index);
536
f5d9fbc2
EN
537 /* Free memory used by various renames maps */
538 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; ++i) {
a49b55d5 539 strintmap_func(&renames->dirs_removed[i]);
f5d9fbc2 540 strmap_func(&renames->dir_renames[i], 0);
a49b55d5 541 strintmap_func(&renames->relevant_sources[i]);
d5098029
EN
542 if (!reinitialize)
543 assert(renames->cached_pairs_valid_side == 0);
544 if (i != renames->cached_pairs_valid_side) {
545 strset_func(&renames->cached_target_names[i]);
546 strmap_func(&renames->cached_pairs[i], 1);
547 strset_func(&renames->cached_irrelevant[i]);
548 partial_clear_dir_rename_count(&renames->dir_rename_count[i]);
549 if (!reinitialize)
550 strmap_clear(&renames->dir_rename_count[i], 1);
551 }
f5d9fbc2 552 }
d478f567
EN
553 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; ++i) {
554 strintmap_func(&renames->deferred[i].possible_trivial_merges);
555 strset_func(&renames->deferred[i].target_dirs);
556 renames->deferred[i].trivial_merges_okay = 1; /* 1 == maybe */
557 }
64aceb6d
EN
558 renames->cached_pairs_valid_side = 0;
559 renames->dir_rename_mask = 0;
f5d9fbc2 560
c5a6f655
EN
561 if (!reinitialize) {
562 struct hashmap_iter iter;
563 struct strmap_entry *e;
564
565 /* Release and free each strbuf found in output */
566 strmap_for_each_entry(&opti->output, &iter, e) {
567 struct strbuf *sb = e->value;
568 strbuf_release(sb);
569 /*
570 * While strictly speaking we don't need to free(sb)
571 * here because we could pass free_values=1 when
572 * calling strmap_clear() on opti->output, that would
573 * require strmap_clear to do another
574 * strmap_for_each_entry() loop, so we just free it
575 * while we're iterating anyway.
576 */
577 free(sb);
578 }
579 strmap_clear(&opti->output, 0);
580 }
beb06145
EN
581
582 /* Clean out callback_data as well. */
583 FREE_AND_NULL(renames->callback_data);
584 renames->callback_data_nr = renames->callback_data_alloc = 0;
101bc5bc
EN
585}
586
0c0d705b
EN
587static int err(struct merge_options *opt, const char *err, ...)
588{
589 va_list params;
590 struct strbuf sb = STRBUF_INIT;
591
592 strbuf_addstr(&sb, "error: ");
593 va_start(params, err);
594 strbuf_vaddf(&sb, err, params);
595 va_end(params);
596
597 error("%s", sb.buf);
598 strbuf_release(&sb);
599
600 return -1;
601}
602
c73cda76
EN
603static void format_commit(struct strbuf *sb,
604 int indent,
605 struct commit *commit)
606{
70f19c7f
EN
607 struct merge_remote_desc *desc;
608 struct pretty_print_context ctx = {0};
609 ctx.abbrev = DEFAULT_ABBREV;
610
611 strbuf_addchars(sb, ' ', indent);
612 desc = merge_remote_util(commit);
613 if (desc) {
614 strbuf_addf(sb, "virtual %s\n", desc->name);
615 return;
616 }
617
618 format_commit_message(commit, "%h %s", sb, &ctx);
619 strbuf_addch(sb, '\n');
c73cda76
EN
620}
621
c5a6f655
EN
622__attribute__((format (printf, 4, 5)))
623static void path_msg(struct merge_options *opt,
624 const char *path,
625 int omittable_hint, /* skippable under --remerge-diff */
626 const char *fmt, ...)
627{
628 va_list ap;
629 struct strbuf *sb = strmap_get(&opt->priv->output, path);
630 if (!sb) {
631 sb = xmalloc(sizeof(*sb));
632 strbuf_init(sb, 0);
633 strmap_put(&opt->priv->output, path, sb);
634 }
635
636 va_start(ap, fmt);
637 strbuf_vaddf(sb, fmt, ap);
638 va_end(ap);
639
640 strbuf_addch(sb, '\n');
641}
642
5a1a1e8e
EN
643/* add a string to a strbuf, but converting "/" to "_" */
644static void add_flattened_path(struct strbuf *out, const char *s)
645{
646 size_t i = out->len;
647 strbuf_addstr(out, s);
648 for (; i < out->len; i++)
649 if (out->buf[i] == '/')
650 out->buf[i] = '_';
651}
652
23366d2a
EN
653static char *unique_path(struct strmap *existing_paths,
654 const char *path,
655 const char *branch)
656{
5a1a1e8e
EN
657 struct strbuf newpath = STRBUF_INIT;
658 int suffix = 0;
659 size_t base_len;
660
661 strbuf_addf(&newpath, "%s~", path);
662 add_flattened_path(&newpath, branch);
663
664 base_len = newpath.len;
665 while (strmap_contains(existing_paths, newpath.buf)) {
666 strbuf_setlen(&newpath, base_len);
667 strbuf_addf(&newpath, "_%d", suffix++);
668 }
669
670 return strbuf_detach(&newpath, NULL);
23366d2a
EN
671}
672
04af1879
EN
673/*** Function Grouping: functions related to collect_merge_info() ***/
674
a68e6cea
EN
675static int traverse_trees_wrapper_callback(int n,
676 unsigned long mask,
677 unsigned long dirmask,
678 struct name_entry *names,
679 struct traverse_info *info)
680{
681 struct merge_options *opt = info->data;
682 struct rename_info *renames = &opt->priv->renames;
2fd9eda4 683 unsigned filemask = mask & ~dirmask;
a68e6cea
EN
684
685 assert(n==3);
686
687 if (!renames->callback_data_traverse_path)
688 renames->callback_data_traverse_path = xstrdup(info->traverse_path);
689
2fd9eda4
EN
690 if (filemask && filemask == renames->dir_rename_mask)
691 renames->dir_rename_mask = 0x07;
692
a68e6cea
EN
693 ALLOC_GROW(renames->callback_data, renames->callback_data_nr + 1,
694 renames->callback_data_alloc);
695 renames->callback_data[renames->callback_data_nr].mask = mask;
696 renames->callback_data[renames->callback_data_nr].dirmask = dirmask;
697 COPY_ARRAY(renames->callback_data[renames->callback_data_nr].names,
698 names, 3);
699 renames->callback_data_nr++;
700
701 return mask;
702}
703
704/*
705 * Much like traverse_trees(), BUT:
706 * - read all the tree entries FIRST, saving them
707 * - note that the above step provides an opportunity to compute necessary
708 * additional details before the "real" traversal
709 * - loop through the saved entries and call the original callback on them
710 */
a68e6cea
EN
711static int traverse_trees_wrapper(struct index_state *istate,
712 int n,
713 struct tree_desc *t,
714 struct traverse_info *info)
715{
716 int ret, i, old_offset;
717 traverse_callback_t old_fn;
718 char *old_callback_data_traverse_path;
719 struct merge_options *opt = info->data;
720 struct rename_info *renames = &opt->priv->renames;
721
2fd9eda4
EN
722 assert(renames->dir_rename_mask == 2 || renames->dir_rename_mask == 4);
723
a68e6cea
EN
724 old_callback_data_traverse_path = renames->callback_data_traverse_path;
725 old_fn = info->fn;
726 old_offset = renames->callback_data_nr;
727
728 renames->callback_data_traverse_path = NULL;
729 info->fn = traverse_trees_wrapper_callback;
730 ret = traverse_trees(istate, n, t, info);
731 if (ret < 0)
732 return ret;
733
734 info->traverse_path = renames->callback_data_traverse_path;
735 info->fn = old_fn;
736 for (i = old_offset; i < renames->callback_data_nr; ++i) {
737 info->fn(n,
738 renames->callback_data[i].mask,
739 renames->callback_data[i].dirmask,
740 renames->callback_data[i].names,
741 info);
742 }
743
744 renames->callback_data_nr = old_offset;
745 free(renames->callback_data_traverse_path);
746 renames->callback_data_traverse_path = old_callback_data_traverse_path;
747 info->traverse_path = NULL;
748 return 0;
749}
750
98bf9841
EN
751static void setup_path_info(struct merge_options *opt,
752 struct string_list_item *result,
753 const char *current_dir_name,
754 int current_dir_name_len,
755 char *fullpath, /* we'll take over ownership */
756 struct name_entry *names,
757 struct name_entry *merged_version,
758 unsigned is_null, /* boolean */
759 unsigned df_conflict, /* boolean */
760 unsigned filemask,
761 unsigned dirmask,
762 int resolved /* boolean */)
763{
764 /* result->util is void*, so mi is a convenience typed variable */
765 struct merged_info *mi;
766
767 assert(!is_null || resolved);
768 assert(!df_conflict || !resolved); /* df_conflict implies !resolved */
769 assert(resolved == (merged_version != NULL));
770
771 mi = xcalloc(1, resolved ? sizeof(struct merged_info) :
772 sizeof(struct conflict_info));
773 mi->directory_name = current_dir_name;
774 mi->basename_offset = current_dir_name_len;
775 mi->clean = !!resolved;
776 if (resolved) {
777 mi->result.mode = merged_version->mode;
778 oidcpy(&mi->result.oid, &merged_version->oid);
779 mi->is_null = !!is_null;
780 } else {
781 int i;
782 struct conflict_info *ci;
783
784 ASSIGN_AND_VERIFY_CI(ci, mi);
785 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
786 ci->pathnames[i] = fullpath;
787 ci->stages[i].mode = names[i].mode;
788 oidcpy(&ci->stages[i].oid, &names[i].oid);
789 }
790 ci->filemask = filemask;
791 ci->dirmask = dirmask;
792 ci->df_conflict = !!df_conflict;
793 if (dirmask)
794 /*
795 * Assume is_null for now, but if we have entries
796 * under the directory then when it is complete in
797 * write_completed_directory() it'll update this.
798 * Also, for D/F conflicts, we have to handle the
799 * directory first, then clear this bit and process
800 * the file to see how it is handled -- that occurs
801 * near the top of process_entry().
802 */
803 mi->is_null = 1;
804 }
805 strmap_put(&opt->priv->paths, fullpath, mi);
806 result->string = fullpath;
807 result->util = mi;
808}
809
f78cf976
EN
810static void add_pair(struct merge_options *opt,
811 struct name_entry *names,
812 const char *pathname,
813 unsigned side,
32a56dfb 814 unsigned is_add /* if false, is_delete */,
2fd9eda4
EN
815 unsigned match_mask,
816 unsigned dir_rename_mask)
f78cf976
EN
817{
818 struct diff_filespec *one, *two;
819 struct rename_info *renames = &opt->priv->renames;
820 int names_idx = is_add ? side : 0;
821
25e65b6d 822 if (is_add) {
ef68c3d8 823 assert(match_mask == 0 || match_mask == 6);
25e65b6d
EN
824 if (strset_contains(&renames->cached_target_names[side],
825 pathname))
826 return;
827 } else {
32a56dfb 828 unsigned content_relevant = (match_mask == 0);
2fd9eda4 829 unsigned location_relevant = (dir_rename_mask == 0x07);
32a56dfb 830
ef68c3d8
EN
831 assert(match_mask == 0 || match_mask == 3 || match_mask == 5);
832
25e65b6d
EN
833 /*
834 * If pathname is found in cached_irrelevant[side] due to
835 * previous pick but for this commit content is relevant,
836 * then we need to remove it from cached_irrelevant.
837 */
838 if (content_relevant)
839 /* strset_remove is no-op if strset doesn't have key */
840 strset_remove(&renames->cached_irrelevant[side],
841 pathname);
842
843 /*
844 * We do not need to re-detect renames for paths that we already
845 * know the pairing, i.e. for cached_pairs (or
846 * cached_irrelevant). However, handle_deferred_entries() needs
847 * to loop over the union of keys from relevant_sources[side] and
848 * cached_pairs[side], so for simplicity we set relevant_sources
849 * for all the cached_pairs too and then strip them back out in
850 * prune_cached_from_relevant() at the beginning of
851 * detect_regular_renames().
852 */
ec59da60
EN
853 if (content_relevant || location_relevant) {
854 /* content_relevant trumps location_relevant */
855 strintmap_set(&renames->relevant_sources[side], pathname,
856 content_relevant ? RELEVANT_CONTENT : RELEVANT_LOCATION);
857 }
25e65b6d
EN
858
859 /*
860 * Avoid creating pair if we've already cached rename results.
861 * Note that we do this after setting relevant_sources[side]
862 * as noted in the comment above.
863 */
864 if (strmap_contains(&renames->cached_pairs[side], pathname) ||
865 strset_contains(&renames->cached_irrelevant[side], pathname))
866 return;
32a56dfb
EN
867 }
868
f78cf976
EN
869 one = alloc_filespec(pathname);
870 two = alloc_filespec(pathname);
871 fill_filespec(is_add ? two : one,
872 &names[names_idx].oid, 1, names[names_idx].mode);
873 diff_queue(&renames->pairs[side], one, two);
874}
875
eb3e3e1d
EN
876static void collect_rename_info(struct merge_options *opt,
877 struct name_entry *names,
878 const char *dirname,
879 const char *fullname,
880 unsigned filemask,
881 unsigned dirmask,
882 unsigned match_mask)
883{
884 struct rename_info *renames = &opt->priv->renames;
f78cf976 885 unsigned side;
eb3e3e1d 886
2fd9eda4
EN
887 /*
888 * Update dir_rename_mask (determines ignore-rename-source validity)
889 *
890 * dir_rename_mask helps us keep track of when directory rename
891 * detection may be relevant. Basically, whenver a directory is
892 * removed on one side of history, and a file is added to that
893 * directory on the other side of history, directory rename
894 * detection is relevant (meaning we have to detect renames for all
895 * files within that directory to deduce where the directory
896 * moved). Also, whenever a directory needs directory rename
897 * detection, due to the "majority rules" choice for where to move
898 * it (see t6423 testcase 1f), we also need to detect renames for
899 * all files within subdirectories of that directory as well.
900 *
901 * Here we haven't looked at files within the directory yet, we are
902 * just looking at the directory itself. So, if we aren't yet in
903 * a case where a parent directory needed directory rename detection
904 * (i.e. dir_rename_mask != 0x07), and if the directory was removed
905 * on one side of history, record the mask of the other side of
906 * history in dir_rename_mask.
907 */
908 if (renames->dir_rename_mask != 0x07 &&
909 (dirmask == 3 || dirmask == 5)) {
910 /* simple sanity check */
911 assert(renames->dir_rename_mask == 0 ||
912 renames->dir_rename_mask == (dirmask & ~1));
913 /* update dir_rename_mask; have it record mask of new side */
914 renames->dir_rename_mask = (dirmask & ~1);
915 }
916
eb3e3e1d
EN
917 /* Update dirs_removed, as needed */
918 if (dirmask == 1 || dirmask == 3 || dirmask == 5) {
919 /* absent_mask = 0x07 - dirmask; sides = absent_mask/2 */
920 unsigned sides = (0x07 - dirmask)/2;
fb52938e
EN
921 unsigned relevance = (renames->dir_rename_mask == 0x07) ?
922 RELEVANT_FOR_ANCESTOR : NOT_RELEVANT;
923 /*
924 * Record relevance of this directory. However, note that
925 * when collect_merge_info_callback() recurses into this
926 * directory and calls collect_rename_info() on paths
927 * within that directory, if we find a path that was added
928 * to this directory on the other side of history, we will
929 * upgrade this value to RELEVANT_FOR_SELF; see below.
930 */
eb3e3e1d 931 if (sides & 1)
fb52938e
EN
932 strintmap_set(&renames->dirs_removed[1], fullname,
933 relevance);
eb3e3e1d 934 if (sides & 2)
fb52938e
EN
935 strintmap_set(&renames->dirs_removed[2], fullname,
936 relevance);
937 }
938
939 /*
940 * Here's the block that potentially upgrades to RELEVANT_FOR_SELF.
941 * When we run across a file added to a directory. In such a case,
942 * find the directory of the file and upgrade its relevance.
943 */
944 if (renames->dir_rename_mask == 0x07 &&
945 (filemask == 2 || filemask == 4)) {
946 /*
947 * Need directory rename for parent directory on other side
948 * of history from added file. Thus
949 * side = (~filemask & 0x06) >> 1
950 * or
951 * side = 3 - (filemask/2).
952 */
953 unsigned side = 3 - (filemask >> 1);
954 strintmap_set(&renames->dirs_removed[side], dirname,
955 RELEVANT_FOR_SELF);
eb3e3e1d 956 }
f78cf976
EN
957
958 if (filemask == 0 || filemask == 7)
959 return;
960
961 for (side = MERGE_SIDE1; side <= MERGE_SIDE2; ++side) {
962 unsigned side_mask = (1 << side);
963
964 /* Check for deletion on side */
965 if ((filemask & 1) && !(filemask & side_mask))
32a56dfb 966 add_pair(opt, names, fullname, side, 0 /* delete */,
2fd9eda4
EN
967 match_mask & filemask,
968 renames->dir_rename_mask);
f78cf976
EN
969
970 /* Check for addition on side */
971 if (!(filemask & 1) && (filemask & side_mask))
32a56dfb 972 add_pair(opt, names, fullname, side, 1 /* add */,
2fd9eda4
EN
973 match_mask & filemask,
974 renames->dir_rename_mask);
f78cf976 975 }
eb3e3e1d
EN
976}
977
d2bc1994
EN
978static int collect_merge_info_callback(int n,
979 unsigned long mask,
980 unsigned long dirmask,
981 struct name_entry *names,
982 struct traverse_info *info)
983{
984 /*
985 * n is 3. Always.
986 * common ancestor (mbase) has mask 1, and stored in index 0 of names
987 * head of side 1 (side1) has mask 2, and stored in index 1 of names
988 * head of side 2 (side2) has mask 4, and stored in index 2 of names
989 */
990 struct merge_options *opt = info->data;
991 struct merge_options_internal *opti = opt->priv;
2fd9eda4 992 struct rename_info *renames = &opt->priv->renames;
98bf9841
EN
993 struct string_list_item pi; /* Path Info */
994 struct conflict_info *ci; /* typed alias to pi.util (which is void*) */
d2bc1994
EN
995 struct name_entry *p;
996 size_t len;
997 char *fullpath;
98bf9841 998 const char *dirname = opti->current_dir_name;
2fd9eda4 999 unsigned prev_dir_rename_mask = renames->dir_rename_mask;
d2bc1994 1000 unsigned filemask = mask & ~dirmask;
34e557af 1001 unsigned match_mask = 0; /* will be updated below */
d2bc1994
EN
1002 unsigned mbase_null = !(mask & 1);
1003 unsigned side1_null = !(mask & 2);
1004 unsigned side2_null = !(mask & 4);
885f0063
EN
1005 unsigned side1_matches_mbase = (!side1_null && !mbase_null &&
1006 names[0].mode == names[1].mode &&
1007 oideq(&names[0].oid, &names[1].oid));
1008 unsigned side2_matches_mbase = (!side2_null && !mbase_null &&
1009 names[0].mode == names[2].mode &&
1010 oideq(&names[0].oid, &names[2].oid));
1011 unsigned sides_match = (!side1_null && !side2_null &&
1012 names[1].mode == names[2].mode &&
1013 oideq(&names[1].oid, &names[2].oid));
d2bc1994 1014
34e557af
EN
1015 /*
1016 * Note: When a path is a file on one side of history and a directory
1017 * in another, we have a directory/file conflict. In such cases, if
1018 * the conflict doesn't resolve from renames and deletions, then we
1019 * always leave directories where they are and move files out of the
1020 * way. Thus, while struct conflict_info has a df_conflict field to
1021 * track such conflicts, we ignore that field for any directories at
1022 * a path and only pay attention to it for files at the given path.
1023 * The fact that we leave directories were they are also means that
1024 * we do not need to worry about getting additional df_conflict
1025 * information propagated from parent directories down to children
1026 * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
1027 * sets a newinfo.df_conflicts field specifically to propagate it).
1028 */
1029 unsigned df_conflict = (filemask != 0) && (dirmask != 0);
1030
d2bc1994
EN
1031 /* n = 3 is a fundamental assumption. */
1032 if (n != 3)
1033 BUG("Called collect_merge_info_callback wrong");
1034
1035 /*
1036 * A bunch of sanity checks verifying that traverse_trees() calls
1037 * us the way I expect. Could just remove these at some point,
1038 * though maybe they are helpful to future code readers.
1039 */
1040 assert(mbase_null == is_null_oid(&names[0].oid));
1041 assert(side1_null == is_null_oid(&names[1].oid));
1042 assert(side2_null == is_null_oid(&names[2].oid));
1043 assert(!mbase_null || !side1_null || !side2_null);
1044 assert(mask > 0 && mask < 8);
1045
34e557af
EN
1046 /* Determine match_mask */
1047 if (side1_matches_mbase)
1048 match_mask = (side2_matches_mbase ? 7 : 3);
1049 else if (side2_matches_mbase)
1050 match_mask = 5;
1051 else if (sides_match)
1052 match_mask = 6;
1053
d2bc1994
EN
1054 /*
1055 * Get the name of the relevant filepath, which we'll pass to
1056 * setup_path_info() for tracking.
1057 */
1058 p = names;
1059 while (!p->mode)
1060 p++;
1061 len = traverse_path_len(info, p->pathlen);
1062
1063 /* +1 in both of the following lines to include the NUL byte */
1064 fullpath = xmalloc(len + 1);
1065 make_traverse_path(fullpath, len + 1, info, p->path, p->pathlen);
1066
291f29ca
EN
1067 /*
1068 * If mbase, side1, and side2 all match, we can resolve early. Even
1069 * if these are trees, there will be no renames or anything
1070 * underneath.
1071 */
1072 if (side1_matches_mbase && side2_matches_mbase) {
1073 /* mbase, side1, & side2 all match; use mbase as resolution */
1074 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
528fc51b
EN
1075 names, names+0, mbase_null, 0 /* df_conflict */,
1076 filemask, dirmask, 1 /* resolved */);
291f29ca
EN
1077 return mask;
1078 }
1079
785bf208
EN
1080 /*
1081 * If the sides match, and all three paths are present and are
1082 * files, then we can take either as the resolution. We can't do
1083 * this with trees, because there may be rename sources from the
1084 * merge_base.
1085 */
1086 if (sides_match && filemask == 0x07) {
1087 /* use side1 (== side2) version as resolution */
1088 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1089 names, names+1, side1_null, 0,
1090 filemask, dirmask, 1);
1091 return mask;
1092 }
1093
1094 /*
1095 * If side1 matches mbase and all three paths are present and are
1096 * files, then we can use side2 as the resolution. We cannot
1097 * necessarily do so this for trees, because there may be rename
1098 * destinations within side2.
1099 */
1100 if (side1_matches_mbase && filemask == 0x07) {
1101 /* use side2 version as resolution */
1102 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1103 names, names+2, side2_null, 0,
1104 filemask, dirmask, 1);
1105 return mask;
1106 }
1107
1108 /* Similar to above but swapping sides 1 and 2 */
1109 if (side2_matches_mbase && filemask == 0x07) {
1110 /* use side1 version as resolution */
1111 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1112 names, names+1, side1_null, 0,
1113 filemask, dirmask, 1);
1114 return mask;
1115 }
1116
eb3e3e1d 1117 /*
528fc51b
EN
1118 * Sometimes we can tell that a source path need not be included in
1119 * rename detection -- namely, whenever either
1120 * side1_matches_mbase && side2_null
1121 * or
1122 * side2_matches_mbase && side1_null
1123 * However, we call collect_rename_info() even in those cases,
1124 * because exact renames are cheap and would let us remove both a
1125 * source and destination path. We'll cull the unneeded sources
1126 * later.
eb3e3e1d
EN
1127 */
1128 collect_rename_info(opt, names, dirname, fullpath,
1129 filemask, dirmask, match_mask);
1130
d2bc1994 1131 /*
528fc51b
EN
1132 * None of the special cases above matched, so we have a
1133 * provisional conflict. (Rename detection might allow us to
1134 * unconflict some more cases, but that comes later so all we can
1135 * do now is record the different non-null file hashes.)
d2bc1994 1136 */
98bf9841
EN
1137 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1138 names, NULL, 0, df_conflict, filemask, dirmask, 0);
1139
1140 ci = pi.util;
1141 VERIFY_CI(ci);
34e557af 1142 ci->match_mask = match_mask;
d2bc1994
EN
1143
1144 /* If dirmask, recurse into subdirectories */
1145 if (dirmask) {
1146 struct traverse_info newinfo;
1147 struct tree_desc t[3];
1148 void *buf[3] = {NULL, NULL, NULL};
1149 const char *original_dir_name;
1150 int i, ret;
1151
1152 ci->match_mask &= filemask;
1153 newinfo = *info;
1154 newinfo.prev = info;
1155 newinfo.name = p->path;
1156 newinfo.namelen = p->pathlen;
1157 newinfo.pathlen = st_add3(newinfo.pathlen, p->pathlen, 1);
34e557af
EN
1158 /*
1159 * If this directory we are about to recurse into cared about
1160 * its parent directory (the current directory) having a D/F
1161 * conflict, then we'd propagate the masks in this way:
1162 * newinfo.df_conflicts |= (mask & ~dirmask);
1163 * But we don't worry about propagating D/F conflicts. (See
1164 * comment near setting of local df_conflict variable near
1165 * the beginning of this function).
1166 */
d2bc1994
EN
1167
1168 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
885f0063
EN
1169 if (i == 1 && side1_matches_mbase)
1170 t[1] = t[0];
1171 else if (i == 2 && side2_matches_mbase)
1172 t[2] = t[0];
1173 else if (i == 2 && sides_match)
1174 t[2] = t[1];
1175 else {
1176 const struct object_id *oid = NULL;
1177 if (dirmask & 1)
1178 oid = &names[i].oid;
1179 buf[i] = fill_tree_descriptor(opt->repo,
1180 t + i, oid);
1181 }
d2bc1994
EN
1182 dirmask >>= 1;
1183 }
1184
1185 original_dir_name = opti->current_dir_name;
98bf9841 1186 opti->current_dir_name = pi.string;
2fd9eda4
EN
1187 if (renames->dir_rename_mask == 0 ||
1188 renames->dir_rename_mask == 0x07)
1189 ret = traverse_trees(NULL, 3, t, &newinfo);
1190 else
1191 ret = traverse_trees_wrapper(NULL, 3, t, &newinfo);
d2bc1994 1192 opti->current_dir_name = original_dir_name;
2fd9eda4 1193 renames->dir_rename_mask = prev_dir_rename_mask;
d2bc1994
EN
1194
1195 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
1196 free(buf[i]);
1197
1198 if (ret < 0)
1199 return -1;
1200 }
1201
1202 return mask;
1203}
1204
e0ef578e
EN
1205MAYBE_UNUSED
1206static int handle_deferred_entries(struct merge_options *opt,
1207 struct traverse_info *info)
1208{
1209 struct rename_info *renames = &opt->priv->renames;
1210 struct hashmap_iter iter;
1211 struct strmap_entry *entry;
1212 int side, ret = 0;
1213
1214 for (side = MERGE_SIDE1; side <= MERGE_SIDE2; side++) {
1215 renames->deferred[side].trivial_merges_okay = 0;
1216 strintmap_for_each_entry(&renames->deferred[side].possible_trivial_merges,
1217 &iter, entry) {
1218 const char *path = entry->key;
1219 unsigned dir_rename_mask = (intptr_t)entry->value;
1220 struct conflict_info *ci;
1221 unsigned dirmask;
1222 struct tree_desc t[3];
1223 void *buf[3] = {NULL,};
1224 int i;
1225
1226 ci = strmap_get(&opt->priv->paths, path);
1227 VERIFY_CI(ci);
1228 dirmask = ci->dirmask;
1229
1230 info->name = path;
1231 info->namelen = strlen(path);
1232 info->pathlen = info->namelen + 1;
1233
1234 for (i = 0; i < 3; i++, dirmask >>= 1) {
1235 if (i == 1 && ci->match_mask == 3)
1236 t[1] = t[0];
1237 else if (i == 2 && ci->match_mask == 5)
1238 t[2] = t[0];
1239 else if (i == 2 && ci->match_mask == 6)
1240 t[2] = t[1];
1241 else {
1242 const struct object_id *oid = NULL;
1243 if (dirmask & 1)
1244 oid = &ci->stages[i].oid;
1245 buf[i] = fill_tree_descriptor(opt->repo,
1246 t+i, oid);
1247 }
1248 }
1249
1250 ci->match_mask &= ci->filemask;
1251 opt->priv->current_dir_name = path;
1252 renames->dir_rename_mask = dir_rename_mask;
1253 if (renames->dir_rename_mask == 0 ||
1254 renames->dir_rename_mask == 0x07)
1255 ret = traverse_trees(NULL, 3, t, info);
1256 else
1257 ret = traverse_trees_wrapper(NULL, 3, t, info);
1258
1259 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
1260 free(buf[i]);
1261
1262 if (ret < 0)
1263 return ret;
1264 }
1265 }
1266 return ret;
1267}
1268
231e2dd4
EN
1269static int collect_merge_info(struct merge_options *opt,
1270 struct tree *merge_base,
1271 struct tree *side1,
1272 struct tree *side2)
1273{
d2bc1994
EN
1274 int ret;
1275 struct tree_desc t[3];
1276 struct traverse_info info;
d2bc1994 1277
05b85c6e
EN
1278 opt->priv->toplevel_dir = "";
1279 opt->priv->current_dir_name = opt->priv->toplevel_dir;
1280 setup_traverse_info(&info, opt->priv->toplevel_dir);
d2bc1994
EN
1281 info.fn = collect_merge_info_callback;
1282 info.data = opt;
1283 info.show_all_errors = 1;
1284
1285 parse_tree(merge_base);
1286 parse_tree(side1);
1287 parse_tree(side2);
1288 init_tree_desc(t + 0, merge_base->buffer, merge_base->size);
1289 init_tree_desc(t + 1, side1->buffer, side1->size);
1290 init_tree_desc(t + 2, side2->buffer, side2->size);
1291
557ac035 1292 trace2_region_enter("merge", "traverse_trees", opt->repo);
d2bc1994 1293 ret = traverse_trees(NULL, 3, t, &info);
557ac035 1294 trace2_region_leave("merge", "traverse_trees", opt->repo);
d2bc1994
EN
1295
1296 return ret;
231e2dd4
EN
1297}
1298
04af1879
EN
1299/*** Function Grouping: functions related to threeway content merges ***/
1300
c73cda76
EN
1301static int find_first_merges(struct repository *repo,
1302 const char *path,
1303 struct commit *a,
1304 struct commit *b,
1305 struct object_array *result)
1306{
4204cd59
EN
1307 int i, j;
1308 struct object_array merges = OBJECT_ARRAY_INIT;
1309 struct commit *commit;
1310 int contains_another;
1311
1312 char merged_revision[GIT_MAX_HEXSZ + 2];
1313 const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1314 "--all", merged_revision, NULL };
1315 struct rev_info revs;
1316 struct setup_revision_opt rev_opts;
1317
1318 memset(result, 0, sizeof(struct object_array));
1319 memset(&rev_opts, 0, sizeof(rev_opts));
1320
1321 /* get all revisions that merge commit a */
1322 xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
1323 oid_to_hex(&a->object.oid));
1324 repo_init_revisions(repo, &revs, NULL);
1325 rev_opts.submodule = path;
1326 /* FIXME: can't handle linked worktrees in submodules yet */
1327 revs.single_worktree = path != NULL;
1328 setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1329
1330 /* save all revisions from the above list that contain b */
1331 if (prepare_revision_walk(&revs))
1332 die("revision walk setup failed");
1333 while ((commit = get_revision(&revs)) != NULL) {
1334 struct object *o = &(commit->object);
1335 if (in_merge_bases(b, commit))
1336 add_object_array(o, NULL, &merges);
1337 }
1338 reset_revision_walk();
1339
1340 /* Now we've got all merges that contain a and b. Prune all
1341 * merges that contain another found merge and save them in
1342 * result.
1343 */
1344 for (i = 0; i < merges.nr; i++) {
1345 struct commit *m1 = (struct commit *) merges.objects[i].item;
1346
1347 contains_another = 0;
1348 for (j = 0; j < merges.nr; j++) {
1349 struct commit *m2 = (struct commit *) merges.objects[j].item;
1350 if (i != j && in_merge_bases(m2, m1)) {
1351 contains_another = 1;
1352 break;
1353 }
1354 }
1355
1356 if (!contains_another)
1357 add_object_array(merges.objects[i].item, NULL, result);
1358 }
1359
1360 object_array_clear(&merges);
1361 return result->nr;
c73cda76
EN
1362}
1363
62fdec17
EN
1364static int merge_submodule(struct merge_options *opt,
1365 const char *path,
1366 const struct object_id *o,
1367 const struct object_id *a,
1368 const struct object_id *b,
1369 struct object_id *result)
1370{
c73cda76
EN
1371 struct commit *commit_o, *commit_a, *commit_b;
1372 int parent_count;
1373 struct object_array merges;
1374 struct strbuf sb = STRBUF_INIT;
1375
1376 int i;
1377 int search = !opt->priv->call_depth;
1378
1379 /* store fallback answer in result in case we fail */
1380 oidcpy(result, opt->priv->call_depth ? o : a);
1381
1382 /* we can not handle deletion conflicts */
1383 if (is_null_oid(o))
1384 return 0;
1385 if (is_null_oid(a))
1386 return 0;
1387 if (is_null_oid(b))
1388 return 0;
1389
1390 if (add_submodule_odb(path)) {
1391 path_msg(opt, path, 0,
1392 _("Failed to merge submodule %s (not checked out)"),
1393 path);
1394 return 0;
1395 }
1396
1397 if (!(commit_o = lookup_commit_reference(opt->repo, o)) ||
1398 !(commit_a = lookup_commit_reference(opt->repo, a)) ||
1399 !(commit_b = lookup_commit_reference(opt->repo, b))) {
1400 path_msg(opt, path, 0,
1401 _("Failed to merge submodule %s (commits not present)"),
1402 path);
1403 return 0;
1404 }
1405
1406 /* check whether both changes are forward */
1407 if (!in_merge_bases(commit_o, commit_a) ||
1408 !in_merge_bases(commit_o, commit_b)) {
1409 path_msg(opt, path, 0,
1410 _("Failed to merge submodule %s "
1411 "(commits don't follow merge-base)"),
1412 path);
1413 return 0;
1414 }
1415
1416 /* Case #1: a is contained in b or vice versa */
1417 if (in_merge_bases(commit_a, commit_b)) {
1418 oidcpy(result, b);
1419 path_msg(opt, path, 1,
1420 _("Note: Fast-forwarding submodule %s to %s"),
1421 path, oid_to_hex(b));
1422 return 1;
1423 }
1424 if (in_merge_bases(commit_b, commit_a)) {
1425 oidcpy(result, a);
1426 path_msg(opt, path, 1,
1427 _("Note: Fast-forwarding submodule %s to %s"),
1428 path, oid_to_hex(a));
1429 return 1;
1430 }
1431
1432 /*
1433 * Case #2: There are one or more merges that contain a and b in
1434 * the submodule. If there is only one, then present it as a
1435 * suggestion to the user, but leave it marked unmerged so the
1436 * user needs to confirm the resolution.
1437 */
1438
1439 /* Skip the search if makes no sense to the calling context. */
1440 if (!search)
1441 return 0;
1442
1443 /* find commit which merges them */
1444 parent_count = find_first_merges(opt->repo, path, commit_a, commit_b,
1445 &merges);
1446 switch (parent_count) {
1447 case 0:
1448 path_msg(opt, path, 0, _("Failed to merge submodule %s"), path);
1449 break;
1450
1451 case 1:
1452 format_commit(&sb, 4,
1453 (struct commit *)merges.objects[0].item);
1454 path_msg(opt, path, 0,
1455 _("Failed to merge submodule %s, but a possible merge "
1456 "resolution exists:\n%s\n"),
1457 path, sb.buf);
1458 path_msg(opt, path, 1,
1459 _("If this is correct simply add it to the index "
1460 "for example\n"
1461 "by using:\n\n"
1462 " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1463 "which will accept this suggestion.\n"),
1464 oid_to_hex(&merges.objects[0].item->oid), path);
1465 strbuf_release(&sb);
1466 break;
1467 default:
1468 for (i = 0; i < merges.nr; i++)
1469 format_commit(&sb, 4,
1470 (struct commit *)merges.objects[i].item);
1471 path_msg(opt, path, 0,
1472 _("Failed to merge submodule %s, but multiple "
1473 "possible merges exist:\n%s"), path, sb.buf);
1474 strbuf_release(&sb);
1475 }
1476
1477 object_array_clear(&merges);
1478 return 0;
62fdec17
EN
1479}
1480
1218b3ab
EN
1481static void initialize_attr_index(struct merge_options *opt)
1482{
1483 /*
1484 * The renormalize_buffer() functions require attributes, and
1485 * annoyingly those can only be read from the working tree or from
1486 * an index_state. merge-ort doesn't have an index_state, so we
1487 * generate a fake one containing only attribute information.
1488 */
1489 struct merged_info *mi;
1490 struct index_state *attr_index = &opt->priv->attr_index;
1491 struct cache_entry *ce;
1492
1493 attr_index->initialized = 1;
1494
1495 if (!opt->renormalize)
1496 return;
1497
1498 mi = strmap_get(&opt->priv->paths, GITATTRIBUTES_FILE);
1499 if (!mi)
1500 return;
1501
1502 if (mi->clean) {
1503 int len = strlen(GITATTRIBUTES_FILE);
1504 ce = make_empty_cache_entry(attr_index, len);
1505 ce->ce_mode = create_ce_mode(mi->result.mode);
1506 ce->ce_flags = create_ce_flags(0);
1507 ce->ce_namelen = len;
1508 oidcpy(&ce->oid, &mi->result.oid);
1509 memcpy(ce->name, GITATTRIBUTES_FILE, len);
1510 add_index_entry(attr_index, ce,
1511 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
1512 get_stream_filter(attr_index, GITATTRIBUTES_FILE, &ce->oid);
1513 } else {
1514 int stage, len;
1515 struct conflict_info *ci;
1516
1517 ASSIGN_AND_VERIFY_CI(ci, mi);
1518 for (stage = 0; stage < 3; stage++) {
1519 unsigned stage_mask = (1 << stage);
1520
1521 if (!(ci->filemask & stage_mask))
1522 continue;
1523 len = strlen(GITATTRIBUTES_FILE);
1524 ce = make_empty_cache_entry(attr_index, len);
1525 ce->ce_mode = create_ce_mode(ci->stages[stage].mode);
1526 ce->ce_flags = create_ce_flags(stage);
1527 ce->ce_namelen = len;
1528 oidcpy(&ce->oid, &ci->stages[stage].oid);
1529 memcpy(ce->name, GITATTRIBUTES_FILE, len);
1530 add_index_entry(attr_index, ce,
1531 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
1532 get_stream_filter(attr_index, GITATTRIBUTES_FILE,
1533 &ce->oid);
1534 }
1535 }
1536}
1537
62fdec17
EN
1538static int merge_3way(struct merge_options *opt,
1539 const char *path,
1540 const struct object_id *o,
1541 const struct object_id *a,
1542 const struct object_id *b,
1543 const char *pathnames[3],
1544 const int extra_marker_size,
1545 mmbuffer_t *result_buf)
1546{
f591c472
EN
1547 mmfile_t orig, src1, src2;
1548 struct ll_merge_options ll_opts = {0};
1549 char *base, *name1, *name2;
1550 int merge_status;
1551
1218b3ab
EN
1552 if (!opt->priv->attr_index.initialized)
1553 initialize_attr_index(opt);
1554
f591c472
EN
1555 ll_opts.renormalize = opt->renormalize;
1556 ll_opts.extra_marker_size = extra_marker_size;
1557 ll_opts.xdl_opts = opt->xdl_opts;
1558
1559 if (opt->priv->call_depth) {
1560 ll_opts.virtual_ancestor = 1;
1561 ll_opts.variant = 0;
1562 } else {
1563 switch (opt->recursive_variant) {
1564 case MERGE_VARIANT_OURS:
1565 ll_opts.variant = XDL_MERGE_FAVOR_OURS;
1566 break;
1567 case MERGE_VARIANT_THEIRS:
1568 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
1569 break;
1570 default:
1571 ll_opts.variant = 0;
1572 break;
1573 }
1574 }
1575
1576 assert(pathnames[0] && pathnames[1] && pathnames[2] && opt->ancestor);
1577 if (pathnames[0] == pathnames[1] && pathnames[1] == pathnames[2]) {
1578 base = mkpathdup("%s", opt->ancestor);
1579 name1 = mkpathdup("%s", opt->branch1);
1580 name2 = mkpathdup("%s", opt->branch2);
1581 } else {
1582 base = mkpathdup("%s:%s", opt->ancestor, pathnames[0]);
1583 name1 = mkpathdup("%s:%s", opt->branch1, pathnames[1]);
1584 name2 = mkpathdup("%s:%s", opt->branch2, pathnames[2]);
1585 }
1586
1587 read_mmblob(&orig, o);
1588 read_mmblob(&src1, a);
1589 read_mmblob(&src2, b);
1590
1591 merge_status = ll_merge(result_buf, path, &orig, base,
1592 &src1, name1, &src2, name2,
1218b3ab 1593 &opt->priv->attr_index, &ll_opts);
f591c472
EN
1594
1595 free(base);
1596 free(name1);
1597 free(name2);
1598 free(orig.ptr);
1599 free(src1.ptr);
1600 free(src2.ptr);
1601 return merge_status;
62fdec17
EN
1602}
1603
e2e9dc03
EN
1604static int handle_content_merge(struct merge_options *opt,
1605 const char *path,
1606 const struct version_info *o,
1607 const struct version_info *a,
1608 const struct version_info *b,
1609 const char *pathnames[3],
1610 const int extra_marker_size,
1611 struct version_info *result)
1612{
991bbdca 1613 /*
62fdec17
EN
1614 * path is the target location where we want to put the file, and
1615 * is used to determine any normalization rules in ll_merge.
1616 *
1617 * The normal case is that path and all entries in pathnames are
1618 * identical, though renames can affect which path we got one of
1619 * the three blobs to merge on various sides of history.
1620 *
1621 * extra_marker_size is the amount to extend conflict markers in
1622 * ll_merge; this is neeed if we have content merges of content
1623 * merges, which happens for example with rename/rename(2to1) and
1624 * rename/add conflicts.
1625 */
1626 unsigned clean = 1;
1627
1628 /*
1629 * handle_content_merge() needs both files to be of the same type, i.e.
1630 * both files OR both submodules OR both symlinks. Conflicting types
1631 * needs to be handled elsewhere.
991bbdca 1632 */
62fdec17
EN
1633 assert((S_IFMT & a->mode) == (S_IFMT & b->mode));
1634
1635 /* Merge modes */
1636 if (a->mode == b->mode || a->mode == o->mode)
1637 result->mode = b->mode;
1638 else {
1639 /* must be the 100644/100755 case */
1640 assert(S_ISREG(a->mode));
1641 result->mode = a->mode;
1642 clean = (b->mode == o->mode);
1643 /*
1644 * FIXME: If opt->priv->call_depth && !clean, then we really
1645 * should not make result->mode match either a->mode or
1646 * b->mode; that causes t6036 "check conflicting mode for
1647 * regular file" to fail. It would be best to use some other
1648 * mode, but we'll confuse all kinds of stuff if we use one
1649 * where S_ISREG(result->mode) isn't true, and if we use
1650 * something like 0100666, then tree-walk.c's calls to
1651 * canon_mode() will just normalize that to 100644 for us and
1652 * thus not solve anything.
1653 *
1654 * Figure out if there's some kind of way we can work around
1655 * this...
1656 */
1657 }
1658
1659 /*
1660 * Trivial oid merge.
1661 *
1662 * Note: While one might assume that the next four lines would
1663 * be unnecessary due to the fact that match_mask is often
1664 * setup and already handled, renames don't always take care
1665 * of that.
1666 */
1667 if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
1668 oidcpy(&result->oid, &b->oid);
1669 else if (oideq(&b->oid, &o->oid))
1670 oidcpy(&result->oid, &a->oid);
1671
1672 /* Remaining rules depend on file vs. submodule vs. symlink. */
1673 else if (S_ISREG(a->mode)) {
1674 mmbuffer_t result_buf;
1675 int ret = 0, merge_status;
1676 int two_way;
1677
1678 /*
1679 * If 'o' is different type, treat it as null so we do a
1680 * two-way merge.
1681 */
1682 two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
1683
1684 merge_status = merge_3way(opt, path,
14228447 1685 two_way ? null_oid() : &o->oid,
62fdec17
EN
1686 &a->oid, &b->oid,
1687 pathnames, extra_marker_size,
1688 &result_buf);
1689
1690 if ((merge_status < 0) || !result_buf.ptr)
1691 ret = err(opt, _("Failed to execute internal merge"));
1692
1693 if (!ret &&
1694 write_object_file(result_buf.ptr, result_buf.size,
1695 blob_type, &result->oid))
1696 ret = err(opt, _("Unable to add %s to database"),
1697 path);
1698
1699 free(result_buf.ptr);
1700 if (ret)
1701 return -1;
1702 clean &= (merge_status == 0);
1703 path_msg(opt, path, 1, _("Auto-merging %s"), path);
1704 } else if (S_ISGITLINK(a->mode)) {
1705 int two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
1706 clean = merge_submodule(opt, pathnames[0],
14228447 1707 two_way ? null_oid() : &o->oid,
62fdec17
EN
1708 &a->oid, &b->oid, &result->oid);
1709 if (opt->priv->call_depth && two_way && !clean) {
1710 result->mode = o->mode;
1711 oidcpy(&result->oid, &o->oid);
1712 }
1713 } else if (S_ISLNK(a->mode)) {
1714 if (opt->priv->call_depth) {
1715 clean = 0;
1716 result->mode = o->mode;
1717 oidcpy(&result->oid, &o->oid);
1718 } else {
1719 switch (opt->recursive_variant) {
1720 case MERGE_VARIANT_NORMAL:
1721 clean = 0;
1722 oidcpy(&result->oid, &a->oid);
1723 break;
1724 case MERGE_VARIANT_OURS:
1725 oidcpy(&result->oid, &a->oid);
1726 break;
1727 case MERGE_VARIANT_THEIRS:
1728 oidcpy(&result->oid, &b->oid);
1729 break;
1730 }
1731 }
1732 } else
1733 BUG("unsupported object type in the tree: %06o for %s",
1734 a->mode, path);
1735
991bbdca 1736 return clean;
e2e9dc03
EN
1737}
1738
04af1879
EN
1739/*** Function Grouping: functions related to detect_and_process_renames(), ***
1740 *** which are split into directory and regular rename detection sections. ***/
1741
1742/*** Function Grouping: functions related to directory rename detection ***/
1743
fa5e06d6
EN
1744struct collision_info {
1745 struct string_list source_files;
1746 unsigned reported_already:1;
1747};
1748
d9d015df
EN
1749/*
1750 * Return a new string that replaces the beginning portion (which matches
1751 * rename_info->key), with rename_info->util.new_dir. In perl-speak:
1752 * new_path_name = (old_path =~ s/rename_info->key/rename_info->value/);
1753 * NOTE:
1754 * Caller must ensure that old_path starts with rename_info->key + '/'.
1755 */
1756static char *apply_dir_rename(struct strmap_entry *rename_info,
1757 const char *old_path)
1758{
fbcfc0cc
EN
1759 struct strbuf new_path = STRBUF_INIT;
1760 const char *old_dir = rename_info->key;
1761 const char *new_dir = rename_info->value;
1762 int oldlen, newlen, new_dir_len;
1763
1764 oldlen = strlen(old_dir);
1765 if (*new_dir == '\0')
1766 /*
1767 * If someone renamed/merged a subdirectory into the root
1768 * directory (e.g. 'some/subdir' -> ''), then we want to
1769 * avoid returning
1770 * '' + '/filename'
1771 * as the rename; we need to make old_path + oldlen advance
1772 * past the '/' character.
1773 */
1774 oldlen++;
1775 new_dir_len = strlen(new_dir);
1776 newlen = new_dir_len + (strlen(old_path) - oldlen) + 1;
1777 strbuf_grow(&new_path, newlen);
1778 strbuf_add(&new_path, new_dir, new_dir_len);
1779 strbuf_addstr(&new_path, &old_path[oldlen]);
1780
1781 return strbuf_detach(&new_path, NULL);
d9d015df
EN
1782}
1783
bea43365
EN
1784static int path_in_way(struct strmap *paths, const char *path, unsigned side_mask)
1785{
1786 struct merged_info *mi = strmap_get(paths, path);
1787 struct conflict_info *ci;
1788 if (!mi)
1789 return 0;
1790 INITIALIZE_CI(ci, mi);
1791 return mi->clean || (side_mask & (ci->filemask | ci->dirmask));
1792}
1793
47325e85
EN
1794/*
1795 * See if there is a directory rename for path, and if there are any file
1796 * level conflicts on the given side for the renamed location. If there is
1797 * a rename and there are no conflicts, return the new name. Otherwise,
1798 * return NULL.
1799 */
1800static char *handle_path_level_conflicts(struct merge_options *opt,
1801 const char *path,
1802 unsigned side_index,
1803 struct strmap_entry *rename_info,
1804 struct strmap *collisions)
1805{
bea43365
EN
1806 char *new_path = NULL;
1807 struct collision_info *c_info;
1808 int clean = 1;
1809 struct strbuf collision_paths = STRBUF_INIT;
1810
1811 /*
1812 * entry has the mapping of old directory name to new directory name
1813 * that we want to apply to path.
1814 */
1815 new_path = apply_dir_rename(rename_info, path);
1816 if (!new_path)
1817 BUG("Failed to apply directory rename!");
1818
1819 /*
1820 * The caller needs to have ensured that it has pre-populated
1821 * collisions with all paths that map to new_path. Do a quick check
1822 * to ensure that's the case.
1823 */
1824 c_info = strmap_get(collisions, new_path);
1825 if (c_info == NULL)
1826 BUG("c_info is NULL");
1827
1828 /*
1829 * Check for one-sided add/add/.../add conflicts, i.e.
1830 * where implicit renames from the other side doing
1831 * directory rename(s) can affect this side of history
1832 * to put multiple paths into the same location. Warn
1833 * and bail on directory renames for such paths.
1834 */
1835 if (c_info->reported_already) {
1836 clean = 0;
1837 } else if (path_in_way(&opt->priv->paths, new_path, 1 << side_index)) {
1838 c_info->reported_already = 1;
1839 strbuf_add_separated_string_list(&collision_paths, ", ",
1840 &c_info->source_files);
1841 path_msg(opt, new_path, 0,
1842 _("CONFLICT (implicit dir rename): Existing file/dir "
1843 "at %s in the way of implicit directory rename(s) "
1844 "putting the following path(s) there: %s."),
1845 new_path, collision_paths.buf);
1846 clean = 0;
1847 } else if (c_info->source_files.nr > 1) {
1848 c_info->reported_already = 1;
1849 strbuf_add_separated_string_list(&collision_paths, ", ",
1850 &c_info->source_files);
1851 path_msg(opt, new_path, 0,
1852 _("CONFLICT (implicit dir rename): Cannot map more "
1853 "than one path to %s; implicit directory renames "
1854 "tried to put these paths there: %s"),
1855 new_path, collision_paths.buf);
1856 clean = 0;
1857 }
1858
1859 /* Free memory we no longer need */
1860 strbuf_release(&collision_paths);
1861 if (!clean && new_path) {
1862 free(new_path);
1863 return NULL;
1864 }
1865
1866 return new_path;
47325e85
EN
1867}
1868
112e1112
EN
1869static void get_provisional_directory_renames(struct merge_options *opt,
1870 unsigned side,
1871 int *clean)
1872{
04264d40
EN
1873 struct hashmap_iter iter;
1874 struct strmap_entry *entry;
1875 struct rename_info *renames = &opt->priv->renames;
1876
04264d40
EN
1877 /*
1878 * Collapse
1879 * dir_rename_count: old_directory -> {new_directory -> count}
1880 * down to
1881 * dir_renames: old_directory -> best_new_directory
1882 * where best_new_directory is the one with the unique highest count.
1883 */
1884 strmap_for_each_entry(&renames->dir_rename_count[side], &iter, entry) {
1885 const char *source_dir = entry->key;
1886 struct strintmap *counts = entry->value;
1887 struct hashmap_iter count_iter;
1888 struct strmap_entry *count_entry;
1889 int max = 0;
1890 int bad_max = 0;
1891 const char *best = NULL;
1892
1893 strintmap_for_each_entry(counts, &count_iter, count_entry) {
1894 const char *target_dir = count_entry->key;
1895 intptr_t count = (intptr_t)count_entry->value;
1896
1897 if (count == max)
1898 bad_max = max;
1899 else if (count > max) {
1900 max = count;
1901 best = target_dir;
1902 }
1903 }
1904
bf238b71
EN
1905 if (max == 0)
1906 continue;
1907
04264d40
EN
1908 if (bad_max == max) {
1909 path_msg(opt, source_dir, 0,
1910 _("CONFLICT (directory rename split): "
1911 "Unclear where to rename %s to; it was "
1912 "renamed to multiple other directories, with "
1913 "no destination getting a majority of the "
1914 "files."),
1915 source_dir);
41376b58 1916 *clean = 0;
04264d40
EN
1917 } else {
1918 strmap_put(&renames->dir_renames[side],
1919 source_dir, (void*)best);
1920 }
1921 }
112e1112
EN
1922}
1923
1924static void handle_directory_level_conflicts(struct merge_options *opt)
1925{
98d0d081
EN
1926 struct hashmap_iter iter;
1927 struct strmap_entry *entry;
1928 struct string_list duplicated = STRING_LIST_INIT_NODUP;
1929 struct rename_info *renames = &opt->priv->renames;
1930 struct strmap *side1_dir_renames = &renames->dir_renames[MERGE_SIDE1];
1931 struct strmap *side2_dir_renames = &renames->dir_renames[MERGE_SIDE2];
1932 int i;
1933
1934 strmap_for_each_entry(side1_dir_renames, &iter, entry) {
1935 if (strmap_contains(side2_dir_renames, entry->key))
1936 string_list_append(&duplicated, entry->key);
1937 }
1938
1939 for (i = 0; i < duplicated.nr; i++) {
1940 strmap_remove(side1_dir_renames, duplicated.items[i].string, 0);
1941 strmap_remove(side2_dir_renames, duplicated.items[i].string, 0);
1942 }
1943 string_list_clear(&duplicated, 0);
112e1112
EN
1944}
1945
d9d015df
EN
1946static struct strmap_entry *check_dir_renamed(const char *path,
1947 struct strmap *dir_renames)
1948{
fbcfc0cc
EN
1949 char *temp = xstrdup(path);
1950 char *end;
1951 struct strmap_entry *e = NULL;
1952
1953 while ((end = strrchr(temp, '/'))) {
1954 *end = '\0';
1955 e = strmap_get_entry(dir_renames, temp);
1956 if (e)
1957 break;
1958 }
1959 free(temp);
1960 return e;
d9d015df
EN
1961}
1962
fa5e06d6
EN
1963static void compute_collisions(struct strmap *collisions,
1964 struct strmap *dir_renames,
1965 struct diff_queue_struct *pairs)
1966{
d9d015df
EN
1967 int i;
1968
1969 strmap_init_with_options(collisions, NULL, 0);
1970 if (strmap_empty(dir_renames))
1971 return;
1972
1973 /*
1974 * Multiple files can be mapped to the same path due to directory
1975 * renames done by the other side of history. Since that other
1976 * side of history could have merged multiple directories into one,
1977 * if our side of history added the same file basename to each of
1978 * those directories, then all N of them would get implicitly
1979 * renamed by the directory rename detection into the same path,
1980 * and we'd get an add/add/.../add conflict, and all those adds
1981 * from *this* side of history. This is not representable in the
1982 * index, and users aren't going to easily be able to make sense of
1983 * it. So we need to provide a good warning about what's
1984 * happening, and fall back to no-directory-rename detection
1985 * behavior for those paths.
1986 *
1987 * See testcases 9e and all of section 5 from t6043 for examples.
1988 */
1989 for (i = 0; i < pairs->nr; ++i) {
1990 struct strmap_entry *rename_info;
1991 struct collision_info *collision_info;
1992 char *new_path;
1993 struct diff_filepair *pair = pairs->queue[i];
1994
1995 if (pair->status != 'A' && pair->status != 'R')
1996 continue;
1997 rename_info = check_dir_renamed(pair->two->path, dir_renames);
1998 if (!rename_info)
1999 continue;
2000
2001 new_path = apply_dir_rename(rename_info, pair->two->path);
2002 assert(new_path);
2003 collision_info = strmap_get(collisions, new_path);
2004 if (collision_info) {
2005 free(new_path);
2006 } else {
ca56dadb 2007 CALLOC_ARRAY(collision_info, 1);
bc40dfb1 2008 string_list_init_nodup(&collision_info->source_files);
d9d015df
EN
2009 strmap_put(collisions, new_path, collision_info);
2010 }
2011 string_list_insert(&collision_info->source_files,
2012 pair->two->path);
2013 }
fa5e06d6
EN
2014}
2015
2016static char *check_for_directory_rename(struct merge_options *opt,
2017 const char *path,
2018 unsigned side_index,
2019 struct strmap *dir_renames,
2020 struct strmap *dir_rename_exclusions,
2021 struct strmap *collisions,
2022 int *clean_merge)
2023{
47325e85
EN
2024 char *new_path = NULL;
2025 struct strmap_entry *rename_info;
2026 struct strmap_entry *otherinfo = NULL;
2027 const char *new_dir;
2028
2029 if (strmap_empty(dir_renames))
2030 return new_path;
2031 rename_info = check_dir_renamed(path, dir_renames);
2032 if (!rename_info)
2033 return new_path;
2034 /* old_dir = rename_info->key; */
2035 new_dir = rename_info->value;
2036
2037 /*
2038 * This next part is a little weird. We do not want to do an
2039 * implicit rename into a directory we renamed on our side, because
2040 * that will result in a spurious rename/rename(1to2) conflict. An
2041 * example:
2042 * Base commit: dumbdir/afile, otherdir/bfile
2043 * Side 1: smrtdir/afile, otherdir/bfile
2044 * Side 2: dumbdir/afile, dumbdir/bfile
2045 * Here, while working on Side 1, we could notice that otherdir was
2046 * renamed/merged to dumbdir, and change the diff_filepair for
2047 * otherdir/bfile into a rename into dumbdir/bfile. However, Side
2048 * 2 will notice the rename from dumbdir to smrtdir, and do the
2049 * transitive rename to move it from dumbdir/bfile to
2050 * smrtdir/bfile. That gives us bfile in dumbdir vs being in
2051 * smrtdir, a rename/rename(1to2) conflict. We really just want
2052 * the file to end up in smrtdir. And the way to achieve that is
2053 * to not let Side1 do the rename to dumbdir, since we know that is
2054 * the source of one of our directory renames.
2055 *
2056 * That's why otherinfo and dir_rename_exclusions is here.
2057 *
2058 * As it turns out, this also prevents N-way transient rename
2059 * confusion; See testcases 9c and 9d of t6043.
2060 */
2061 otherinfo = strmap_get_entry(dir_rename_exclusions, new_dir);
2062 if (otherinfo) {
2063 path_msg(opt, rename_info->key, 1,
2064 _("WARNING: Avoiding applying %s -> %s rename "
2065 "to %s, because %s itself was renamed."),
2066 rename_info->key, new_dir, path, new_dir);
2067 return NULL;
2068 }
2069
2070 new_path = handle_path_level_conflicts(opt, path, side_index,
2071 rename_info, collisions);
2072 *clean_merge &= (new_path != NULL);
2073
2074 return new_path;
fa5e06d6
EN
2075}
2076
2077static void apply_directory_rename_modifications(struct merge_options *opt,
2078 struct diff_filepair *pair,
2079 char *new_path)
2080{
089d82bc
EN
2081 /*
2082 * The basic idea is to get the conflict_info from opt->priv->paths
2083 * at old path, and insert it into new_path; basically just this:
2084 * ci = strmap_get(&opt->priv->paths, old_path);
2085 * strmap_remove(&opt->priv->paths, old_path, 0);
2086 * strmap_put(&opt->priv->paths, new_path, ci);
2087 * However, there are some factors complicating this:
2088 * - opt->priv->paths may already have an entry at new_path
2089 * - Each ci tracks its containing directory, so we need to
2090 * update that
2091 * - If another ci has the same containing directory, then
2092 * the two char*'s MUST point to the same location. See the
2093 * comment in struct merged_info. strcmp equality is not
2094 * enough; we need pointer equality.
2095 * - opt->priv->paths must hold the parent directories of any
2096 * entries that are added. So, if this directory rename
2097 * causes entirely new directories, we must recursively add
2098 * parent directories.
2099 * - For each parent directory added to opt->priv->paths, we
2100 * also need to get its parent directory stored in its
2101 * conflict_info->merged.directory_name with all the same
2102 * requirements about pointer equality.
2103 */
2104 struct string_list dirs_to_insert = STRING_LIST_INIT_NODUP;
2105 struct conflict_info *ci, *new_ci;
2106 struct strmap_entry *entry;
2107 const char *branch_with_new_path, *branch_with_dir_rename;
2108 const char *old_path = pair->two->path;
2109 const char *parent_name;
2110 const char *cur_path;
2111 int i, len;
2112
2113 entry = strmap_get_entry(&opt->priv->paths, old_path);
2114 old_path = entry->key;
2115 ci = entry->value;
2116 VERIFY_CI(ci);
2117
2118 /* Find parent directories missing from opt->priv->paths */
2119 cur_path = new_path;
2120 while (1) {
2121 /* Find the parent directory of cur_path */
2122 char *last_slash = strrchr(cur_path, '/');
2123 if (last_slash) {
2124 parent_name = xstrndup(cur_path, last_slash - cur_path);
2125 } else {
2126 parent_name = opt->priv->toplevel_dir;
2127 break;
2128 }
2129
2130 /* Look it up in opt->priv->paths */
2131 entry = strmap_get_entry(&opt->priv->paths, parent_name);
2132 if (entry) {
2133 free((char*)parent_name);
2134 parent_name = entry->key; /* reuse known pointer */
2135 break;
2136 }
2137
2138 /* Record this is one of the directories we need to insert */
2139 string_list_append(&dirs_to_insert, parent_name);
2140 cur_path = parent_name;
2141 }
2142
2143 /* Traverse dirs_to_insert and insert them into opt->priv->paths */
2144 for (i = dirs_to_insert.nr-1; i >= 0; --i) {
2145 struct conflict_info *dir_ci;
2146 char *cur_dir = dirs_to_insert.items[i].string;
2147
ca56dadb 2148 CALLOC_ARRAY(dir_ci, 1);
089d82bc
EN
2149
2150 dir_ci->merged.directory_name = parent_name;
2151 len = strlen(parent_name);
2152 /* len+1 because of trailing '/' character */
2153 dir_ci->merged.basename_offset = (len > 0 ? len+1 : len);
2154 dir_ci->dirmask = ci->filemask;
2155 strmap_put(&opt->priv->paths, cur_dir, dir_ci);
2156
2157 parent_name = cur_dir;
2158 }
2159
2160 /*
2161 * We are removing old_path from opt->priv->paths. old_path also will
2162 * eventually need to be freed, but it may still be used by e.g.
2163 * ci->pathnames. So, store it in another string-list for now.
2164 */
2165 string_list_append(&opt->priv->paths_to_free, old_path);
2166
2167 assert(ci->filemask == 2 || ci->filemask == 4);
2168 assert(ci->dirmask == 0);
2169 strmap_remove(&opt->priv->paths, old_path, 0);
2170
2171 branch_with_new_path = (ci->filemask == 2) ? opt->branch1 : opt->branch2;
2172 branch_with_dir_rename = (ci->filemask == 2) ? opt->branch2 : opt->branch1;
2173
2174 /* Now, finally update ci and stick it into opt->priv->paths */
2175 ci->merged.directory_name = parent_name;
2176 len = strlen(parent_name);
2177 ci->merged.basename_offset = (len > 0 ? len+1 : len);
2178 new_ci = strmap_get(&opt->priv->paths, new_path);
2179 if (!new_ci) {
2180 /* Place ci back into opt->priv->paths, but at new_path */
2181 strmap_put(&opt->priv->paths, new_path, ci);
2182 } else {
2183 int index;
2184
2185 /* A few sanity checks */
2186 VERIFY_CI(new_ci);
2187 assert(ci->filemask == 2 || ci->filemask == 4);
2188 assert((new_ci->filemask & ci->filemask) == 0);
2189 assert(!new_ci->merged.clean);
2190
2191 /* Copy stuff from ci into new_ci */
2192 new_ci->filemask |= ci->filemask;
2193 if (new_ci->dirmask)
2194 new_ci->df_conflict = 1;
2195 index = (ci->filemask >> 1);
2196 new_ci->pathnames[index] = ci->pathnames[index];
2197 new_ci->stages[index].mode = ci->stages[index].mode;
2198 oidcpy(&new_ci->stages[index].oid, &ci->stages[index].oid);
2199
2200 free(ci);
2201 ci = new_ci;
2202 }
2203
2204 if (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE) {
2205 /* Notify user of updated path */
2206 if (pair->status == 'A')
2207 path_msg(opt, new_path, 1,
2208 _("Path updated: %s added in %s inside a "
2209 "directory that was renamed in %s; moving "
2210 "it to %s."),
2211 old_path, branch_with_new_path,
2212 branch_with_dir_rename, new_path);
2213 else
2214 path_msg(opt, new_path, 1,
2215 _("Path updated: %s renamed to %s in %s, "
2216 "inside a directory that was renamed in %s; "
2217 "moving it to %s."),
2218 pair->one->path, old_path, branch_with_new_path,
2219 branch_with_dir_rename, new_path);
2220 } else {
2221 /*
2222 * opt->detect_directory_renames has the value
2223 * MERGE_DIRECTORY_RENAMES_CONFLICT, so mark these as conflicts.
2224 */
2225 ci->path_conflict = 1;
2226 if (pair->status == 'A')
2227 path_msg(opt, new_path, 0,
2228 _("CONFLICT (file location): %s added in %s "
2229 "inside a directory that was renamed in %s, "
2230 "suggesting it should perhaps be moved to "
2231 "%s."),
2232 old_path, branch_with_new_path,
2233 branch_with_dir_rename, new_path);
2234 else
2235 path_msg(opt, new_path, 0,
2236 _("CONFLICT (file location): %s renamed to %s "
2237 "in %s, inside a directory that was renamed "
2238 "in %s, suggesting it should perhaps be "
2239 "moved to %s."),
2240 pair->one->path, old_path, branch_with_new_path,
2241 branch_with_dir_rename, new_path);
2242 }
2243
2244 /*
2245 * Finally, record the new location.
2246 */
2247 pair->two->path = new_path;
fa5e06d6
EN
2248}
2249
04af1879
EN
2250/*** Function Grouping: functions related to regular rename detection ***/
2251
e1a124e8
EN
2252static int process_renames(struct merge_options *opt,
2253 struct diff_queue_struct *renames)
2254{
c2d267df
EN
2255 int clean_merge = 1, i;
2256
2257 for (i = 0; i < renames->nr; ++i) {
2258 const char *oldpath = NULL, *newpath;
2259 struct diff_filepair *pair = renames->queue[i];
2260 struct conflict_info *oldinfo = NULL, *newinfo = NULL;
2261 struct strmap_entry *old_ent, *new_ent;
2262 unsigned int old_sidemask;
2263 int target_index, other_source_index;
2264 int source_deleted, collision, type_changed;
2e91ddd2 2265 const char *rename_branch = NULL, *delete_branch = NULL;
c2d267df
EN
2266
2267 old_ent = strmap_get_entry(&opt->priv->paths, pair->one->path);
c2d267df 2268 new_ent = strmap_get_entry(&opt->priv->paths, pair->two->path);
1b6b902d
EN
2269 if (old_ent) {
2270 oldpath = old_ent->key;
2271 oldinfo = old_ent->value;
2272 }
2273 newpath = pair->two->path;
2274 if (new_ent) {
2275 newpath = new_ent->key;
2276 newinfo = new_ent->value;
2277 }
2278
2279 /*
2280 * If pair->one->path isn't in opt->priv->paths, that means
2281 * that either directory rename detection removed that
2282 * path, or a parent directory of oldpath was resolved and
2283 * we don't even need the rename; in either case, we can
2284 * skip it. If oldinfo->merged.clean, then the other side
2285 * of history had no changes to oldpath and we don't need
2286 * the rename and can skip it.
2287 */
2288 if (!oldinfo || oldinfo->merged.clean)
2289 continue;
c2d267df
EN
2290
2291 /*
2292 * diff_filepairs have copies of pathnames, thus we have to
2293 * use standard 'strcmp()' (negated) instead of '=='.
2294 */
2295 if (i + 1 < renames->nr &&
2296 !strcmp(oldpath, renames->queue[i+1]->one->path)) {
2297 /* Handle rename/rename(1to2) or rename/rename(1to1) */
2298 const char *pathnames[3];
af1e56c4
EN
2299 struct version_info merged;
2300 struct conflict_info *base, *side1, *side2;
53e88a03 2301 unsigned was_binary_blob = 0;
c2d267df
EN
2302
2303 pathnames[0] = oldpath;
2304 pathnames[1] = newpath;
2305 pathnames[2] = renames->queue[i+1]->two->path;
2306
af1e56c4
EN
2307 base = strmap_get(&opt->priv->paths, pathnames[0]);
2308 side1 = strmap_get(&opt->priv->paths, pathnames[1]);
2309 side2 = strmap_get(&opt->priv->paths, pathnames[2]);
2310
2311 VERIFY_CI(base);
2312 VERIFY_CI(side1);
2313 VERIFY_CI(side2);
2314
c2d267df 2315 if (!strcmp(pathnames[1], pathnames[2])) {
cbdca289
EN
2316 struct rename_info *ri = &opt->priv->renames;
2317 int j;
2318
af1e56c4
EN
2319 /* Both sides renamed the same way */
2320 assert(side1 == side2);
2321 memcpy(&side1->stages[0], &base->stages[0],
2322 sizeof(merged));
2323 side1->filemask |= (1 << MERGE_BASE);
2324 /* Mark base as resolved by removal */
2325 base->merged.is_null = 1;
2326 base->merged.clean = 1;
c2d267df 2327
cbdca289
EN
2328 /*
2329 * Disable remembering renames optimization;
2330 * rename/rename(1to1) is incredibly rare, and
2331 * just disabling the optimization is easier
2332 * than purging cached_pairs,
2333 * cached_target_names, and dir_rename_counts.
2334 */
2335 for (j = 0; j < 3; j++)
2336 ri->merge_trees[j] = NULL;
2337
c2d267df
EN
2338 /* We handled both renames, i.e. i+1 handled */
2339 i++;
2340 /* Move to next rename */
2341 continue;
2342 }
2343
2344 /* This is a rename/rename(1to2) */
53e88a03
EN
2345 clean_merge = handle_content_merge(opt,
2346 pair->one->path,
2347 &base->stages[0],
2348 &side1->stages[1],
2349 &side2->stages[2],
2350 pathnames,
2351 1 + 2 * opt->priv->call_depth,
2352 &merged);
2353 if (!clean_merge &&
2354 merged.mode == side1->stages[1].mode &&
2355 oideq(&merged.oid, &side1->stages[1].oid))
2356 was_binary_blob = 1;
2357 memcpy(&side1->stages[1], &merged, sizeof(merged));
2358 if (was_binary_blob) {
2359 /*
2360 * Getting here means we were attempting to
2361 * merge a binary blob.
2362 *
2363 * Since we can't merge binaries,
2364 * handle_content_merge() just takes one
2365 * side. But we don't want to copy the
2366 * contents of one side to both paths. We
2367 * used the contents of side1 above for
2368 * side1->stages, let's use the contents of
2369 * side2 for side2->stages below.
2370 */
2371 oidcpy(&merged.oid, &side2->stages[2].oid);
2372 merged.mode = side2->stages[2].mode;
2373 }
2374 memcpy(&side2->stages[2], &merged, sizeof(merged));
2375
2376 side1->path_conflict = 1;
2377 side2->path_conflict = 1;
2378 /*
2379 * TODO: For renames we normally remove the path at the
2380 * old name. It would thus seem consistent to do the
2381 * same for rename/rename(1to2) cases, but we haven't
2382 * done so traditionally and a number of the regression
2383 * tests now encode an expectation that the file is
2384 * left there at stage 1. If we ever decide to change
2385 * this, add the following two lines here:
2386 * base->merged.is_null = 1;
2387 * base->merged.clean = 1;
2388 * and remove the setting of base->path_conflict to 1.
2389 */
2390 base->path_conflict = 1;
2391 path_msg(opt, oldpath, 0,
2392 _("CONFLICT (rename/rename): %s renamed to "
2393 "%s in %s and to %s in %s."),
2394 pathnames[0],
2395 pathnames[1], opt->branch1,
2396 pathnames[2], opt->branch2);
c2d267df
EN
2397
2398 i++; /* We handled both renames, i.e. i+1 handled */
2399 continue;
2400 }
2401
2402 VERIFY_CI(oldinfo);
2403 VERIFY_CI(newinfo);
2404 target_index = pair->score; /* from collect_renames() */
2405 assert(target_index == 1 || target_index == 2);
2406 other_source_index = 3 - target_index;
2407 old_sidemask = (1 << other_source_index); /* 2 or 4 */
2408 source_deleted = (oldinfo->filemask == 1);
2409 collision = ((newinfo->filemask & old_sidemask) != 0);
2410 type_changed = !source_deleted &&
2411 (S_ISREG(oldinfo->stages[other_source_index].mode) !=
2412 S_ISREG(newinfo->stages[target_index].mode));
2413 if (type_changed && collision) {
6fcccbd7
EN
2414 /*
2415 * special handling so later blocks can handle this...
2416 *
2417 * if type_changed && collision are both true, then this
2418 * was really a double rename, but one side wasn't
2419 * detected due to lack of break detection. I.e.
2420 * something like
2421 * orig: has normal file 'foo'
2422 * side1: renames 'foo' to 'bar', adds 'foo' symlink
2423 * side2: renames 'foo' to 'bar'
2424 * In this case, the foo->bar rename on side1 won't be
2425 * detected because the new symlink named 'foo' is
2426 * there and we don't do break detection. But we detect
2427 * this here because we don't want to merge the content
2428 * of the foo symlink with the foo->bar file, so we
2429 * have some logic to handle this special case. The
2430 * easiest way to do that is make 'bar' on side1 not
2431 * be considered a colliding file but the other part
2432 * of a normal rename. If the file is very different,
2433 * well we're going to get content merge conflicts
2434 * anyway so it doesn't hurt. And if the colliding
2435 * file also has a different type, that'll be handled
2436 * by the content merge logic in process_entry() too.
2437 *
2438 * See also t6430, 'rename vs. rename/symlink'
2439 */
2440 collision = 0;
c2d267df 2441 }
2e91ddd2
EN
2442 if (source_deleted) {
2443 if (target_index == 1) {
2444 rename_branch = opt->branch1;
2445 delete_branch = opt->branch2;
2446 } else {
2447 rename_branch = opt->branch2;
2448 delete_branch = opt->branch1;
2449 }
2450 }
c2d267df
EN
2451
2452 assert(source_deleted || oldinfo->filemask & old_sidemask);
2453
2454 /* Need to check for special types of rename conflicts... */
2455 if (collision && !source_deleted) {
2456 /* collision: rename/add or rename/rename(2to1) */
35e47e35
EN
2457 const char *pathnames[3];
2458 struct version_info merged;
2459
2460 struct conflict_info *base, *side1, *side2;
2461 unsigned clean;
2462
2463 pathnames[0] = oldpath;
2464 pathnames[other_source_index] = oldpath;
2465 pathnames[target_index] = newpath;
2466
2467 base = strmap_get(&opt->priv->paths, pathnames[0]);
2468 side1 = strmap_get(&opt->priv->paths, pathnames[1]);
2469 side2 = strmap_get(&opt->priv->paths, pathnames[2]);
2470
2471 VERIFY_CI(base);
2472 VERIFY_CI(side1);
2473 VERIFY_CI(side2);
2474
2475 clean = handle_content_merge(opt, pair->one->path,
2476 &base->stages[0],
2477 &side1->stages[1],
2478 &side2->stages[2],
2479 pathnames,
2480 1 + 2 * opt->priv->call_depth,
2481 &merged);
2482
2483 memcpy(&newinfo->stages[target_index], &merged,
2484 sizeof(merged));
2485 if (!clean) {
2486 path_msg(opt, newpath, 0,
2487 _("CONFLICT (rename involved in "
2488 "collision): rename of %s -> %s has "
2489 "content conflicts AND collides "
2490 "with another path; this may result "
2491 "in nested conflict markers."),
2492 oldpath, newpath);
2493 }
c2d267df 2494 } else if (collision && source_deleted) {
35e47e35
EN
2495 /*
2496 * rename/add/delete or rename/rename(2to1)/delete:
2497 * since oldpath was deleted on the side that didn't
2498 * do the rename, there's not much of a content merge
2499 * we can do for the rename. oldinfo->merged.is_null
2500 * was already set, so we just leave things as-is so
2501 * they look like an add/add conflict.
2502 */
2503
2504 newinfo->path_conflict = 1;
2505 path_msg(opt, newpath, 0,
2506 _("CONFLICT (rename/delete): %s renamed "
2507 "to %s in %s, but deleted in %s."),
2508 oldpath, newpath, rename_branch, delete_branch);
c2d267df 2509 } else {
2e91ddd2
EN
2510 /*
2511 * a few different cases...start by copying the
2512 * existing stage(s) from oldinfo over the newinfo
2513 * and update the pathname(s).
2514 */
2515 memcpy(&newinfo->stages[0], &oldinfo->stages[0],
2516 sizeof(newinfo->stages[0]));
2517 newinfo->filemask |= (1 << MERGE_BASE);
2518 newinfo->pathnames[0] = oldpath;
c2d267df
EN
2519 if (type_changed) {
2520 /* rename vs. typechange */
6fcccbd7 2521 /* Mark the original as resolved by removal */
14228447 2522 memcpy(&oldinfo->stages[0].oid, null_oid(),
6fcccbd7
EN
2523 sizeof(oldinfo->stages[0].oid));
2524 oldinfo->stages[0].mode = 0;
2525 oldinfo->filemask &= 0x06;
c2d267df
EN
2526 } else if (source_deleted) {
2527 /* rename/delete */
2e91ddd2
EN
2528 newinfo->path_conflict = 1;
2529 path_msg(opt, newpath, 0,
2530 _("CONFLICT (rename/delete): %s renamed"
2531 " to %s in %s, but deleted in %s."),
2532 oldpath, newpath,
2533 rename_branch, delete_branch);
c2d267df
EN
2534 } else {
2535 /* normal rename */
f1665e69
EN
2536 memcpy(&newinfo->stages[other_source_index],
2537 &oldinfo->stages[other_source_index],
2538 sizeof(newinfo->stages[0]));
2539 newinfo->filemask |= (1 << other_source_index);
2540 newinfo->pathnames[other_source_index] = oldpath;
c2d267df
EN
2541 }
2542 }
2543
2544 if (!type_changed) {
2545 /* Mark the original as resolved by removal */
2546 oldinfo->merged.is_null = 1;
2547 oldinfo->merged.clean = 1;
2548 }
2549
2550 }
2551
2552 return clean_merge;
e1a124e8
EN
2553}
2554
f89b4f2b
EN
2555static inline int possible_side_renames(struct rename_info *renames,
2556 unsigned side_index)
2557{
2558 return renames->pairs[side_index].nr > 0 &&
a49b55d5 2559 !strintmap_empty(&renames->relevant_sources[side_index]);
f89b4f2b
EN
2560}
2561
2562static inline int possible_renames(struct rename_info *renames)
2563{
2564 return possible_side_renames(renames, 1) ||
25e65b6d
EN
2565 possible_side_renames(renames, 2) ||
2566 !strmap_empty(&renames->cached_pairs[1]) ||
2567 !strmap_empty(&renames->cached_pairs[2]);
f89b4f2b
EN
2568}
2569
f78cf976
EN
2570static void resolve_diffpair_statuses(struct diff_queue_struct *q)
2571{
2572 /*
2573 * A simplified version of diff_resolve_rename_copy(); would probably
2574 * just use that function but it's static...
2575 */
2576 int i;
2577 struct diff_filepair *p;
2578
2579 for (i = 0; i < q->nr; ++i) {
2580 p = q->queue[i];
2581 p->status = 0; /* undecided */
2582 if (!DIFF_FILE_VALID(p->one))
2583 p->status = DIFF_STATUS_ADDED;
2584 else if (!DIFF_FILE_VALID(p->two))
2585 p->status = DIFF_STATUS_DELETED;
2586 else if (DIFF_PAIR_RENAME(p))
2587 p->status = DIFF_STATUS_RENAMED;
2588 }
2589}
2590
86b41b38
EN
2591static void prune_cached_from_relevant(struct rename_info *renames,
2592 unsigned side)
2593{
2594 /* Reason for this function described in add_pair() */
2595 struct hashmap_iter iter;
2596 struct strmap_entry *entry;
2597
2598 /* Remove from relevant_sources all entries in cached_pairs[side] */
2599 strmap_for_each_entry(&renames->cached_pairs[side], &iter, entry) {
2600 strintmap_remove(&renames->relevant_sources[side],
2601 entry->key);
2602 }
2603 /* Remove from relevant_sources all entries in cached_irrelevant[side] */
2604 strset_for_each_entry(&renames->cached_irrelevant[side], &iter, entry) {
2605 strintmap_remove(&renames->relevant_sources[side],
2606 entry->key);
2607 }
2608}
2609
86b41b38
EN
2610static void use_cached_pairs(struct merge_options *opt,
2611 struct strmap *cached_pairs,
2612 struct diff_queue_struct *pairs)
2613{
2614 struct hashmap_iter iter;
2615 struct strmap_entry *entry;
2616
2617 /*
2618 * Add to side_pairs all entries from renames->cached_pairs[side_index].
2619 * (Info in cached_irrelevant[side_index] is not relevant here.)
2620 */
2621 strmap_for_each_entry(cached_pairs, &iter, entry) {
2622 struct diff_filespec *one, *two;
2623 const char *old_name = entry->key;
2624 const char *new_name = entry->value;
2625 if (!new_name)
2626 new_name = old_name;
2627
2628 /* We don't care about oid/mode, only filenames and status */
2629 one = alloc_filespec(old_name);
2630 two = alloc_filespec(new_name);
2631 diff_queue(pairs, one, two);
2632 pairs->queue[pairs->nr-1]->status = entry->value ? 'R' : 'D';
2633 }
2634}
2635
2734f2e3
EN
2636static void cache_new_pair(struct rename_info *renames,
2637 int side,
2638 char *old_path,
2639 char *new_path,
2640 int free_old_value)
2641{
2642 char *old_value;
2643 new_path = xstrdup(new_path);
2644 old_value = strmap_put(&renames->cached_pairs[side],
2645 old_path, new_path);
2646 strset_add(&renames->cached_target_names[side], new_path);
2647 if (free_old_value)
2648 free(old_value);
2649 else
2650 assert(!old_value);
2651}
2652
2653static void possibly_cache_new_pair(struct rename_info *renames,
2654 struct diff_filepair *p,
2655 unsigned side,
2656 char *new_path)
2657{
2658 int dir_renamed_side = 0;
2659
2660 if (new_path) {
2661 /*
2662 * Directory renames happen on the other side of history from
2663 * the side that adds new files to the old directory.
2664 */
2665 dir_renamed_side = 3 - side;
2666 } else {
2667 int val = strintmap_get(&renames->relevant_sources[side],
2668 p->one->path);
2669 if (val == RELEVANT_NO_MORE) {
2670 assert(p->status == 'D');
2671 strset_add(&renames->cached_irrelevant[side],
2672 p->one->path);
2673 }
2674 if (val <= 0)
2675 return;
2676 }
2677
2678 if (p->status == 'D') {
2679 /*
2680 * If we already had this delete, we'll just set it's value
2681 * to NULL again, so no harm.
2682 */
2683 strmap_put(&renames->cached_pairs[side], p->one->path, NULL);
2684 } else if (p->status == 'R') {
2685 if (!new_path)
2686 new_path = p->two->path;
2687 else
2688 cache_new_pair(renames, dir_renamed_side,
2689 p->two->path, new_path, 0);
2690 cache_new_pair(renames, side, p->one->path, new_path, 1);
2691 } else if (p->status == 'A' && new_path) {
2692 cache_new_pair(renames, dir_renamed_side,
2693 p->two->path, new_path, 0);
2694 }
2695}
2696
e1a124e8
EN
2697static int compare_pairs(const void *a_, const void *b_)
2698{
965a7bc2
EN
2699 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
2700 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
2701
2702 return strcmp(a->one->path, b->one->path);
e1a124e8
EN
2703}
2704
356da0f9 2705/* Call diffcore_rename() to update deleted/added pairs into rename pairs */
e1a124e8 2706static void detect_regular_renames(struct merge_options *opt,
e1a124e8
EN
2707 unsigned side_index)
2708{
f39d05ca
EN
2709 struct diff_options diff_opts;
2710 struct rename_info *renames = &opt->priv->renames;
2711
25e65b6d 2712 prune_cached_from_relevant(renames, side_index);
f89b4f2b
EN
2713 if (!possible_side_renames(renames, side_index)) {
2714 /*
2715 * No rename detection needed for this side, but we still need
2716 * to make sure 'adds' are marked correctly in case the other
2717 * side had directory renames.
2718 */
2719 resolve_diffpair_statuses(&renames->pairs[side_index]);
2720 return;
2721 }
2722
d5098029 2723 partial_clear_dir_rename_count(&renames->dir_rename_count[side_index]);
f39d05ca
EN
2724 repo_diff_setup(opt->repo, &diff_opts);
2725 diff_opts.flags.recursive = 1;
2726 diff_opts.flags.rename_empty = 0;
2727 diff_opts.detect_rename = DIFF_DETECT_RENAME;
2728 diff_opts.rename_limit = opt->rename_limit;
2729 if (opt->rename_limit <= 0)
2730 diff_opts.rename_limit = 1000;
2731 diff_opts.rename_score = opt->rename_score;
2732 diff_opts.show_rename_progress = opt->show_rename_progress;
2733 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2734 diff_setup_done(&diff_opts);
557ac035 2735
f78cf976 2736 diff_queued_diff = renames->pairs[side_index];
557ac035 2737 trace2_region_enter("diff", "diffcore_rename", opt->repo);
0c4fd732 2738 diffcore_rename_extended(&diff_opts,
174791f0 2739 &renames->relevant_sources[side_index],
0c4fd732 2740 &renames->dirs_removed[side_index],
25e65b6d
EN
2741 &renames->dir_rename_count[side_index],
2742 &renames->cached_pairs[side_index]);
557ac035 2743 trace2_region_leave("diff", "diffcore_rename", opt->repo);
f78cf976 2744 resolve_diffpair_statuses(&diff_queued_diff);
f39d05ca
EN
2745
2746 if (diff_opts.needed_rename_limit > renames->needed_limit)
2747 renames->needed_limit = diff_opts.needed_rename_limit;
2748
2749 renames->pairs[side_index] = diff_queued_diff;
2750
2751 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2752 diff_queued_diff.nr = 0;
2753 diff_queued_diff.queue = NULL;
2754 diff_flush(&diff_opts);
e1a124e8
EN
2755}
2756
2757/*
356da0f9
EN
2758 * Get information of all renames which occurred in 'side_pairs', making use
2759 * of any implicit directory renames in side_dir_renames (also making use of
2760 * implicit directory renames rename_exclusions as needed by
2761 * check_for_directory_rename()). Add all (updated) renames into result.
e1a124e8
EN
2762 */
2763static int collect_renames(struct merge_options *opt,
2764 struct diff_queue_struct *result,
fa5e06d6
EN
2765 unsigned side_index,
2766 struct strmap *dir_renames_for_side,
2767 struct strmap *rename_exclusions)
e1a124e8 2768{
965a7bc2 2769 int i, clean = 1;
fa5e06d6 2770 struct strmap collisions;
965a7bc2 2771 struct diff_queue_struct *side_pairs;
fa5e06d6
EN
2772 struct hashmap_iter iter;
2773 struct strmap_entry *entry;
965a7bc2
EN
2774 struct rename_info *renames = &opt->priv->renames;
2775
2776 side_pairs = &renames->pairs[side_index];
fa5e06d6 2777 compute_collisions(&collisions, dir_renames_for_side, side_pairs);
965a7bc2
EN
2778
2779 for (i = 0; i < side_pairs->nr; ++i) {
2780 struct diff_filepair *p = side_pairs->queue[i];
fa5e06d6 2781 char *new_path; /* non-NULL only with directory renames */
965a7bc2 2782
fa5e06d6 2783 if (p->status != 'A' && p->status != 'R') {
2734f2e3 2784 possibly_cache_new_pair(renames, p, side_index, NULL);
965a7bc2
EN
2785 diff_free_filepair(p);
2786 continue;
2787 }
2788
fa5e06d6
EN
2789 new_path = check_for_directory_rename(opt, p->two->path,
2790 side_index,
2791 dir_renames_for_side,
2792 rename_exclusions,
2793 &collisions,
2794 &clean);
2795
2734f2e3 2796 possibly_cache_new_pair(renames, p, side_index, new_path);
fa5e06d6
EN
2797 if (p->status != 'R' && !new_path) {
2798 diff_free_filepair(p);
2799 continue;
2800 }
2801
2802 if (new_path)
2803 apply_directory_rename_modifications(opt, p, new_path);
2804
965a7bc2
EN
2805 /*
2806 * p->score comes back from diffcore_rename_extended() with
2807 * the similarity of the renamed file. The similarity is
2808 * was used to determine that the two files were related
2809 * and are a rename, which we have already used, but beyond
2810 * that we have no use for the similarity. So p->score is
2811 * now irrelevant. However, process_renames() will need to
2812 * know which side of the merge this rename was associated
2813 * with, so overwrite p->score with that value.
2814 */
2815 p->score = side_index;
2816 result->queue[result->nr++] = p;
2817 }
2818
fa5e06d6
EN
2819 /* Free each value in the collisions map */
2820 strmap_for_each_entry(&collisions, &iter, entry) {
2821 struct collision_info *info = entry->value;
2822 string_list_clear(&info->source_files, 0);
2823 }
2824 /*
2825 * In compute_collisions(), we set collisions.strdup_strings to 0
2826 * so that we wouldn't have to make another copy of the new_path
2827 * allocated by apply_dir_rename(). But now that we've used them
2828 * and have no other references to these strings, it is time to
2829 * deallocate them.
2830 */
2831 free_strmap_strings(&collisions);
2832 strmap_clear(&collisions, 1);
965a7bc2 2833 return clean;
e1a124e8
EN
2834}
2835
231e2dd4
EN
2836static int detect_and_process_renames(struct merge_options *opt,
2837 struct tree *merge_base,
2838 struct tree *side1,
2839 struct tree *side2)
2840{
e1a124e8
EN
2841 struct diff_queue_struct combined;
2842 struct rename_info *renames = &opt->priv->renames;
112e1112 2843 int need_dir_renames, s, clean = 1;
e1a124e8
EN
2844
2845 memset(&combined, 0, sizeof(combined));
f89b4f2b
EN
2846 if (!possible_renames(renames))
2847 goto cleanup;
e1a124e8 2848
557ac035 2849 trace2_region_enter("merge", "regular renames", opt->repo);
f78cf976
EN
2850 detect_regular_renames(opt, MERGE_SIDE1);
2851 detect_regular_renames(opt, MERGE_SIDE2);
25e65b6d
EN
2852 use_cached_pairs(opt, &renames->cached_pairs[1], &renames->pairs[1]);
2853 use_cached_pairs(opt, &renames->cached_pairs[2], &renames->pairs[2]);
557ac035 2854 trace2_region_leave("merge", "regular renames", opt->repo);
e1a124e8 2855
557ac035 2856 trace2_region_enter("merge", "directory renames", opt->repo);
112e1112
EN
2857 need_dir_renames =
2858 !opt->priv->call_depth &&
2859 (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE ||
2860 opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT);
2861
2862 if (need_dir_renames) {
2863 get_provisional_directory_renames(opt, MERGE_SIDE1, &clean);
2864 get_provisional_directory_renames(opt, MERGE_SIDE2, &clean);
2865 handle_directory_level_conflicts(opt);
2866 }
2867
e1a124e8
EN
2868 ALLOC_GROW(combined.queue,
2869 renames->pairs[1].nr + renames->pairs[2].nr,
2870 combined.alloc);
fa5e06d6
EN
2871 clean &= collect_renames(opt, &combined, MERGE_SIDE1,
2872 &renames->dir_renames[2],
2873 &renames->dir_renames[1]);
2874 clean &= collect_renames(opt, &combined, MERGE_SIDE2,
2875 &renames->dir_renames[1],
2876 &renames->dir_renames[2]);
72b30910 2877 STABLE_QSORT(combined.queue, combined.nr, compare_pairs);
557ac035 2878 trace2_region_leave("merge", "directory renames", opt->repo);
e1a124e8 2879
557ac035 2880 trace2_region_enter("merge", "process renames", opt->repo);
e1a124e8 2881 clean &= process_renames(opt, &combined);
557ac035 2882 trace2_region_leave("merge", "process renames", opt->repo);
e1a124e8 2883
f89b4f2b
EN
2884 goto simple_cleanup; /* collect_renames() handles some of cleanup */
2885
2886cleanup:
2887 /*
2888 * Free now unneeded filepairs, which would have been handled
2889 * in collect_renames() normally but we skipped that code.
2890 */
2891 for (s = MERGE_SIDE1; s <= MERGE_SIDE2; s++) {
2892 struct diff_queue_struct *side_pairs;
2893 int i;
2894
2895 side_pairs = &renames->pairs[s];
2896 for (i = 0; i < side_pairs->nr; ++i) {
2897 struct diff_filepair *p = side_pairs->queue[i];
2898 diff_free_filepair(p);
2899 }
2900 }
2901
2902simple_cleanup:
e1a124e8
EN
2903 /* Free memory for renames->pairs[] and combined */
2904 for (s = MERGE_SIDE1; s <= MERGE_SIDE2; s++) {
2905 free(renames->pairs[s].queue);
2906 DIFF_QUEUE_CLEAR(&renames->pairs[s]);
2907 }
2908 if (combined.nr) {
2909 int i;
2910 for (i = 0; i < combined.nr; i++)
2911 diff_free_filepair(combined.queue[i]);
2912 free(combined.queue);
2913 }
231e2dd4 2914
231e2dd4
EN
2915 return clean;
2916}
2917
04af1879
EN
2918/*** Function Grouping: functions related to process_entries() ***/
2919
5a3743da 2920static int sort_dirs_next_to_their_children(const char *one, const char *two)
8adffaa8 2921{
5a3743da
EN
2922 unsigned char c1, c2;
2923
2924 /*
2925 * Here we only care that entries for directories appear adjacent
2926 * to and before files underneath the directory. We can achieve
2927 * that by pretending to add a trailing slash to every file and
2928 * then sorting. In other words, we do not want the natural
2929 * sorting of
2930 * foo
2931 * foo.txt
2932 * foo/bar
2933 * Instead, we want "foo" to sort as though it were "foo/", so that
2934 * we instead get
2935 * foo.txt
2936 * foo
2937 * foo/bar
2938 * To achieve this, we basically implement our own strcmp, except that
2939 * if we get to the end of either string instead of comparing NUL to
2940 * another character, we compare '/' to it.
2941 *
2942 * If this unusual "sort as though '/' were appended" perplexes
2943 * you, perhaps it will help to note that this is not the final
2944 * sort. write_tree() will sort again without the trailing slash
2945 * magic, but just on paths immediately under a given tree.
8adffaa8 2946 *
5a3743da
EN
2947 * The reason to not use df_name_compare directly was that it was
2948 * just too expensive (we don't have the string lengths handy), so
2949 * it was reimplemented.
8adffaa8 2950 */
5a3743da 2951
8adffaa8 2952 /*
5a3743da
EN
2953 * NOTE: This function will never be called with two equal strings,
2954 * because it is used to sort the keys of a strmap, and strmaps have
2955 * unique keys by construction. That simplifies our c1==c2 handling
2956 * below.
8adffaa8 2957 */
5a3743da
EN
2958
2959 while (*one && (*one == *two)) {
2960 one++;
2961 two++;
2962 }
2963
2964 c1 = *one ? *one : '/';
2965 c2 = *two ? *two : '/';
2966
2967 if (c1 == c2) {
2968 /* Getting here means one is a leading directory of the other */
2969 return (*one) ? 1 : -1;
2970 } else
2971 return c1 - c2;
8adffaa8
EN
2972}
2973
3860220b
EN
2974static int read_oid_strbuf(struct merge_options *opt,
2975 const struct object_id *oid,
2976 struct strbuf *dst)
2977{
2978 void *buf;
2979 enum object_type type;
2980 unsigned long size;
2981 buf = read_object_file(oid, &type, &size);
2982 if (!buf)
2983 return err(opt, _("cannot read object %s"), oid_to_hex(oid));
2984 if (type != OBJ_BLOB) {
2985 free(buf);
2986 return err(opt, _("object %s is not a blob"), oid_to_hex(oid));
2987 }
2988 strbuf_attach(dst, buf, size, size + 1);
2989 return 0;
2990}
2991
2992static int blob_unchanged(struct merge_options *opt,
2993 const struct version_info *base,
2994 const struct version_info *side,
2995 const char *path)
2996{
2997 struct strbuf basebuf = STRBUF_INIT;
2998 struct strbuf sidebuf = STRBUF_INIT;
2999 int ret = 0; /* assume changed for safety */
8e978529 3000 struct index_state *idx = &opt->priv->attr_index;
3860220b
EN
3001
3002 if (!idx->initialized)
3003 initialize_attr_index(opt);
3004
3005 if (base->mode != side->mode)
3006 return 0;
3007 if (oideq(&base->oid, &side->oid))
3008 return 1;
3009
3010 if (read_oid_strbuf(opt, &base->oid, &basebuf) ||
3011 read_oid_strbuf(opt, &side->oid, &sidebuf))
3012 goto error_return;
3013 /*
3014 * Note: binary | is used so that both renormalizations are
3015 * performed. Comparison can be skipped if both files are
3016 * unchanged since their sha1s have already been compared.
3017 */
3018 if (renormalize_buffer(idx, path, basebuf.buf, basebuf.len, &basebuf) |
3019 renormalize_buffer(idx, path, sidebuf.buf, sidebuf.len, &sidebuf))
3020 ret = (basebuf.len == sidebuf.len &&
3021 !memcmp(basebuf.buf, sidebuf.buf, basebuf.len));
3022
3023error_return:
3024 strbuf_release(&basebuf);
3025 strbuf_release(&sidebuf);
3026 return ret;
3027}
3028
a9945bba 3029struct directory_versions {
bb470f4e
EN
3030 /*
3031 * versions: list of (basename -> version_info)
3032 *
3033 * The basenames are in reverse lexicographic order of full pathnames,
3034 * as processed in process_entries(). This puts all entries within
3035 * a directory together, and covers the directory itself after
3036 * everything within it, allowing us to write subtrees before needing
3037 * to record information for the tree itself.
3038 */
a9945bba 3039 struct string_list versions;
bb470f4e
EN
3040
3041 /*
3042 * offsets: list of (full relative path directories -> integer offsets)
3043 *
3044 * Since versions contains basenames from files in multiple different
3045 * directories, we need to know which entries in versions correspond
3046 * to which directories. Values of e.g.
3047 * "" 0
3048 * src 2
3049 * src/moduleA 5
3050 * Would mean that entries 0-1 of versions are files in the toplevel
3051 * directory, entries 2-4 are files under src/, and the remaining
3052 * entries starting at index 5 are files under src/moduleA/.
3053 */
3054 struct string_list offsets;
3055
3056 /*
3057 * last_directory: directory that previously processed file found in
3058 *
3059 * last_directory starts NULL, but records the directory in which the
3060 * previous file was found within. As soon as
3061 * directory(current_file) != last_directory
3062 * then we need to start updating accounting in versions & offsets.
3063 * Note that last_directory is always the last path in "offsets" (or
3064 * NULL if "offsets" is empty) so this exists just for quick access.
3065 */
3066 const char *last_directory;
3067
3068 /* last_directory_len: cached computation of strlen(last_directory) */
3069 unsigned last_directory_len;
a9945bba
EN
3070};
3071
ee4012dc
EN
3072static int tree_entry_order(const void *a_, const void *b_)
3073{
3074 const struct string_list_item *a = a_;
3075 const struct string_list_item *b = b_;
3076
3077 const struct merged_info *ami = a->util;
3078 const struct merged_info *bmi = b->util;
3079 return base_name_compare(a->string, strlen(a->string), ami->result.mode,
3080 b->string, strlen(b->string), bmi->result.mode);
3081}
3082
3083static void write_tree(struct object_id *result_oid,
3084 struct string_list *versions,
3085 unsigned int offset,
3086 size_t hash_size)
3087{
3088 size_t maxlen = 0, extra;
c1ea48a8 3089 unsigned int nr;
ee4012dc 3090 struct strbuf buf = STRBUF_INIT;
ee4012dc
EN
3091 int i;
3092
c1ea48a8
AH
3093 assert(offset <= versions->nr);
3094 nr = versions->nr - offset;
3095 if (versions->nr)
257ae76b 3096 /* No need for STABLE_QSORT -- filenames must be unique */
c1ea48a8 3097 QSORT(versions->items + offset, nr, tree_entry_order);
ee4012dc
EN
3098
3099 /* Pre-allocate some space in buf */
3100 extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
3101 for (i = 0; i < nr; i++) {
3102 maxlen += strlen(versions->items[offset+i].string) + extra;
3103 }
3104 strbuf_grow(&buf, maxlen);
3105
3106 /* Write each entry out to buf */
3107 for (i = 0; i < nr; i++) {
3108 struct merged_info *mi = versions->items[offset+i].util;
3109 struct version_info *ri = &mi->result;
3110 strbuf_addf(&buf, "%o %s%c",
3111 ri->mode,
3112 versions->items[offset+i].string, '\0');
3113 strbuf_add(&buf, ri->oid.hash, hash_size);
3114 }
3115
3116 /* Write this object file out, and record in result_oid */
3117 write_object_file(buf.buf, buf.len, tree_type, result_oid);
3118 strbuf_release(&buf);
3119}
3120
a9945bba
EN
3121static void record_entry_for_tree(struct directory_versions *dir_metadata,
3122 const char *path,
3123 struct merged_info *mi)
3124{
3125 const char *basename;
3126
3127 if (mi->is_null)
3128 /* nothing to record */
3129 return;
3130
3131 basename = path + mi->basename_offset;
3132 assert(strchr(basename, '/') == NULL);
3133 string_list_append(&dir_metadata->versions,
3134 basename)->util = &mi->result;
3135}
3136
bb470f4e
EN
3137static void write_completed_directory(struct merge_options *opt,
3138 const char *new_directory_name,
3139 struct directory_versions *info)
3140{
3141 const char *prev_dir;
3142 struct merged_info *dir_info = NULL;
3143 unsigned int offset;
3144
3145 /*
3146 * Some explanation of info->versions and info->offsets...
3147 *
3148 * process_entries() iterates over all relevant files AND
3149 * directories in reverse lexicographic order, and calls this
3150 * function. Thus, an example of the paths that process_entries()
3151 * could operate on (along with the directories for those paths
3152 * being shown) is:
3153 *
3154 * xtract.c ""
3155 * tokens.txt ""
3156 * src/moduleB/umm.c src/moduleB
3157 * src/moduleB/stuff.h src/moduleB
3158 * src/moduleB/baz.c src/moduleB
3159 * src/moduleB src
3160 * src/moduleA/foo.c src/moduleA
3161 * src/moduleA/bar.c src/moduleA
3162 * src/moduleA src
3163 * src ""
3164 * Makefile ""
3165 *
3166 * info->versions:
3167 *
3168 * always contains the unprocessed entries and their
3169 * version_info information. For example, after the first five
3170 * entries above, info->versions would be:
3171 *
3172 * xtract.c <xtract.c's version_info>
3173 * token.txt <token.txt's version_info>
3174 * umm.c <src/moduleB/umm.c's version_info>
3175 * stuff.h <src/moduleB/stuff.h's version_info>
3176 * baz.c <src/moduleB/baz.c's version_info>
3177 *
3178 * Once a subdirectory is completed we remove the entries in
3179 * that subdirectory from info->versions, writing it as a tree
3180 * (write_tree()). Thus, as soon as we get to src/moduleB,
3181 * info->versions would be updated to
3182 *
3183 * xtract.c <xtract.c's version_info>
3184 * token.txt <token.txt's version_info>
3185 * moduleB <src/moduleB's version_info>
3186 *
3187 * info->offsets:
3188 *
3189 * helps us track which entries in info->versions correspond to
3190 * which directories. When we are N directories deep (e.g. 4
3191 * for src/modA/submod/subdir/), we have up to N+1 unprocessed
3192 * directories (+1 because of toplevel dir). Corresponding to
3193 * the info->versions example above, after processing five entries
3194 * info->offsets will be:
3195 *
3196 * "" 0
3197 * src/moduleB 2
3198 *
3199 * which is used to know that xtract.c & token.txt are from the
3200 * toplevel dirctory, while umm.c & stuff.h & baz.c are from the
3201 * src/moduleB directory. Again, following the example above,
3202 * once we need to process src/moduleB, then info->offsets is
3203 * updated to
3204 *
3205 * "" 0
3206 * src 2
3207 *
3208 * which says that moduleB (and only moduleB so far) is in the
3209 * src directory.
3210 *
3211 * One unique thing to note about info->offsets here is that
3212 * "src" was not added to info->offsets until there was a path
3213 * (a file OR directory) immediately below src/ that got
3214 * processed.
3215 *
3216 * Since process_entry() just appends new entries to info->versions,
3217 * write_completed_directory() only needs to do work if the next path
3218 * is in a directory that is different than the last directory found
3219 * in info->offsets.
3220 */
3221
3222 /*
3223 * If we are working with the same directory as the last entry, there
3224 * is no work to do. (See comments above the directory_name member of
3225 * struct merged_info for why we can use pointer comparison instead of
3226 * strcmp here.)
3227 */
3228 if (new_directory_name == info->last_directory)
3229 return;
3230
3231 /*
3232 * If we are just starting (last_directory is NULL), or last_directory
3233 * is a prefix of the current directory, then we can just update
3234 * info->offsets to record the offset where we started this directory
3235 * and update last_directory to have quick access to it.
3236 */
3237 if (info->last_directory == NULL ||
3238 !strncmp(new_directory_name, info->last_directory,
3239 info->last_directory_len)) {
3240 uintptr_t offset = info->versions.nr;
3241
3242 info->last_directory = new_directory_name;
3243 info->last_directory_len = strlen(info->last_directory);
3244 /*
3245 * Record the offset into info->versions where we will
3246 * start recording basenames of paths found within
3247 * new_directory_name.
3248 */
3249 string_list_append(&info->offsets,
3250 info->last_directory)->util = (void*)offset;
3251 return;
3252 }
3253
3254 /*
3255 * The next entry that will be processed will be within
3256 * new_directory_name. Since at this point we know that
3257 * new_directory_name is within a different directory than
3258 * info->last_directory, we have all entries for info->last_directory
3259 * in info->versions and we need to create a tree object for them.
3260 */
3261 dir_info = strmap_get(&opt->priv->paths, info->last_directory);
3262 assert(dir_info);
3263 offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
3264 if (offset == info->versions.nr) {
3265 /*
3266 * Actually, we don't need to create a tree object in this
3267 * case. Whenever all files within a directory disappear
3268 * during the merge (e.g. unmodified on one side and
3269 * deleted on the other, or files were renamed elsewhere),
3270 * then we get here and the directory itself needs to be
3271 * omitted from its parent tree as well.
3272 */
3273 dir_info->is_null = 1;
3274 } else {
3275 /*
3276 * Write out the tree to the git object directory, and also
3277 * record the mode and oid in dir_info->result.
3278 */
3279 dir_info->is_null = 0;
3280 dir_info->result.mode = S_IFDIR;
3281 write_tree(&dir_info->result.oid, &info->versions, offset,
3282 opt->repo->hash_algo->rawsz);
3283 }
3284
3285 /*
3286 * We've now used several entries from info->versions and one entry
3287 * from info->offsets, so we get rid of those values.
3288 */
3289 info->offsets.nr--;
3290 info->versions.nr = offset;
3291
3292 /*
3293 * Now we've taken care of the completed directory, but we need to
3294 * prepare things since future entries will be in
3295 * new_directory_name. (In particular, process_entry() will be
3296 * appending new entries to info->versions.) So, we need to make
3297 * sure new_directory_name is the last entry in info->offsets.
3298 */
3299 prev_dir = info->offsets.nr == 0 ? NULL :
3300 info->offsets.items[info->offsets.nr-1].string;
3301 if (new_directory_name != prev_dir) {
3302 uintptr_t c = info->versions.nr;
3303 string_list_append(&info->offsets,
3304 new_directory_name)->util = (void*)c;
3305 }
3306
3307 /* And, of course, we need to update last_directory to match. */
3308 info->last_directory = new_directory_name;
3309 info->last_directory_len = strlen(info->last_directory);
3310}
3311
6a02dd90
EN
3312/* Per entry merge function */
3313static void process_entry(struct merge_options *opt,
3314 const char *path,
a9945bba
EN
3315 struct conflict_info *ci,
3316 struct directory_versions *dir_metadata)
6a02dd90 3317{
23366d2a
EN
3318 int df_file_index = 0;
3319
6a02dd90
EN
3320 VERIFY_CI(ci);
3321 assert(ci->filemask >= 0 && ci->filemask <= 7);
3322 /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
3323 assert(ci->match_mask == 0 || ci->match_mask == 3 ||
3324 ci->match_mask == 5 || ci->match_mask == 6);
3325
a9945bba
EN
3326 if (ci->dirmask) {
3327 record_entry_for_tree(dir_metadata, path, &ci->merged);
3328 if (ci->filemask == 0)
3329 /* nothing else to handle */
3330 return;
3331 assert(ci->df_conflict);
3332 }
3333
0ccfa4e5
EN
3334 if (ci->df_conflict && ci->merged.result.mode == 0) {
3335 int i;
3336
3337 /*
3338 * directory no longer in the way, but we do have a file we
3339 * need to place here so we need to clean away the "directory
3340 * merges to nothing" result.
3341 */
3342 ci->df_conflict = 0;
3343 assert(ci->filemask != 0);
3344 ci->merged.clean = 0;
3345 ci->merged.is_null = 0;
3346 /* and we want to zero out any directory-related entries */
3347 ci->match_mask = (ci->match_mask & ~ci->dirmask);
3348 ci->dirmask = 0;
3349 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
3350 if (ci->filemask & (1 << i))
3351 continue;
3352 ci->stages[i].mode = 0;
14228447 3353 oidcpy(&ci->stages[i].oid, null_oid());
0ccfa4e5
EN
3354 }
3355 } else if (ci->df_conflict && ci->merged.result.mode != 0) {
23366d2a
EN
3356 /*
3357 * This started out as a D/F conflict, and the entries in
3358 * the competing directory were not removed by the merge as
3359 * evidenced by write_completed_directory() writing a value
3360 * to ci->merged.result.mode.
3361 */
3362 struct conflict_info *new_ci;
3363 const char *branch;
3364 const char *old_path = path;
3365 int i;
3366
3367 assert(ci->merged.result.mode == S_IFDIR);
3368
3369 /*
3370 * If filemask is 1, we can just ignore the file as having
3371 * been deleted on both sides. We do not want to overwrite
3372 * ci->merged.result, since it stores the tree for all the
3373 * files under it.
3374 */
3375 if (ci->filemask == 1) {
3376 ci->filemask = 0;
3377 return;
3378 }
3379
3380 /*
3381 * This file still exists on at least one side, and we want
3382 * the directory to remain here, so we need to move this
3383 * path to some new location.
3384 */
ca56dadb 3385 CALLOC_ARRAY(new_ci, 1);
23366d2a
EN
3386 /* We don't really want new_ci->merged.result copied, but it'll
3387 * be overwritten below so it doesn't matter. We also don't
3388 * want any directory mode/oid values copied, but we'll zero
3389 * those out immediately. We do want the rest of ci copied.
3390 */
3391 memcpy(new_ci, ci, sizeof(*ci));
3392 new_ci->match_mask = (new_ci->match_mask & ~new_ci->dirmask);
3393 new_ci->dirmask = 0;
3394 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
3395 if (new_ci->filemask & (1 << i))
3396 continue;
3397 /* zero out any entries related to directories */
3398 new_ci->stages[i].mode = 0;
14228447 3399 oidcpy(&new_ci->stages[i].oid, null_oid());
23366d2a
EN
3400 }
3401
3402 /*
3403 * Find out which side this file came from; note that we
3404 * cannot just use ci->filemask, because renames could cause
3405 * the filemask to go back to 7. So we use dirmask, then
3406 * pick the opposite side's index.
3407 */
3408 df_file_index = (ci->dirmask & (1 << 1)) ? 2 : 1;
3409 branch = (df_file_index == 1) ? opt->branch1 : opt->branch2;
3410 path = unique_path(&opt->priv->paths, path, branch);
3411 strmap_put(&opt->priv->paths, path, new_ci);
3412
3413 path_msg(opt, path, 0,
3414 _("CONFLICT (file/directory): directory in the way "
3415 "of %s from %s; moving it to %s instead."),
3416 old_path, branch, path);
3417
3418 /*
3419 * Zero out the filemask for the old ci. At this point, ci
3420 * was just an entry for a directory, so we don't need to
3421 * do anything more with it.
3422 */
3423 ci->filemask = 0;
3424
3425 /*
3426 * Now note that we're working on the new entry (path was
3427 * updated above.
3428 */
3429 ci = new_ci;
6a02dd90
EN
3430 }
3431
3432 /*
3433 * NOTE: Below there is a long switch-like if-elseif-elseif... block
3434 * which the code goes through even for the df_conflict cases
23366d2a 3435 * above.
6a02dd90
EN
3436 */
3437 if (ci->match_mask) {
a492d533 3438 ci->merged.clean = !ci->df_conflict && !ci->path_conflict;
6a02dd90
EN
3439 if (ci->match_mask == 6) {
3440 /* stages[1] == stages[2] */
3441 ci->merged.result.mode = ci->stages[1].mode;
3442 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
3443 } else {
3444 /* determine the mask of the side that didn't match */
3445 unsigned int othermask = 7 & ~ci->match_mask;
3446 int side = (othermask == 4) ? 2 : 1;
3447
3448 ci->merged.result.mode = ci->stages[side].mode;
3449 ci->merged.is_null = !ci->merged.result.mode;
a492d533
EN
3450 if (ci->merged.is_null)
3451 ci->merged.clean = 1;
6a02dd90
EN
3452 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
3453
3454 assert(othermask == 2 || othermask == 4);
3455 assert(ci->merged.is_null ==
3456 (ci->filemask == ci->match_mask));
3457 }
3458 } else if (ci->filemask >= 6 &&
3459 (S_IFMT & ci->stages[1].mode) !=
3460 (S_IFMT & ci->stages[2].mode)) {
4ef88fc3
EN
3461 /* Two different items from (file/submodule/symlink) */
3462 if (opt->priv->call_depth) {
3463 /* Just use the version from the merge base */
3464 ci->merged.clean = 0;
3465 oidcpy(&ci->merged.result.oid, &ci->stages[0].oid);
3466 ci->merged.result.mode = ci->stages[0].mode;
3467 ci->merged.is_null = (ci->merged.result.mode == 0);
3468 } else {
3469 /* Handle by renaming one or both to separate paths. */
3470 unsigned o_mode = ci->stages[0].mode;
3471 unsigned a_mode = ci->stages[1].mode;
3472 unsigned b_mode = ci->stages[2].mode;
3473 struct conflict_info *new_ci;
3474 const char *a_path = NULL, *b_path = NULL;
3475 int rename_a = 0, rename_b = 0;
3476
3477 new_ci = xmalloc(sizeof(*new_ci));
3478
3479 if (S_ISREG(a_mode))
3480 rename_a = 1;
3481 else if (S_ISREG(b_mode))
3482 rename_b = 1;
3483 else {
3484 rename_a = 1;
3485 rename_b = 1;
3486 }
3487
0e59f7ad
AH
3488 if (rename_a && rename_b) {
3489 path_msg(opt, path, 0,
3490 _("CONFLICT (distinct types): %s had "
3491 "different types on each side; "
3492 "renamed both of them so each can "
3493 "be recorded somewhere."),
3494 path);
3495 } else {
3496 path_msg(opt, path, 0,
3497 _("CONFLICT (distinct types): %s had "
3498 "different types on each side; "
3499 "renamed one of them so each can be "
3500 "recorded somewhere."),
3501 path);
3502 }
4ef88fc3
EN
3503
3504 ci->merged.clean = 0;
3505 memcpy(new_ci, ci, sizeof(*new_ci));
3506
3507 /* Put b into new_ci, removing a from stages */
3508 new_ci->merged.result.mode = ci->stages[2].mode;
3509 oidcpy(&new_ci->merged.result.oid, &ci->stages[2].oid);
3510 new_ci->stages[1].mode = 0;
14228447 3511 oidcpy(&new_ci->stages[1].oid, null_oid());
4ef88fc3
EN
3512 new_ci->filemask = 5;
3513 if ((S_IFMT & b_mode) != (S_IFMT & o_mode)) {
3514 new_ci->stages[0].mode = 0;
14228447 3515 oidcpy(&new_ci->stages[0].oid, null_oid());
4ef88fc3
EN
3516 new_ci->filemask = 4;
3517 }
3518
3519 /* Leave only a in ci, fixing stages. */
3520 ci->merged.result.mode = ci->stages[1].mode;
3521 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
3522 ci->stages[2].mode = 0;
14228447 3523 oidcpy(&ci->stages[2].oid, null_oid());
4ef88fc3
EN
3524 ci->filemask = 3;
3525 if ((S_IFMT & a_mode) != (S_IFMT & o_mode)) {
3526 ci->stages[0].mode = 0;
14228447 3527 oidcpy(&ci->stages[0].oid, null_oid());
4ef88fc3
EN
3528 ci->filemask = 2;
3529 }
3530
3531 /* Insert entries into opt->priv_paths */
3532 assert(rename_a || rename_b);
3533 if (rename_a) {
3534 a_path = unique_path(&opt->priv->paths,
3535 path, opt->branch1);
3536 strmap_put(&opt->priv->paths, a_path, ci);
3537 }
3538
3539 if (rename_b)
3540 b_path = unique_path(&opt->priv->paths,
3541 path, opt->branch2);
3542 else
3543 b_path = path;
3544 strmap_put(&opt->priv->paths, b_path, new_ci);
3545
3546 if (rename_a && rename_b) {
3547 strmap_remove(&opt->priv->paths, path, 0);
3548 /*
3549 * We removed path from opt->priv->paths. path
3550 * will also eventually need to be freed, but
3551 * it may still be used by e.g. ci->pathnames.
3552 * So, store it in another string-list for now.
3553 */
3554 string_list_append(&opt->priv->paths_to_free,
3555 path);
3556 }
3557
3558 /*
3559 * Do special handling for b_path since process_entry()
3560 * won't be called on it specially.
3561 */
3562 strmap_put(&opt->priv->conflicted, b_path, new_ci);
3563 record_entry_for_tree(dir_metadata, b_path,
3564 &new_ci->merged);
3565
3566 /*
3567 * Remaining code for processing this entry should
3568 * think in terms of processing a_path.
3569 */
3570 if (a_path)
3571 path = a_path;
3572 }
6a02dd90 3573 } else if (ci->filemask >= 6) {
991bbdca
EN
3574 /* Need a two-way or three-way content merge */
3575 struct version_info merged_file;
3576 unsigned clean_merge;
3577 struct version_info *o = &ci->stages[0];
3578 struct version_info *a = &ci->stages[1];
3579 struct version_info *b = &ci->stages[2];
3580
3581 clean_merge = handle_content_merge(opt, path, o, a, b,
3582 ci->pathnames,
3583 opt->priv->call_depth * 2,
3584 &merged_file);
3585 ci->merged.clean = clean_merge &&
3586 !ci->df_conflict && !ci->path_conflict;
3587 ci->merged.result.mode = merged_file.mode;
3588 ci->merged.is_null = (merged_file.mode == 0);
3589 oidcpy(&ci->merged.result.oid, &merged_file.oid);
3590 if (clean_merge && ci->df_conflict) {
3591 assert(df_file_index == 1 || df_file_index == 2);
3592 ci->filemask = 1 << df_file_index;
3593 ci->stages[df_file_index].mode = merged_file.mode;
3594 oidcpy(&ci->stages[df_file_index].oid, &merged_file.oid);
3595 }
3596 if (!clean_merge) {
3597 const char *reason = _("content");
3598 if (ci->filemask == 6)
3599 reason = _("add/add");
3600 if (S_ISGITLINK(merged_file.mode))
3601 reason = _("submodule");
3602 path_msg(opt, path, 0,
3603 _("CONFLICT (%s): Merge conflict in %s"),
3604 reason, path);
3605 }
6a02dd90
EN
3606 } else if (ci->filemask == 3 || ci->filemask == 5) {
3607 /* Modify/delete */
c5a6f655
EN
3608 const char *modify_branch, *delete_branch;
3609 int side = (ci->filemask == 5) ? 2 : 1;
3610 int index = opt->priv->call_depth ? 0 : side;
3611
3612 ci->merged.result.mode = ci->stages[index].mode;
3613 oidcpy(&ci->merged.result.oid, &ci->stages[index].oid);
3614 ci->merged.clean = 0;
3615
3616 modify_branch = (side == 1) ? opt->branch1 : opt->branch2;
3617 delete_branch = (side == 1) ? opt->branch2 : opt->branch1;
3618
3860220b
EN
3619 if (opt->renormalize &&
3620 blob_unchanged(opt, &ci->stages[0], &ci->stages[side],
3621 path)) {
3622 ci->merged.is_null = 1;
3623 ci->merged.clean = 1;
a492d533 3624 assert(!ci->df_conflict && !ci->path_conflict);
3860220b
EN
3625 } else if (ci->path_conflict &&
3626 oideq(&ci->stages[0].oid, &ci->stages[side].oid)) {
2e91ddd2
EN
3627 /*
3628 * This came from a rename/delete; no action to take,
3629 * but avoid printing "modify/delete" conflict notice
3630 * since the contents were not modified.
3631 */
3632 } else {
3633 path_msg(opt, path, 0,
3634 _("CONFLICT (modify/delete): %s deleted in %s "
3635 "and modified in %s. Version %s of %s left "
3636 "in tree."),
3637 path, delete_branch, modify_branch,
3638 modify_branch, path);
3639 }
6a02dd90
EN
3640 } else if (ci->filemask == 2 || ci->filemask == 4) {
3641 /* Added on one side */
3642 int side = (ci->filemask == 4) ? 2 : 1;
3643 ci->merged.result.mode = ci->stages[side].mode;
3644 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
53e88a03 3645 ci->merged.clean = !ci->df_conflict && !ci->path_conflict;
6a02dd90
EN
3646 } else if (ci->filemask == 1) {
3647 /* Deleted on both sides */
3648 ci->merged.is_null = 1;
3649 ci->merged.result.mode = 0;
14228447 3650 oidcpy(&ci->merged.result.oid, null_oid());
a492d533 3651 assert(!ci->df_conflict);
53e88a03 3652 ci->merged.clean = !ci->path_conflict;
6a02dd90
EN
3653 }
3654
3655 /*
3656 * If still conflicted, record it separately. This allows us to later
3657 * iterate over just conflicted entries when updating the index instead
3658 * of iterating over all entries.
3659 */
3660 if (!ci->merged.clean)
3661 strmap_put(&opt->priv->conflicted, path, ci);
ef68c3d8
EN
3662
3663 /* Record metadata for ci->merged in dir_metadata */
a9945bba 3664 record_entry_for_tree(dir_metadata, path, &ci->merged);
6a02dd90
EN
3665}
3666
2bff554b
EN
3667static void prefetch_for_content_merges(struct merge_options *opt,
3668 struct string_list *plist)
3669{
3670 struct string_list_item *e;
3671 struct oid_array to_fetch = OID_ARRAY_INIT;
3672
3673 if (opt->repo != the_repository || !has_promisor_remote())
3674 return;
3675
3676 for (e = &plist->items[plist->nr-1]; e >= plist->items; --e) {
3677 /* char *path = e->string; */
3678 struct conflict_info *ci = e->util;
3679 int i;
3680
3681 /* Ignore clean entries */
3682 if (ci->merged.clean)
3683 continue;
3684
3685 /* Ignore entries that don't need a content merge */
3686 if (ci->match_mask || ci->filemask < 6 ||
3687 !S_ISREG(ci->stages[1].mode) ||
3688 !S_ISREG(ci->stages[2].mode) ||
3689 oideq(&ci->stages[1].oid, &ci->stages[2].oid))
3690 continue;
3691
3692 /* Also don't need content merge if base matches either side */
3693 if (ci->filemask == 7 &&
3694 S_ISREG(ci->stages[0].mode) &&
3695 (oideq(&ci->stages[0].oid, &ci->stages[1].oid) ||
3696 oideq(&ci->stages[0].oid, &ci->stages[2].oid)))
3697 continue;
3698
3699 for (i = 0; i < 3; i++) {
3700 unsigned side_mask = (1 << i);
3701 struct version_info *vi = &ci->stages[i];
3702
3703 if ((ci->filemask & side_mask) &&
3704 S_ISREG(vi->mode) &&
3705 oid_object_info_extended(opt->repo, &vi->oid, NULL,
3706 OBJECT_INFO_FOR_PREFETCH))
3707 oid_array_append(&to_fetch, &vi->oid);
3708 }
3709 }
3710
3711 promisor_remote_get_direct(opt->repo, to_fetch.oid, to_fetch.nr);
3712 oid_array_clear(&to_fetch);
3713}
3714
231e2dd4
EN
3715static void process_entries(struct merge_options *opt,
3716 struct object_id *result_oid)
3717{
6a02dd90
EN
3718 struct hashmap_iter iter;
3719 struct strmap_entry *e;
8adffaa8
EN
3720 struct string_list plist = STRING_LIST_INIT_NODUP;
3721 struct string_list_item *entry;
bb470f4e
EN
3722 struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
3723 STRING_LIST_INIT_NODUP,
3724 NULL, 0 };
6a02dd90 3725
557ac035 3726 trace2_region_enter("merge", "process_entries setup", opt->repo);
6a02dd90
EN
3727 if (strmap_empty(&opt->priv->paths)) {
3728 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
3729 return;
3730 }
3731
8adffaa8 3732 /* Hack to pre-allocate plist to the desired size */
557ac035 3733 trace2_region_enter("merge", "plist grow", opt->repo);
8adffaa8 3734 ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
557ac035 3735 trace2_region_leave("merge", "plist grow", opt->repo);
8adffaa8
EN
3736
3737 /* Put every entry from paths into plist, then sort */
557ac035 3738 trace2_region_enter("merge", "plist copy", opt->repo);
6a02dd90 3739 strmap_for_each_entry(&opt->priv->paths, &iter, e) {
8adffaa8
EN
3740 string_list_append(&plist, e->key)->util = e->value;
3741 }
557ac035
EN
3742 trace2_region_leave("merge", "plist copy", opt->repo);
3743
3744 trace2_region_enter("merge", "plist special sort", opt->repo);
5a3743da 3745 plist.cmp = sort_dirs_next_to_their_children;
8adffaa8 3746 string_list_sort(&plist);
557ac035
EN
3747 trace2_region_leave("merge", "plist special sort", opt->repo);
3748
3749 trace2_region_leave("merge", "process_entries setup", opt->repo);
8adffaa8
EN
3750
3751 /*
3752 * Iterate over the items in reverse order, so we can handle paths
3753 * below a directory before needing to handle the directory itself.
bb470f4e
EN
3754 *
3755 * This allows us to write subtrees before we need to write trees,
3756 * and it also enables sane handling of directory/file conflicts
3757 * (because it allows us to know whether the directory is still in
3758 * the way when it is time to process the file at the same path).
8adffaa8 3759 */
557ac035 3760 trace2_region_enter("merge", "processing", opt->repo);
2bff554b 3761 prefetch_for_content_merges(opt, &plist);
8adffaa8
EN
3762 for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
3763 char *path = entry->string;
6a02dd90
EN
3764 /*
3765 * NOTE: mi may actually be a pointer to a conflict_info, but
3766 * we have to check mi->clean first to see if it's safe to
3767 * reassign to such a pointer type.
3768 */
8adffaa8 3769 struct merged_info *mi = entry->util;
6a02dd90 3770
bb470f4e
EN
3771 write_completed_directory(opt, mi->directory_name,
3772 &dir_metadata);
a9945bba
EN
3773 if (mi->clean)
3774 record_entry_for_tree(&dir_metadata, path, mi);
3775 else {
8adffaa8 3776 struct conflict_info *ci = (struct conflict_info *)mi;
a9945bba 3777 process_entry(opt, path, ci, &dir_metadata);
8adffaa8 3778 }
6a02dd90 3779 }
557ac035 3780 trace2_region_leave("merge", "processing", opt->repo);
6a02dd90 3781
557ac035 3782 trace2_region_enter("merge", "process_entries cleanup", opt->repo);
bb470f4e
EN
3783 if (dir_metadata.offsets.nr != 1 ||
3784 (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
3785 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
3786 dir_metadata.offsets.nr);
3787 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
3788 (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
3789 fflush(stdout);
3790 BUG("dir_metadata accounting completely off; shouldn't happen");
3791 }
ee4012dc
EN
3792 write_tree(result_oid, &dir_metadata.versions, 0,
3793 opt->repo->hash_algo->rawsz);
8adffaa8 3794 string_list_clear(&plist, 0);
a9945bba 3795 string_list_clear(&dir_metadata.versions, 0);
bb470f4e 3796 string_list_clear(&dir_metadata.offsets, 0);
557ac035 3797 trace2_region_leave("merge", "process_entries cleanup", opt->repo);
231e2dd4
EN
3798}
3799
04af1879
EN
3800/*** Function Grouping: functions related to merge_switch_to_result() ***/
3801
9fefce68
EN
3802static int checkout(struct merge_options *opt,
3803 struct tree *prev,
3804 struct tree *next)
3805{
6681ce5c
EN
3806 /* Switch the index/working copy from old to new */
3807 int ret;
3808 struct tree_desc trees[2];
3809 struct unpack_trees_options unpack_opts;
3810
3811 memset(&unpack_opts, 0, sizeof(unpack_opts));
3812 unpack_opts.head_idx = -1;
3813 unpack_opts.src_index = opt->repo->index;
3814 unpack_opts.dst_index = opt->repo->index;
3815
3816 setup_unpack_trees_porcelain(&unpack_opts, "merge");
3817
3818 /*
3819 * NOTE: if this were just "git checkout" code, we would probably
3820 * read or refresh the cache and check for a conflicted index, but
3821 * builtin/merge.c or sequencer.c really needs to read the index
3822 * and check for conflicted entries before starting merging for a
3823 * good user experience (no sense waiting for merges/rebases before
3824 * erroring out), so there's no reason to duplicate that work here.
3825 */
3826
3827 /* 2-way merge to the new branch */
3828 unpack_opts.update = 1;
3829 unpack_opts.merge = 1;
3830 unpack_opts.quiet = 0; /* FIXME: sequencer might want quiet? */
3831 unpack_opts.verbose_update = (opt->verbosity > 2);
3832 unpack_opts.fn = twoway_merge;
3833 if (1/* FIXME: opts->overwrite_ignore*/) {
ca56dadb 3834 CALLOC_ARRAY(unpack_opts.dir, 1);
6681ce5c
EN
3835 unpack_opts.dir->flags |= DIR_SHOW_IGNORED;
3836 setup_standard_excludes(unpack_opts.dir);
3837 }
3838 parse_tree(prev);
3839 init_tree_desc(&trees[0], prev->buffer, prev->size);
3840 parse_tree(next);
3841 init_tree_desc(&trees[1], next->buffer, next->size);
3842
3843 ret = unpack_trees(2, trees, &unpack_opts);
3844 clear_unpack_trees_porcelain(&unpack_opts);
3845 dir_clear(unpack_opts.dir);
3846 FREE_AND_NULL(unpack_opts.dir);
3847 return ret;
9fefce68
EN
3848}
3849
66b209b8 3850static int record_conflicted_index_entries(struct merge_options *opt)
9fefce68 3851{
ef2b3693
EN
3852 struct hashmap_iter iter;
3853 struct strmap_entry *e;
66b209b8
EN
3854 struct index_state *index = opt->repo->index;
3855 struct checkout state = CHECKOUT_INIT;
ef2b3693
EN
3856 int errs = 0;
3857 int original_cache_nr;
3858
66b209b8 3859 if (strmap_empty(&opt->priv->conflicted))
9fefce68
EN
3860 return 0;
3861
66b209b8
EN
3862 /* If any entries have skip_worktree set, we'll have to check 'em out */
3863 state.force = 1;
3864 state.quiet = 1;
3865 state.refresh_cache = 1;
3866 state.istate = index;
ef2b3693
EN
3867 original_cache_nr = index->cache_nr;
3868
3869 /* Put every entry from paths into plist, then sort */
66b209b8 3870 strmap_for_each_entry(&opt->priv->conflicted, &iter, e) {
ef2b3693
EN
3871 const char *path = e->key;
3872 struct conflict_info *ci = e->value;
3873 int pos;
3874 struct cache_entry *ce;
3875 int i;
3876
3877 VERIFY_CI(ci);
3878
3879 /*
3880 * The index will already have a stage=0 entry for this path,
3881 * because we created an as-merged-as-possible version of the
3882 * file and checkout() moved the working copy and index over
3883 * to that version.
3884 *
3885 * However, previous iterations through this loop will have
3886 * added unstaged entries to the end of the cache which
3887 * ignore the standard alphabetical ordering of cache
3888 * entries and break invariants needed for index_name_pos()
3889 * to work. However, we know the entry we want is before
3890 * those appended cache entries, so do a temporary swap on
3891 * cache_nr to only look through entries of interest.
3892 */
3893 SWAP(index->cache_nr, original_cache_nr);
3894 pos = index_name_pos(index, path, strlen(path));
3895 SWAP(index->cache_nr, original_cache_nr);
3896 if (pos < 0) {
3897 if (ci->filemask != 1)
3898 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path);
3899 cache_tree_invalidate_path(index, path);
3900 } else {
3901 ce = index->cache[pos];
3902
3903 /*
3904 * Clean paths with CE_SKIP_WORKTREE set will not be
3905 * written to the working tree by the unpack_trees()
3906 * call in checkout(). Our conflicted entries would
3907 * have appeared clean to that code since we ignored
3908 * the higher order stages. Thus, we need override
3909 * the CE_SKIP_WORKTREE bit and manually write those
3910 * files to the working disk here.
ef2b3693 3911 */
66b209b8
EN
3912 if (ce_skip_worktree(ce)) {
3913 struct stat st;
3914
3915 if (!lstat(path, &st)) {
3916 char *new_name = unique_path(&opt->priv->paths,
3917 path,
3918 "cruft");
3919
3920 path_msg(opt, path, 1,
3921 _("Note: %s not up to date and in way of checking out conflicted version; old copy renamed to %s"),
3922 path, new_name);
3923 errs |= rename(path, new_name);
3924 free(new_name);
3925 }
3926 errs |= checkout_entry(ce, &state, NULL, NULL);
3927 }
ef2b3693
EN
3928
3929 /*
3930 * Mark this cache entry for removal and instead add
3931 * new stage>0 entries corresponding to the
3932 * conflicts. If there are many conflicted entries, we
3933 * want to avoid memmove'ing O(NM) entries by
3934 * inserting the new entries one at a time. So,
3935 * instead, we just add the new cache entries to the
3936 * end (ignoring normal index requirements on sort
3937 * order) and sort the index once we're all done.
3938 */
3939 ce->ce_flags |= CE_REMOVE;
3940 }
3941
3942 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
3943 struct version_info *vi;
3944 if (!(ci->filemask & (1ul << i)))
3945 continue;
3946 vi = &ci->stages[i];
3947 ce = make_cache_entry(index, vi->mode, &vi->oid,
3948 path, i+1, 0);
3949 add_index_entry(index, ce, ADD_CACHE_JUST_APPEND);
3950 }
3951 }
3952
3953 /*
3954 * Remove the unused cache entries (and invalidate the relevant
3955 * cache-trees), then sort the index entries to get the conflicted
3956 * entries we added to the end into their right locations.
3957 */
3958 remove_marked_cache_entries(index, 1);
72b30910
EN
3959 /*
3960 * No need for STABLE_QSORT -- cmp_cache_name_compare sorts primarily
3961 * on filename and secondarily on stage, and (name, stage #) are a
3962 * unique tuple.
3963 */
ef2b3693
EN
3964 QSORT(index->cache, index->cache_nr, cmp_cache_name_compare);
3965
3966 return errs;
9fefce68
EN
3967}
3968
17e5574b
EN
3969void merge_switch_to_result(struct merge_options *opt,
3970 struct tree *head,
3971 struct merge_result *result,
3972 int update_worktree_and_index,
3973 int display_update_msgs)
3974{
9fefce68
EN
3975 assert(opt->priv == NULL);
3976 if (result->clean >= 0 && update_worktree_and_index) {
5291828d
EN
3977 const char *filename;
3978 FILE *fp;
9fefce68 3979
557ac035 3980 trace2_region_enter("merge", "checkout", opt->repo);
9fefce68
EN
3981 if (checkout(opt, head, result->tree)) {
3982 /* failure to function */
3983 result->clean = -1;
3984 return;
3985 }
557ac035 3986 trace2_region_leave("merge", "checkout", opt->repo);
9fefce68 3987
557ac035 3988 trace2_region_enter("merge", "record_conflicted", opt->repo);
66b209b8
EN
3989 opt->priv = result->priv;
3990 if (record_conflicted_index_entries(opt)) {
9fefce68 3991 /* failure to function */
66b209b8 3992 opt->priv = NULL;
9fefce68
EN
3993 result->clean = -1;
3994 return;
3995 }
66b209b8 3996 opt->priv = NULL;
557ac035 3997 trace2_region_leave("merge", "record_conflicted", opt->repo);
5291828d
EN
3998
3999 trace2_region_enter("merge", "write_auto_merge", opt->repo);
4000 filename = git_path_auto_merge(opt->repo);
4001 fp = xfopen(filename, "w");
4002 fprintf(fp, "%s\n", oid_to_hex(&result->tree->object.oid));
4003 fclose(fp);
4004 trace2_region_leave("merge", "write_auto_merge", opt->repo);
9fefce68
EN
4005 }
4006
4007 if (display_update_msgs) {
c5a6f655
EN
4008 struct merge_options_internal *opti = result->priv;
4009 struct hashmap_iter iter;
4010 struct strmap_entry *e;
4011 struct string_list olist = STRING_LIST_INIT_NODUP;
4012 int i;
4013
557ac035
EN
4014 trace2_region_enter("merge", "display messages", opt->repo);
4015
c5a6f655
EN
4016 /* Hack to pre-allocate olist to the desired size */
4017 ALLOC_GROW(olist.items, strmap_get_size(&opti->output),
4018 olist.alloc);
4019
4020 /* Put every entry from output into olist, then sort */
4021 strmap_for_each_entry(&opti->output, &iter, e) {
4022 string_list_append(&olist, e->key)->util = e->value;
4023 }
4024 string_list_sort(&olist);
4025
4026 /* Iterate over the items, printing them */
4027 for (i = 0; i < olist.nr; ++i) {
4028 struct strbuf *sb = olist.items[i].util;
4029
4030 printf("%s", sb->buf);
4031 }
4032 string_list_clear(&olist, 0);
f39d05ca
EN
4033
4034 /* Also include needed rename limit adjustment now */
4035 diff_warn_rename_limit("merge.renamelimit",
4036 opti->renames.needed_limit, 0);
557ac035
EN
4037
4038 trace2_region_leave("merge", "display messages", opt->repo);
9fefce68
EN
4039 }
4040
17e5574b
EN
4041 merge_finalize(opt, result);
4042}
4043
4044void merge_finalize(struct merge_options *opt,
4045 struct merge_result *result)
4046{
89422d29
EN
4047 struct merge_options_internal *opti = result->priv;
4048
ea305a68
EN
4049 if (opt->renormalize)
4050 git_attr_set_direction(GIT_ATTR_CHECKIN);
89422d29
EN
4051 assert(opt->priv == NULL);
4052
43e9c4ee 4053 clear_or_reinit_internal_opts(opti, 0);
89422d29 4054 FREE_AND_NULL(opti);
17e5574b
EN
4055}
4056
04af1879
EN
4057/*** Function Grouping: helper functions for merge_incore_*() ***/
4058
3639dfb3
EN
4059static struct tree *shift_tree_object(struct repository *repo,
4060 struct tree *one, struct tree *two,
4061 const char *subtree_shift)
4062{
4063 struct object_id shifted;
4064
4065 if (!*subtree_shift) {
4066 shift_tree(repo, &one->object.oid, &two->object.oid, &shifted, 0);
4067 } else {
4068 shift_tree_by(repo, &one->object.oid, &two->object.oid, &shifted,
4069 subtree_shift);
4070 }
4071 if (oideq(&two->object.oid, &shifted))
4072 return two;
4073 return lookup_tree(repo, &shifted);
4074}
4075
4296d8f1
EN
4076static inline void set_commit_tree(struct commit *c, struct tree *t)
4077{
4078 c->maybe_tree = t;
4079}
4080
4296d8f1
EN
4081static struct commit *make_virtual_commit(struct repository *repo,
4082 struct tree *tree,
4083 const char *comment)
4084{
4085 struct commit *commit = alloc_commit_node(repo);
4086
4087 set_merge_remote_desc(commit, comment, (struct object *)commit);
4088 set_commit_tree(commit, tree);
4089 commit->object.parsed = 1;
4090 return commit;
4091}
4092
231e2dd4
EN
4093static void merge_start(struct merge_options *opt, struct merge_result *result)
4094{
f5d9fbc2
EN
4095 struct rename_info *renames;
4096 int i;
4097
e4171b1b 4098 /* Sanity checks on opt */
557ac035 4099 trace2_region_enter("merge", "sanity checks", opt->repo);
e4171b1b
EN
4100 assert(opt->repo);
4101
4102 assert(opt->branch1 && opt->branch2);
4103
4104 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
4105 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
4106 assert(opt->rename_limit >= -1);
4107 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
4108 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
4109
4110 assert(opt->xdl_opts >= 0);
4111 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
4112 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
4113
4114 /*
4115 * detect_renames, verbosity, buffer_output, and obuf are ignored
4116 * fields that were used by "recursive" rather than "ort" -- but
4117 * sanity check them anyway.
4118 */
4119 assert(opt->detect_renames >= -1 &&
4120 opt->detect_renames <= DIFF_DETECT_COPY);
4121 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
4122 assert(opt->buffer_output <= 2);
4123 assert(opt->obuf.len == 0);
4124
4125 assert(opt->priv == NULL);
19ceb486
EN
4126 if (result->_properly_initialized != 0 &&
4127 result->_properly_initialized != RESULT_INITIALIZED)
4128 BUG("struct merge_result passed to merge_incore_*recursive() must be zeroed or filled with values from a previous run");
4129 assert(!!result->priv == !!result->_properly_initialized);
cf8937ac
EN
4130 if (result->priv) {
4131 opt->priv = result->priv;
4132 result->priv = NULL;
4133 /*
4134 * opt->priv non-NULL means we had results from a previous
4135 * run; do a few sanity checks that user didn't mess with
4136 * it in an obvious fashion.
4137 */
4138 assert(opt->priv->call_depth == 0);
4139 assert(!opt->priv->toplevel_dir ||
4140 0 == strlen(opt->priv->toplevel_dir));
4141 }
557ac035 4142 trace2_region_leave("merge", "sanity checks", opt->repo);
e4171b1b 4143
c8017176
EN
4144 /* Default to histogram diff. Actually, just hardcode it...for now. */
4145 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
4146
ea305a68
EN
4147 /* Handle attr direction stuff for renormalization */
4148 if (opt->renormalize)
4149 git_attr_set_direction(GIT_ATTR_CHECKOUT);
4150
e4171b1b 4151 /* Initialization of opt->priv, our internal merge data */
557ac035 4152 trace2_region_enter("merge", "allocate/init", opt->repo);
cf8937ac
EN
4153 if (opt->priv) {
4154 clear_or_reinit_internal_opts(opt->priv, 1);
4155 trace2_region_leave("merge", "allocate/init", opt->repo);
4156 return;
4157 }
e4171b1b
EN
4158 opt->priv = xcalloc(1, sizeof(*opt->priv));
4159
f5d9fbc2
EN
4160 /* Initialization of various renames fields */
4161 renames = &opt->priv->renames;
4162 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; i++) {
a49b55d5 4163 strintmap_init_with_options(&renames->dirs_removed[i],
fb52938e 4164 NOT_RELEVANT, NULL, 0);
f5d9fbc2
EN
4165 strmap_init_with_options(&renames->dir_rename_count[i],
4166 NULL, 1);
4167 strmap_init_with_options(&renames->dir_renames[i],
4168 NULL, 0);
2734f2e3
EN
4169 /*
4170 * relevant_sources uses -1 for the default, because we need
4171 * to be able to distinguish not-in-strintmap from valid
4172 * relevant_source values from enum file_rename_relevance.
4173 * In particular, possibly_cache_new_pair() expects a negative
4174 * value for not-found entries.
4175 */
a49b55d5 4176 strintmap_init_with_options(&renames->relevant_sources[i],
2734f2e3
EN
4177 -1 /* explicitly invalid */,
4178 NULL, 0);
d29bd6d7
EN
4179 strmap_init_with_options(&renames->cached_pairs[i],
4180 NULL, 1);
4181 strset_init_with_options(&renames->cached_irrelevant[i],
4182 NULL, 1);
4183 strset_init_with_options(&renames->cached_target_names[i],
4184 NULL, 0);
f5d9fbc2 4185 }
d478f567
EN
4186 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; i++) {
4187 strintmap_init_with_options(&renames->deferred[i].possible_trivial_merges,
4188 0, NULL, 0);
4189 strset_init_with_options(&renames->deferred[i].target_dirs,
4190 NULL, 1);
4191 renames->deferred[i].trivial_merges_okay = 1; /* 1 == maybe */
4192 }
f5d9fbc2 4193
e4171b1b
EN
4194 /*
4195 * Although we initialize opt->priv->paths with strdup_strings=0,
4196 * that's just to avoid making yet another copy of an allocated
4197 * string. Putting the entry into paths means we are taking
43c1dccb 4198 * ownership, so we will later free it. paths_to_free is similar.
e4171b1b
EN
4199 *
4200 * In contrast, conflicted just has a subset of keys from paths, so
4201 * we don't want to free those (it'd be a duplicate free).
4202 */
4203 strmap_init_with_options(&opt->priv->paths, NULL, 0);
4204 strmap_init_with_options(&opt->priv->conflicted, NULL, 0);
bc40dfb1 4205 string_list_init_nodup(&opt->priv->paths_to_free);
c5a6f655
EN
4206
4207 /*
4208 * keys & strbufs in output will sometimes need to outlive "paths",
4209 * so it will have a copy of relevant keys. It's probably a small
4210 * subset of the overall paths that have special output.
4211 */
4212 strmap_init(&opt->priv->output);
557ac035
EN
4213
4214 trace2_region_leave("merge", "allocate/init", opt->repo);
231e2dd4
EN
4215}
4216
64aceb6d
EN
4217static void merge_check_renames_reusable(struct merge_options *opt,
4218 struct merge_result *result,
4219 struct tree *merge_base,
4220 struct tree *side1,
4221 struct tree *side2)
4222{
4223 struct rename_info *renames;
4224 struct tree **merge_trees;
4225 struct merge_options_internal *opti = result->priv;
4226
4227 if (!opti)
4228 return;
4229
4230 renames = &opti->renames;
4231 merge_trees = renames->merge_trees;
cbdca289
EN
4232
4233 /*
4234 * Handle case where previous merge operation did not want cache to
4235 * take effect, e.g. because rename/rename(1to1) makes it invalid.
4236 */
4237 if (!merge_trees[0]) {
4238 assert(!merge_trees[0] && !merge_trees[1] && !merge_trees[2]);
4239 renames->cached_pairs_valid_side = 0; /* neither side valid */
4240 return;
4241 }
4242
4243 /*
4244 * Handle other cases; note that merge_trees[0..2] will only
4245 * be NULL if opti is, or if all three were manually set to
4246 * NULL by e.g. rename/rename(1to1) handling.
4247 */
64aceb6d
EN
4248 assert(merge_trees[0] && merge_trees[1] && merge_trees[2]);
4249
4250 /* Check if we meet a condition for re-using cached_pairs */
4251 if (oideq(&merge_base->object.oid, &merge_trees[2]->object.oid) &&
4252 oideq(&side1->object.oid, &result->tree->object.oid))
4253 renames->cached_pairs_valid_side = MERGE_SIDE1;
4254 else if (oideq(&merge_base->object.oid, &merge_trees[1]->object.oid) &&
4255 oideq(&side2->object.oid, &result->tree->object.oid))
4256 renames->cached_pairs_valid_side = MERGE_SIDE2;
4257 else
4258 renames->cached_pairs_valid_side = 0; /* neither side valid */
4259}
4260
04af1879
EN
4261/*** Function Grouping: merge_incore_*() and their internal variants ***/
4262
231e2dd4
EN
4263/*
4264 * Originally from merge_trees_internal(); heavily adapted, though.
4265 */
4266static void merge_ort_nonrecursive_internal(struct merge_options *opt,
4267 struct tree *merge_base,
4268 struct tree *side1,
4269 struct tree *side2,
4270 struct merge_result *result)
4271{
4272 struct object_id working_tree_oid;
4273
3639dfb3
EN
4274 if (opt->subtree_shift) {
4275 side2 = shift_tree_object(opt->repo, side1, side2,
4276 opt->subtree_shift);
4277 merge_base = shift_tree_object(opt->repo, side1, merge_base,
4278 opt->subtree_shift);
4279 }
4280
557ac035 4281 trace2_region_enter("merge", "collect_merge_info", opt->repo);
0c0d705b
EN
4282 if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
4283 /*
4284 * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
4285 * base, and 2-3) the trees for the two trees we're merging.
4286 */
4287 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
4288 oid_to_hex(&merge_base->object.oid),
4289 oid_to_hex(&side1->object.oid),
4290 oid_to_hex(&side2->object.oid));
4291 result->clean = -1;
4292 return;
4293 }
557ac035 4294 trace2_region_leave("merge", "collect_merge_info", opt->repo);
0c0d705b 4295
557ac035 4296 trace2_region_enter("merge", "renames", opt->repo);
231e2dd4
EN
4297 result->clean = detect_and_process_renames(opt, merge_base,
4298 side1, side2);
557ac035
EN
4299 trace2_region_leave("merge", "renames", opt->repo);
4300
4301 trace2_region_enter("merge", "process_entries", opt->repo);
231e2dd4 4302 process_entries(opt, &working_tree_oid);
557ac035 4303 trace2_region_leave("merge", "process_entries", opt->repo);
231e2dd4
EN
4304
4305 /* Set return values */
4306 result->tree = parse_tree_indirect(&working_tree_oid);
4307 /* existence of conflicted entries implies unclean */
4308 result->clean &= strmap_empty(&opt->priv->conflicted);
4309 if (!opt->priv->call_depth) {
4310 result->priv = opt->priv;
19ceb486 4311 result->_properly_initialized = RESULT_INITIALIZED;
231e2dd4
EN
4312 opt->priv = NULL;
4313 }
4314}
4315
8119214f
EN
4316/*
4317 * Originally from merge_recursive_internal(); somewhat adapted, though.
4318 */
4319static void merge_ort_internal(struct merge_options *opt,
4320 struct commit_list *merge_bases,
4321 struct commit *h1,
4322 struct commit *h2,
4323 struct merge_result *result)
4324{
4325 struct commit_list *iter;
4326 struct commit *merged_merge_bases;
4327 const char *ancestor_name;
4328 struct strbuf merge_base_abbrev = STRBUF_INIT;
4329
4330 if (!merge_bases) {
4331 merge_bases = get_merge_bases(h1, h2);
4332 /* See merge-ort.h:merge_incore_recursive() declaration NOTE */
4333 merge_bases = reverse_commit_list(merge_bases);
4334 }
4335
4336 merged_merge_bases = pop_commit(&merge_bases);
4337 if (merged_merge_bases == NULL) {
4338 /* if there is no common ancestor, use an empty tree */
4339 struct tree *tree;
4340
4341 tree = lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);
4342 merged_merge_bases = make_virtual_commit(opt->repo, tree,
4343 "ancestor");
4344 ancestor_name = "empty tree";
4345 } else if (merge_bases) {
4346 ancestor_name = "merged common ancestors";
4347 } else {
4348 strbuf_add_unique_abbrev(&merge_base_abbrev,
4349 &merged_merge_bases->object.oid,
4350 DEFAULT_ABBREV);
4351 ancestor_name = merge_base_abbrev.buf;
4352 }
4353
4354 for (iter = merge_bases; iter; iter = iter->next) {
4355 const char *saved_b1, *saved_b2;
4356 struct commit *prev = merged_merge_bases;
4357
4358 opt->priv->call_depth++;
4359 /*
4360 * When the merge fails, the result contains files
4361 * with conflict markers. The cleanness flag is
4362 * ignored (unless indicating an error), it was never
4363 * actually used, as result of merge_trees has always
4364 * overwritten it: the committed "conflicts" were
4365 * already resolved.
4366 */
4367 saved_b1 = opt->branch1;
4368 saved_b2 = opt->branch2;
4369 opt->branch1 = "Temporary merge branch 1";
4370 opt->branch2 = "Temporary merge branch 2";
4371 merge_ort_internal(opt, NULL, prev, iter->item, result);
4372 if (result->clean < 0)
4373 return;
4374 opt->branch1 = saved_b1;
4375 opt->branch2 = saved_b2;
4376 opt->priv->call_depth--;
4377
4378 merged_merge_bases = make_virtual_commit(opt->repo,
4379 result->tree,
4380 "merged tree");
4381 commit_list_insert(prev, &merged_merge_bases->parents);
4382 commit_list_insert(iter->item,
4383 &merged_merge_bases->parents->next);
4384
4385 clear_or_reinit_internal_opts(opt->priv, 1);
4386 }
4387
4388 opt->ancestor = ancestor_name;
4389 merge_ort_nonrecursive_internal(opt,
4390 repo_get_commit_tree(opt->repo,
4391 merged_merge_bases),
4392 repo_get_commit_tree(opt->repo, h1),
4393 repo_get_commit_tree(opt->repo, h2),
4394 result);
4395 strbuf_release(&merge_base_abbrev);
4396 opt->ancestor = NULL; /* avoid accidental re-use of opt->ancestor */
4397}
4398
17e5574b
EN
4399void merge_incore_nonrecursive(struct merge_options *opt,
4400 struct tree *merge_base,
4401 struct tree *side1,
4402 struct tree *side2,
4403 struct merge_result *result)
4404{
557ac035
EN
4405 trace2_region_enter("merge", "incore_nonrecursive", opt->repo);
4406
4407 trace2_region_enter("merge", "merge_start", opt->repo);
231e2dd4 4408 assert(opt->ancestor != NULL);
64aceb6d 4409 merge_check_renames_reusable(opt, result, merge_base, side1, side2);
231e2dd4 4410 merge_start(opt, result);
64aceb6d
EN
4411 /*
4412 * Record the trees used in this merge, so if there's a next merge in
4413 * a cherry-pick or rebase sequence it might be able to take advantage
4414 * of the cached_pairs in that next merge.
4415 */
4416 opt->priv->renames.merge_trees[0] = merge_base;
4417 opt->priv->renames.merge_trees[1] = side1;
4418 opt->priv->renames.merge_trees[2] = side2;
557ac035
EN
4419 trace2_region_leave("merge", "merge_start", opt->repo);
4420
231e2dd4 4421 merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
557ac035 4422 trace2_region_leave("merge", "incore_nonrecursive", opt->repo);
17e5574b
EN
4423}
4424
4425void merge_incore_recursive(struct merge_options *opt,
4426 struct commit_list *merge_bases,
4427 struct commit *side1,
4428 struct commit *side2,
4429 struct merge_result *result)
4430{
557ac035
EN
4431 trace2_region_enter("merge", "incore_recursive", opt->repo);
4432
8119214f
EN
4433 /* We set the ancestor label based on the merge_bases */
4434 assert(opt->ancestor == NULL);
4435
557ac035 4436 trace2_region_enter("merge", "merge_start", opt->repo);
8119214f 4437 merge_start(opt, result);
557ac035
EN
4438 trace2_region_leave("merge", "merge_start", opt->repo);
4439
8119214f 4440 merge_ort_internal(opt, merge_bases, side1, side2, result);
557ac035 4441 trace2_region_leave("merge", "incore_recursive", opt->repo);
17e5574b 4442}