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