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