merge-recursive: switch from (oid,mode) pairs to a diff_filespec
[git] / merge-recursive.c
1 /*
2  * Recursive Merge algorithm stolen from git-merge-recursive.py by
3  * Fredrik Kuivinen.
4  * The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006
5  */
6 #include "cache.h"
7 #include "config.h"
8 #include "advice.h"
9 #include "lockfile.h"
10 #include "cache-tree.h"
11 #include "object-store.h"
12 #include "repository.h"
13 #include "commit.h"
14 #include "blob.h"
15 #include "builtin.h"
16 #include "tree-walk.h"
17 #include "diff.h"
18 #include "diffcore.h"
19 #include "tag.h"
20 #include "alloc.h"
21 #include "unpack-trees.h"
22 #include "string-list.h"
23 #include "xdiff-interface.h"
24 #include "ll-merge.h"
25 #include "attr.h"
26 #include "merge-recursive.h"
27 #include "dir.h"
28 #include "submodule.h"
29 #include "revision.h"
30 #include "commit-reach.h"
31
32 struct path_hashmap_entry {
33         struct hashmap_entry e;
34         char path[FLEX_ARRAY];
35 };
36
37 static int path_hashmap_cmp(const void *cmp_data,
38                             const void *entry,
39                             const void *entry_or_key,
40                             const void *keydata)
41 {
42         const struct path_hashmap_entry *a = entry;
43         const struct path_hashmap_entry *b = entry_or_key;
44         const char *key = keydata;
45
46         if (ignore_case)
47                 return strcasecmp(a->path, key ? key : b->path);
48         else
49                 return strcmp(a->path, key ? key : b->path);
50 }
51
52 static unsigned int path_hash(const char *path)
53 {
54         return ignore_case ? strihash(path) : strhash(path);
55 }
56
57 static struct dir_rename_entry *dir_rename_find_entry(struct hashmap *hashmap,
58                                                       char *dir)
59 {
60         struct dir_rename_entry key;
61
62         if (dir == NULL)
63                 return NULL;
64         hashmap_entry_init(&key, strhash(dir));
65         key.dir = dir;
66         return hashmap_get(hashmap, &key, NULL);
67 }
68
69 static int dir_rename_cmp(const void *unused_cmp_data,
70                           const void *entry,
71                           const void *entry_or_key,
72                           const void *unused_keydata)
73 {
74         const struct dir_rename_entry *e1 = entry;
75         const struct dir_rename_entry *e2 = entry_or_key;
76
77         return strcmp(e1->dir, e2->dir);
78 }
79
80 static void dir_rename_init(struct hashmap *map)
81 {
82         hashmap_init(map, dir_rename_cmp, NULL, 0);
83 }
84
85 static void dir_rename_entry_init(struct dir_rename_entry *entry,
86                                   char *directory)
87 {
88         hashmap_entry_init(entry, strhash(directory));
89         entry->dir = directory;
90         entry->non_unique_new_dir = 0;
91         strbuf_init(&entry->new_dir, 0);
92         string_list_init(&entry->possible_new_dirs, 0);
93 }
94
95 static struct collision_entry *collision_find_entry(struct hashmap *hashmap,
96                                                     char *target_file)
97 {
98         struct collision_entry key;
99
100         hashmap_entry_init(&key, strhash(target_file));
101         key.target_file = target_file;
102         return hashmap_get(hashmap, &key, NULL);
103 }
104
105 static int collision_cmp(void *unused_cmp_data,
106                          const struct collision_entry *e1,
107                          const struct collision_entry *e2,
108                          const void *unused_keydata)
109 {
110         return strcmp(e1->target_file, e2->target_file);
111 }
112
113 static void collision_init(struct hashmap *map)
114 {
115         hashmap_init(map, (hashmap_cmp_fn) collision_cmp, NULL, 0);
116 }
117
118 static void flush_output(struct merge_options *opt)
119 {
120         if (opt->buffer_output < 2 && opt->obuf.len) {
121                 fputs(opt->obuf.buf, stdout);
122                 strbuf_reset(&opt->obuf);
123         }
124 }
125
126 static int err(struct merge_options *opt, const char *err, ...)
127 {
128         va_list params;
129
130         if (opt->buffer_output < 2)
131                 flush_output(opt);
132         else {
133                 strbuf_complete(&opt->obuf, '\n');
134                 strbuf_addstr(&opt->obuf, "error: ");
135         }
136         va_start(params, err);
137         strbuf_vaddf(&opt->obuf, err, params);
138         va_end(params);
139         if (opt->buffer_output > 1)
140                 strbuf_addch(&opt->obuf, '\n');
141         else {
142                 error("%s", opt->obuf.buf);
143                 strbuf_reset(&opt->obuf);
144         }
145
146         return -1;
147 }
148
149 static struct tree *shift_tree_object(struct repository *repo,
150                                       struct tree *one, struct tree *two,
151                                       const char *subtree_shift)
152 {
153         struct object_id shifted;
154
155         if (!*subtree_shift) {
156                 shift_tree(&one->object.oid, &two->object.oid, &shifted, 0);
157         } else {
158                 shift_tree_by(&one->object.oid, &two->object.oid, &shifted,
159                               subtree_shift);
160         }
161         if (oideq(&two->object.oid, &shifted))
162                 return two;
163         return lookup_tree(repo, &shifted);
164 }
165
166 static struct commit *make_virtual_commit(struct repository *repo,
167                                           struct tree *tree,
168                                           const char *comment)
169 {
170         struct commit *commit = alloc_commit_node(repo);
171
172         set_merge_remote_desc(commit, comment, (struct object *)commit);
173         commit->maybe_tree = tree;
174         commit->object.parsed = 1;
175         return commit;
176 }
177
178 /*
179  * Since we use get_tree_entry(), which does not put the read object into
180  * the object pool, we cannot rely on a == b.
181  */
182 static int oid_eq(const struct object_id *a, const struct object_id *b)
183 {
184         if (!a && !b)
185                 return 2;
186         return a && b && oideq(a, b);
187 }
188
189 enum rename_type {
190         RENAME_NORMAL = 0,
191         RENAME_VIA_DIR,
192         RENAME_ADD,
193         RENAME_DELETE,
194         RENAME_ONE_FILE_TO_ONE,
195         RENAME_ONE_FILE_TO_TWO,
196         RENAME_TWO_FILES_TO_ONE
197 };
198
199 /*
200  * Since we want to write the index eventually, we cannot reuse the index
201  * for these (temporary) data.
202  */
203 struct stage_data {
204         struct diff_filespec stages[4]; /* mostly for oid & mode; maybe path */
205         struct rename_conflict_info *rename_conflict_info;
206         unsigned processed:1;
207 };
208
209 struct rename {
210         struct diff_filepair *pair;
211         const char *branch; /* branch that the rename occurred on */
212         /*
213          * Purpose of src_entry and dst_entry:
214          *
215          * If 'before' is renamed to 'after' then src_entry will contain
216          * the versions of 'before' from the merge_base, HEAD, and MERGE in
217          * stages 1, 2, and 3; dst_entry will contain the respective
218          * versions of 'after' in corresponding locations.  Thus, we have a
219          * total of six modes and oids, though some will be null.  (Stage 0
220          * is ignored; we're interested in handling conflicts.)
221          *
222          * Since we don't turn on break-rewrites by default, neither
223          * src_entry nor dst_entry can have all three of their stages have
224          * non-null oids, meaning at most four of the six will be non-null.
225          * Also, since this is a rename, both src_entry and dst_entry will
226          * have at least one non-null oid, meaning at least two will be
227          * non-null.  Of the six oids, a typical rename will have three be
228          * non-null.  Only two implies a rename/delete, and four implies a
229          * rename/add.
230          */
231         struct stage_data *src_entry;
232         struct stage_data *dst_entry;
233         unsigned add_turned_into_rename:1;
234         unsigned processed:1;
235 };
236
237 struct rename_conflict_info {
238         enum rename_type rename_type;
239         struct rename *ren1;
240         struct rename *ren2;
241 };
242
243 static inline void setup_rename_conflict_info(enum rename_type rename_type,
244                                               struct merge_options *opt,
245                                               struct rename *ren1,
246                                               struct rename *ren2)
247 {
248         struct rename_conflict_info *ci;
249
250         /*
251          * When we have two renames involved, it's easiest to get the
252          * correct things into stage 2 and 3, and to make sure that the
253          * content merge puts HEAD before the other branch if we just
254          * ensure that branch1 == opt->branch1.  So, simply flip arguments
255          * around if we don't have that.
256          */
257         if (ren2 && ren1->branch != opt->branch1) {
258                 setup_rename_conflict_info(rename_type, opt, ren2, ren1);
259                 return;
260         }
261
262         ci = xcalloc(1, sizeof(struct rename_conflict_info));
263         ci->rename_type = rename_type;
264         ci->ren1 = ren1;
265         ci->ren2 = ren2;
266
267         ci->ren1->dst_entry->processed = 0;
268         ci->ren1->dst_entry->rename_conflict_info = ci;
269         if (ren2) {
270                 ci->ren2->dst_entry->rename_conflict_info = ci;
271         }
272 }
273
274 static int show(struct merge_options *opt, int v)
275 {
276         return (!opt->call_depth && opt->verbosity >= v) || opt->verbosity >= 5;
277 }
278
279 __attribute__((format (printf, 3, 4)))
280 static void output(struct merge_options *opt, int v, const char *fmt, ...)
281 {
282         va_list ap;
283
284         if (!show(opt, v))
285                 return;
286
287         strbuf_addchars(&opt->obuf, ' ', opt->call_depth * 2);
288
289         va_start(ap, fmt);
290         strbuf_vaddf(&opt->obuf, fmt, ap);
291         va_end(ap);
292
293         strbuf_addch(&opt->obuf, '\n');
294         if (!opt->buffer_output)
295                 flush_output(opt);
296 }
297
298 static void output_commit_title(struct merge_options *opt, struct commit *commit)
299 {
300         struct merge_remote_desc *desc;
301
302         strbuf_addchars(&opt->obuf, ' ', opt->call_depth * 2);
303         desc = merge_remote_util(commit);
304         if (desc)
305                 strbuf_addf(&opt->obuf, "virtual %s\n", desc->name);
306         else {
307                 strbuf_add_unique_abbrev(&opt->obuf, &commit->object.oid,
308                                          DEFAULT_ABBREV);
309                 strbuf_addch(&opt->obuf, ' ');
310                 if (parse_commit(commit) != 0)
311                         strbuf_addstr(&opt->obuf, _("(bad commit)\n"));
312                 else {
313                         const char *title;
314                         const char *msg = get_commit_buffer(commit, NULL);
315                         int len = find_commit_subject(msg, &title);
316                         if (len)
317                                 strbuf_addf(&opt->obuf, "%.*s\n", len, title);
318                         unuse_commit_buffer(commit, msg);
319                 }
320         }
321         flush_output(opt);
322 }
323
324 static int add_cacheinfo(struct merge_options *opt,
325                          const struct diff_filespec *blob,
326                          const char *path, int stage, int refresh, int options)
327 {
328         struct index_state *istate = opt->repo->index;
329         struct cache_entry *ce;
330         int ret;
331
332         ce = make_cache_entry(istate, blob->mode, &blob->oid, path, stage, 0);
333         if (!ce)
334                 return err(opt, _("add_cacheinfo failed for path '%s'; merge aborting."), path);
335
336         ret = add_index_entry(istate, ce, options);
337         if (refresh) {
338                 struct cache_entry *nce;
339
340                 nce = refresh_cache_entry(istate, ce,
341                                           CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING);
342                 if (!nce)
343                         return err(opt, _("add_cacheinfo failed to refresh for path '%s'; merge aborting."), path);
344                 if (nce != ce)
345                         ret = add_index_entry(istate, nce, options);
346         }
347         return ret;
348 }
349
350 static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
351 {
352         parse_tree(tree);
353         init_tree_desc(desc, tree->buffer, tree->size);
354 }
355
356 static int unpack_trees_start(struct merge_options *opt,
357                               struct tree *common,
358                               struct tree *head,
359                               struct tree *merge)
360 {
361         int rc;
362         struct tree_desc t[3];
363         struct index_state tmp_index = { NULL };
364
365         memset(&opt->unpack_opts, 0, sizeof(opt->unpack_opts));
366         if (opt->call_depth)
367                 opt->unpack_opts.index_only = 1;
368         else
369                 opt->unpack_opts.update = 1;
370         opt->unpack_opts.merge = 1;
371         opt->unpack_opts.head_idx = 2;
372         opt->unpack_opts.fn = threeway_merge;
373         opt->unpack_opts.src_index = opt->repo->index;
374         opt->unpack_opts.dst_index = &tmp_index;
375         opt->unpack_opts.aggressive = !merge_detect_rename(opt);
376         setup_unpack_trees_porcelain(&opt->unpack_opts, "merge");
377
378         init_tree_desc_from_tree(t+0, common);
379         init_tree_desc_from_tree(t+1, head);
380         init_tree_desc_from_tree(t+2, merge);
381
382         rc = unpack_trees(3, t, &opt->unpack_opts);
383         cache_tree_free(&opt->repo->index->cache_tree);
384
385         /*
386          * Update opt->repo->index to match the new results, AFTER saving a copy
387          * in opt->orig_index.  Update src_index to point to the saved copy.
388          * (verify_uptodate() checks src_index, and the original index is
389          * the one that had the necessary modification timestamps.)
390          */
391         opt->orig_index = *opt->repo->index;
392         *opt->repo->index = tmp_index;
393         opt->unpack_opts.src_index = &opt->orig_index;
394
395         return rc;
396 }
397
398 static void unpack_trees_finish(struct merge_options *opt)
399 {
400         discard_index(&opt->orig_index);
401         clear_unpack_trees_porcelain(&opt->unpack_opts);
402 }
403
404 struct tree *write_tree_from_memory(struct merge_options *opt)
405 {
406         struct tree *result = NULL;
407         struct index_state *istate = opt->repo->index;
408
409         if (unmerged_index(istate)) {
410                 int i;
411                 fprintf(stderr, "BUG: There are unmerged index entries:\n");
412                 for (i = 0; i < istate->cache_nr; i++) {
413                         const struct cache_entry *ce = istate->cache[i];
414                         if (ce_stage(ce))
415                                 fprintf(stderr, "BUG: %d %.*s\n", ce_stage(ce),
416                                         (int)ce_namelen(ce), ce->name);
417                 }
418                 BUG("unmerged index entries in merge-recursive.c");
419         }
420
421         if (!istate->cache_tree)
422                 istate->cache_tree = cache_tree();
423
424         if (!cache_tree_fully_valid(istate->cache_tree) &&
425             cache_tree_update(istate, 0) < 0) {
426                 err(opt, _("error building trees"));
427                 return NULL;
428         }
429
430         result = lookup_tree(opt->repo, &istate->cache_tree->oid);
431
432         return result;
433 }
434
435 static int save_files_dirs(const struct object_id *oid,
436                            struct strbuf *base, const char *path,
437                            unsigned int mode, int stage, void *context)
438 {
439         struct path_hashmap_entry *entry;
440         int baselen = base->len;
441         struct merge_options *opt = context;
442
443         strbuf_addstr(base, path);
444
445         FLEX_ALLOC_MEM(entry, path, base->buf, base->len);
446         hashmap_entry_init(entry, path_hash(entry->path));
447         hashmap_add(&opt->current_file_dir_set, entry);
448
449         strbuf_setlen(base, baselen);
450         return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
451 }
452
453 static void get_files_dirs(struct merge_options *opt, struct tree *tree)
454 {
455         struct pathspec match_all;
456         memset(&match_all, 0, sizeof(match_all));
457         read_tree_recursive(the_repository, tree, "", 0, 0,
458                             &match_all, save_files_dirs, opt);
459 }
460
461 static int get_tree_entry_if_blob(const struct object_id *tree,
462                                   const char *path,
463                                   struct diff_filespec *dfs)
464 {
465         int ret;
466
467         ret = get_tree_entry(tree, path, &dfs->oid, &dfs->mode);
468         if (S_ISDIR(dfs->mode)) {
469                 oidcpy(&dfs->oid, &null_oid);
470                 dfs->mode = 0;
471         }
472         return ret;
473 }
474
475 /*
476  * Returns an index_entry instance which doesn't have to correspond to
477  * a real cache entry in Git's index.
478  */
479 static struct stage_data *insert_stage_data(const char *path,
480                 struct tree *o, struct tree *a, struct tree *b,
481                 struct string_list *entries)
482 {
483         struct string_list_item *item;
484         struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
485         get_tree_entry_if_blob(&o->object.oid, path, &e->stages[1]);
486         get_tree_entry_if_blob(&a->object.oid, path, &e->stages[2]);
487         get_tree_entry_if_blob(&b->object.oid, path, &e->stages[3]);
488         item = string_list_insert(entries, path);
489         item->util = e;
490         return e;
491 }
492
493 /*
494  * Create a dictionary mapping file names to stage_data objects. The
495  * dictionary contains one entry for every path with a non-zero stage entry.
496  */
497 static struct string_list *get_unmerged(struct index_state *istate)
498 {
499         struct string_list *unmerged = xcalloc(1, sizeof(struct string_list));
500         int i;
501
502         unmerged->strdup_strings = 1;
503
504         for (i = 0; i < istate->cache_nr; i++) {
505                 struct string_list_item *item;
506                 struct stage_data *e;
507                 const struct cache_entry *ce = istate->cache[i];
508                 if (!ce_stage(ce))
509                         continue;
510
511                 item = string_list_lookup(unmerged, ce->name);
512                 if (!item) {
513                         item = string_list_insert(unmerged, ce->name);
514                         item->util = xcalloc(1, sizeof(struct stage_data));
515                 }
516                 e = item->util;
517                 e->stages[ce_stage(ce)].mode = ce->ce_mode;
518                 oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid);
519         }
520
521         return unmerged;
522 }
523
524 static int string_list_df_name_compare(const char *one, const char *two)
525 {
526         int onelen = strlen(one);
527         int twolen = strlen(two);
528         /*
529          * Here we only care that entries for D/F conflicts are
530          * adjacent, in particular with the file of the D/F conflict
531          * appearing before files below the corresponding directory.
532          * The order of the rest of the list is irrelevant for us.
533          *
534          * To achieve this, we sort with df_name_compare and provide
535          * the mode S_IFDIR so that D/F conflicts will sort correctly.
536          * We use the mode S_IFDIR for everything else for simplicity,
537          * since in other cases any changes in their order due to
538          * sorting cause no problems for us.
539          */
540         int cmp = df_name_compare(one, onelen, S_IFDIR,
541                                   two, twolen, S_IFDIR);
542         /*
543          * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
544          * that 'foo' comes before 'foo/bar'.
545          */
546         if (cmp)
547                 return cmp;
548         return onelen - twolen;
549 }
550
551 static void record_df_conflict_files(struct merge_options *opt,
552                                      struct string_list *entries)
553 {
554         /* If there is a D/F conflict and the file for such a conflict
555          * currently exists in the working tree, we want to allow it to be
556          * removed to make room for the corresponding directory if needed.
557          * The files underneath the directories of such D/F conflicts will
558          * be processed before the corresponding file involved in the D/F
559          * conflict.  If the D/F directory ends up being removed by the
560          * merge, then we won't have to touch the D/F file.  If the D/F
561          * directory needs to be written to the working copy, then the D/F
562          * file will simply be removed (in make_room_for_path()) to make
563          * room for the necessary paths.  Note that if both the directory
564          * and the file need to be present, then the D/F file will be
565          * reinstated with a new unique name at the time it is processed.
566          */
567         struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP;
568         const char *last_file = NULL;
569         int last_len = 0;
570         int i;
571
572         /*
573          * If we're merging merge-bases, we don't want to bother with
574          * any working directory changes.
575          */
576         if (opt->call_depth)
577                 return;
578
579         /* Ensure D/F conflicts are adjacent in the entries list. */
580         for (i = 0; i < entries->nr; i++) {
581                 struct string_list_item *next = &entries->items[i];
582                 string_list_append(&df_sorted_entries, next->string)->util =
583                                    next->util;
584         }
585         df_sorted_entries.cmp = string_list_df_name_compare;
586         string_list_sort(&df_sorted_entries);
587
588         string_list_clear(&opt->df_conflict_file_set, 1);
589         for (i = 0; i < df_sorted_entries.nr; i++) {
590                 const char *path = df_sorted_entries.items[i].string;
591                 int len = strlen(path);
592                 struct stage_data *e = df_sorted_entries.items[i].util;
593
594                 /*
595                  * Check if last_file & path correspond to a D/F conflict;
596                  * i.e. whether path is last_file+'/'+<something>.
597                  * If so, record that it's okay to remove last_file to make
598                  * room for path and friends if needed.
599                  */
600                 if (last_file &&
601                     len > last_len &&
602                     memcmp(path, last_file, last_len) == 0 &&
603                     path[last_len] == '/') {
604                         string_list_insert(&opt->df_conflict_file_set, last_file);
605                 }
606
607                 /*
608                  * Determine whether path could exist as a file in the
609                  * working directory as a possible D/F conflict.  This
610                  * will only occur when it exists in stage 2 as a
611                  * file.
612                  */
613                 if (S_ISREG(e->stages[2].mode) || S_ISLNK(e->stages[2].mode)) {
614                         last_file = path;
615                         last_len = len;
616                 } else {
617                         last_file = NULL;
618                 }
619         }
620         string_list_clear(&df_sorted_entries, 0);
621 }
622
623 static int update_stages(struct merge_options *opt, const char *path,
624                          const struct diff_filespec *o,
625                          const struct diff_filespec *a,
626                          const struct diff_filespec *b)
627 {
628
629         /*
630          * NOTE: It is usually a bad idea to call update_stages on a path
631          * before calling update_file on that same path, since it can
632          * sometimes lead to spurious "refusing to lose untracked file..."
633          * messages from update_file (via make_room_for path via
634          * would_lose_untracked).  Instead, reverse the order of the calls
635          * (executing update_file first and then update_stages).
636          */
637         int clear = 1;
638         int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK;
639         if (clear)
640                 if (remove_file_from_index(opt->repo->index, path))
641                         return -1;
642         if (o)
643                 if (add_cacheinfo(opt, o, path, 1, 0, options))
644                         return -1;
645         if (a)
646                 if (add_cacheinfo(opt, a, path, 2, 0, options))
647                         return -1;
648         if (b)
649                 if (add_cacheinfo(opt, b, path, 3, 0, options))
650                         return -1;
651         return 0;
652 }
653
654 static void update_entry(struct stage_data *entry,
655                          struct diff_filespec *o,
656                          struct diff_filespec *a,
657                          struct diff_filespec *b)
658 {
659         entry->processed = 0;
660         entry->stages[1].mode = o->mode;
661         entry->stages[2].mode = a->mode;
662         entry->stages[3].mode = b->mode;
663         oidcpy(&entry->stages[1].oid, &o->oid);
664         oidcpy(&entry->stages[2].oid, &a->oid);
665         oidcpy(&entry->stages[3].oid, &b->oid);
666 }
667
668 static int remove_file(struct merge_options *opt, int clean,
669                        const char *path, int no_wd)
670 {
671         int update_cache = opt->call_depth || clean;
672         int update_working_directory = !opt->call_depth && !no_wd;
673
674         if (update_cache) {
675                 if (remove_file_from_index(opt->repo->index, path))
676                         return -1;
677         }
678         if (update_working_directory) {
679                 if (ignore_case) {
680                         struct cache_entry *ce;
681                         ce = index_file_exists(opt->repo->index, path, strlen(path),
682                                                ignore_case);
683                         if (ce && ce_stage(ce) == 0 && strcmp(path, ce->name))
684                                 return 0;
685                 }
686                 if (remove_path(path))
687                         return -1;
688         }
689         return 0;
690 }
691
692 /* add a string to a strbuf, but converting "/" to "_" */
693 static void add_flattened_path(struct strbuf *out, const char *s)
694 {
695         size_t i = out->len;
696         strbuf_addstr(out, s);
697         for (; i < out->len; i++)
698                 if (out->buf[i] == '/')
699                         out->buf[i] = '_';
700 }
701
702 static char *unique_path(struct merge_options *opt, const char *path, const char *branch)
703 {
704         struct path_hashmap_entry *entry;
705         struct strbuf newpath = STRBUF_INIT;
706         int suffix = 0;
707         size_t base_len;
708
709         strbuf_addf(&newpath, "%s~", path);
710         add_flattened_path(&newpath, branch);
711
712         base_len = newpath.len;
713         while (hashmap_get_from_hash(&opt->current_file_dir_set,
714                                      path_hash(newpath.buf), newpath.buf) ||
715                (!opt->call_depth && file_exists(newpath.buf))) {
716                 strbuf_setlen(&newpath, base_len);
717                 strbuf_addf(&newpath, "_%d", suffix++);
718         }
719
720         FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len);
721         hashmap_entry_init(entry, path_hash(entry->path));
722         hashmap_add(&opt->current_file_dir_set, entry);
723         return strbuf_detach(&newpath, NULL);
724 }
725
726 /**
727  * Check whether a directory in the index is in the way of an incoming
728  * file.  Return 1 if so.  If check_working_copy is non-zero, also
729  * check the working directory.  If empty_ok is non-zero, also return
730  * 0 in the case where the working-tree dir exists but is empty.
731  */
732 static int dir_in_way(struct index_state *istate, const char *path,
733                       int check_working_copy, int empty_ok)
734 {
735         int pos;
736         struct strbuf dirpath = STRBUF_INIT;
737         struct stat st;
738
739         strbuf_addstr(&dirpath, path);
740         strbuf_addch(&dirpath, '/');
741
742         pos = index_name_pos(istate, dirpath.buf, dirpath.len);
743
744         if (pos < 0)
745                 pos = -1 - pos;
746         if (pos < istate->cache_nr &&
747             !strncmp(dirpath.buf, istate->cache[pos]->name, dirpath.len)) {
748                 strbuf_release(&dirpath);
749                 return 1;
750         }
751
752         strbuf_release(&dirpath);
753         return check_working_copy && !lstat(path, &st) && S_ISDIR(st.st_mode) &&
754                 !(empty_ok && is_empty_dir(path));
755 }
756
757 /*
758  * Returns whether path was tracked in the index before the merge started,
759  * and its oid and mode match the specified values
760  */
761 static int was_tracked_and_matches(struct merge_options *opt, const char *path,
762                                    const struct diff_filespec *blob)
763 {
764         int pos = index_name_pos(&opt->orig_index, path, strlen(path));
765         struct cache_entry *ce;
766
767         if (0 > pos)
768                 /* we were not tracking this path before the merge */
769                 return 0;
770
771         /* See if the file we were tracking before matches */
772         ce = opt->orig_index.cache[pos];
773         return (oid_eq(&ce->oid, &blob->oid) && ce->ce_mode == blob->mode);
774 }
775
776 /*
777  * Returns whether path was tracked in the index before the merge started
778  */
779 static int was_tracked(struct merge_options *opt, const char *path)
780 {
781         int pos = index_name_pos(&opt->orig_index, path, strlen(path));
782
783         if (0 <= pos)
784                 /* we were tracking this path before the merge */
785                 return 1;
786
787         return 0;
788 }
789
790 static int would_lose_untracked(struct merge_options *opt, const char *path)
791 {
792         struct index_state *istate = opt->repo->index;
793
794         /*
795          * This may look like it can be simplified to:
796          *   return !was_tracked(opt, path) && file_exists(path)
797          * but it can't.  This function needs to know whether path was in
798          * the working tree due to EITHER having been tracked in the index
799          * before the merge OR having been put into the working copy and
800          * index by unpack_trees().  Due to that either-or requirement, we
801          * check the current index instead of the original one.
802          *
803          * Note that we do not need to worry about merge-recursive itself
804          * updating the index after unpack_trees() and before calling this
805          * function, because we strictly require all code paths in
806          * merge-recursive to update the working tree first and the index
807          * second.  Doing otherwise would break
808          * update_file()/would_lose_untracked(); see every comment in this
809          * file which mentions "update_stages".
810          */
811         int pos = index_name_pos(istate, path, strlen(path));
812
813         if (pos < 0)
814                 pos = -1 - pos;
815         while (pos < istate->cache_nr &&
816                !strcmp(path, istate->cache[pos]->name)) {
817                 /*
818                  * If stage #0, it is definitely tracked.
819                  * If it has stage #2 then it was tracked
820                  * before this merge started.  All other
821                  * cases the path was not tracked.
822                  */
823                 switch (ce_stage(istate->cache[pos])) {
824                 case 0:
825                 case 2:
826                         return 0;
827                 }
828                 pos++;
829         }
830         return file_exists(path);
831 }
832
833 static int was_dirty(struct merge_options *opt, const char *path)
834 {
835         struct cache_entry *ce;
836         int dirty = 1;
837
838         if (opt->call_depth || !was_tracked(opt, path))
839                 return !dirty;
840
841         ce = index_file_exists(opt->unpack_opts.src_index,
842                                path, strlen(path), ignore_case);
843         dirty = verify_uptodate(ce, &opt->unpack_opts) != 0;
844         return dirty;
845 }
846
847 static int make_room_for_path(struct merge_options *opt, const char *path)
848 {
849         int status, i;
850         const char *msg = _("failed to create path '%s'%s");
851
852         /* Unlink any D/F conflict files that are in the way */
853         for (i = 0; i < opt->df_conflict_file_set.nr; i++) {
854                 const char *df_path = opt->df_conflict_file_set.items[i].string;
855                 size_t pathlen = strlen(path);
856                 size_t df_pathlen = strlen(df_path);
857                 if (df_pathlen < pathlen &&
858                     path[df_pathlen] == '/' &&
859                     strncmp(path, df_path, df_pathlen) == 0) {
860                         output(opt, 3,
861                                _("Removing %s to make room for subdirectory\n"),
862                                df_path);
863                         unlink(df_path);
864                         unsorted_string_list_delete_item(&opt->df_conflict_file_set,
865                                                          i, 0);
866                         break;
867                 }
868         }
869
870         /* Make sure leading directories are created */
871         status = safe_create_leading_directories_const(path);
872         if (status) {
873                 if (status == SCLD_EXISTS)
874                         /* something else exists */
875                         return err(opt, msg, path, _(": perhaps a D/F conflict?"));
876                 return err(opt, msg, path, "");
877         }
878
879         /*
880          * Do not unlink a file in the work tree if we are not
881          * tracking it.
882          */
883         if (would_lose_untracked(opt, path))
884                 return err(opt, _("refusing to lose untracked file at '%s'"),
885                            path);
886
887         /* Successful unlink is good.. */
888         if (!unlink(path))
889                 return 0;
890         /* .. and so is no existing file */
891         if (errno == ENOENT)
892                 return 0;
893         /* .. but not some other error (who really cares what?) */
894         return err(opt, msg, path, _(": perhaps a D/F conflict?"));
895 }
896
897 static int update_file_flags(struct merge_options *opt,
898                              const struct diff_filespec *contents,
899                              const char *path,
900                              int update_cache,
901                              int update_wd)
902 {
903         int ret = 0;
904
905         if (opt->call_depth)
906                 update_wd = 0;
907
908         if (update_wd) {
909                 enum object_type type;
910                 void *buf;
911                 unsigned long size;
912
913                 if (S_ISGITLINK(contents->mode)) {
914                         /*
915                          * We may later decide to recursively descend into
916                          * the submodule directory and update its index
917                          * and/or work tree, but we do not do that now.
918                          */
919                         update_wd = 0;
920                         goto update_index;
921                 }
922
923                 buf = read_object_file(&contents->oid, &type, &size);
924                 if (!buf)
925                         return err(opt, _("cannot read object %s '%s'"),
926                                    oid_to_hex(&contents->oid), path);
927                 if (type != OBJ_BLOB) {
928                         ret = err(opt, _("blob expected for %s '%s'"),
929                                   oid_to_hex(&contents->oid), path);
930                         goto free_buf;
931                 }
932                 if (S_ISREG(contents->mode)) {
933                         struct strbuf strbuf = STRBUF_INIT;
934                         if (convert_to_working_tree(opt->repo->index, path, buf, size, &strbuf)) {
935                                 free(buf);
936                                 size = strbuf.len;
937                                 buf = strbuf_detach(&strbuf, NULL);
938                         }
939                 }
940
941                 if (make_room_for_path(opt, path) < 0) {
942                         update_wd = 0;
943                         goto free_buf;
944                 }
945                 if (S_ISREG(contents->mode) ||
946                     (!has_symlinks && S_ISLNK(contents->mode))) {
947                         int fd;
948                         int mode = (contents->mode & 0100 ? 0777 : 0666);
949
950                         fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
951                         if (fd < 0) {
952                                 ret = err(opt, _("failed to open '%s': %s"),
953                                           path, strerror(errno));
954                                 goto free_buf;
955                         }
956                         write_in_full(fd, buf, size);
957                         close(fd);
958                 } else if (S_ISLNK(contents->mode)) {
959                         char *lnk = xmemdupz(buf, size);
960                         safe_create_leading_directories_const(path);
961                         unlink(path);
962                         if (symlink(lnk, path))
963                                 ret = err(opt, _("failed to symlink '%s': %s"),
964                                           path, strerror(errno));
965                         free(lnk);
966                 } else
967                         ret = err(opt,
968                                   _("do not know what to do with %06o %s '%s'"),
969                                   contents->mode, oid_to_hex(&contents->oid), path);
970         free_buf:
971                 free(buf);
972         }
973 update_index:
974         if (!ret && update_cache)
975                 if (add_cacheinfo(opt, contents, path, 0, update_wd,
976                                   ADD_CACHE_OK_TO_ADD))
977                         return -1;
978         return ret;
979 }
980
981 static int update_file(struct merge_options *opt,
982                        int clean,
983                        const struct diff_filespec *contents,
984                        const char *path)
985 {
986         return update_file_flags(opt, contents, path,
987                                  opt->call_depth || clean, !opt->call_depth);
988 }
989
990 /* Low level file merging, update and removal */
991
992 struct merge_file_info {
993         struct diff_filespec blob; /* mostly use oid & mode; sometimes path */
994         unsigned clean:1,
995                  merge:1;
996 };
997
998 static int merge_3way(struct merge_options *opt,
999                       mmbuffer_t *result_buf,
1000                       const struct diff_filespec *o,
1001                       const struct diff_filespec *a,
1002                       const struct diff_filespec *b,
1003                       const char *branch1,
1004                       const char *branch2,
1005                       const int extra_marker_size)
1006 {
1007         mmfile_t orig, src1, src2;
1008         struct ll_merge_options ll_opts = {0};
1009         char *base_name, *name1, *name2;
1010         int merge_status;
1011
1012         ll_opts.renormalize = opt->renormalize;
1013         ll_opts.extra_marker_size = extra_marker_size;
1014         ll_opts.xdl_opts = opt->xdl_opts;
1015
1016         if (opt->call_depth) {
1017                 ll_opts.virtual_ancestor = 1;
1018                 ll_opts.variant = 0;
1019         } else {
1020                 switch (opt->recursive_variant) {
1021                 case MERGE_RECURSIVE_OURS:
1022                         ll_opts.variant = XDL_MERGE_FAVOR_OURS;
1023                         break;
1024                 case MERGE_RECURSIVE_THEIRS:
1025                         ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
1026                         break;
1027                 default:
1028                         ll_opts.variant = 0;
1029                         break;
1030                 }
1031         }
1032
1033         assert(a->path && b->path);
1034         if (strcmp(a->path, b->path) ||
1035             (opt->ancestor != NULL && strcmp(a->path, o->path) != 0)) {
1036                 base_name = opt->ancestor == NULL ? NULL :
1037                         mkpathdup("%s:%s", opt->ancestor, o->path);
1038                 name1 = mkpathdup("%s:%s", branch1, a->path);
1039                 name2 = mkpathdup("%s:%s", branch2, b->path);
1040         } else {
1041                 base_name = opt->ancestor == NULL ? NULL :
1042                         mkpathdup("%s", opt->ancestor);
1043                 name1 = mkpathdup("%s", branch1);
1044                 name2 = mkpathdup("%s", branch2);
1045         }
1046
1047         read_mmblob(&orig, &o->oid);
1048         read_mmblob(&src1, &a->oid);
1049         read_mmblob(&src2, &b->oid);
1050
1051         merge_status = ll_merge(result_buf, a->path, &orig, base_name,
1052                                 &src1, name1, &src2, name2,
1053                                 opt->repo->index, &ll_opts);
1054
1055         free(base_name);
1056         free(name1);
1057         free(name2);
1058         free(orig.ptr);
1059         free(src1.ptr);
1060         free(src2.ptr);
1061         return merge_status;
1062 }
1063
1064 static int find_first_merges(struct repository *repo,
1065                              struct object_array *result, const char *path,
1066                              struct commit *a, struct commit *b)
1067 {
1068         int i, j;
1069         struct object_array merges = OBJECT_ARRAY_INIT;
1070         struct commit *commit;
1071         int contains_another;
1072
1073         char merged_revision[42];
1074         const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1075                                    "--all", merged_revision, NULL };
1076         struct rev_info revs;
1077         struct setup_revision_opt rev_opts;
1078
1079         memset(result, 0, sizeof(struct object_array));
1080         memset(&rev_opts, 0, sizeof(rev_opts));
1081
1082         /* get all revisions that merge commit a */
1083         xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
1084                   oid_to_hex(&a->object.oid));
1085         repo_init_revisions(repo, &revs, NULL);
1086         rev_opts.submodule = path;
1087         /* FIXME: can't handle linked worktrees in submodules yet */
1088         revs.single_worktree = path != NULL;
1089         setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1090
1091         /* save all revisions from the above list that contain b */
1092         if (prepare_revision_walk(&revs))
1093                 die("revision walk setup failed");
1094         while ((commit = get_revision(&revs)) != NULL) {
1095                 struct object *o = &(commit->object);
1096                 if (in_merge_bases(b, commit))
1097                         add_object_array(o, NULL, &merges);
1098         }
1099         reset_revision_walk();
1100
1101         /* Now we've got all merges that contain a and b. Prune all
1102          * merges that contain another found merge and save them in
1103          * result.
1104          */
1105         for (i = 0; i < merges.nr; i++) {
1106                 struct commit *m1 = (struct commit *) merges.objects[i].item;
1107
1108                 contains_another = 0;
1109                 for (j = 0; j < merges.nr; j++) {
1110                         struct commit *m2 = (struct commit *) merges.objects[j].item;
1111                         if (i != j && in_merge_bases(m2, m1)) {
1112                                 contains_another = 1;
1113                                 break;
1114                         }
1115                 }
1116
1117                 if (!contains_another)
1118                         add_object_array(merges.objects[i].item, NULL, result);
1119         }
1120
1121         object_array_clear(&merges);
1122         return result->nr;
1123 }
1124
1125 static void print_commit(struct commit *commit)
1126 {
1127         struct strbuf sb = STRBUF_INIT;
1128         struct pretty_print_context ctx = {0};
1129         ctx.date_mode.type = DATE_NORMAL;
1130         format_commit_message(commit, " %h: %m %s", &sb, &ctx);
1131         fprintf(stderr, "%s\n", sb.buf);
1132         strbuf_release(&sb);
1133 }
1134
1135 static int is_valid(const struct diff_filespec *dfs)
1136 {
1137         return dfs->mode != 0 && !is_null_oid(&dfs->oid);
1138 }
1139
1140 static int merge_submodule(struct merge_options *opt,
1141                            struct object_id *result, const char *path,
1142                            const struct object_id *base, const struct object_id *a,
1143                            const struct object_id *b)
1144 {
1145         struct commit *commit_base, *commit_a, *commit_b;
1146         int parent_count;
1147         struct object_array merges;
1148
1149         int i;
1150         int search = !opt->call_depth;
1151
1152         /* store a in result in case we fail */
1153         oidcpy(result, a);
1154
1155         /* we can not handle deletion conflicts */
1156         if (is_null_oid(base))
1157                 return 0;
1158         if (is_null_oid(a))
1159                 return 0;
1160         if (is_null_oid(b))
1161                 return 0;
1162
1163         if (add_submodule_odb(path)) {
1164                 output(opt, 1, _("Failed to merge submodule %s (not checked out)"), path);
1165                 return 0;
1166         }
1167
1168         if (!(commit_base = lookup_commit_reference(opt->repo, base)) ||
1169             !(commit_a = lookup_commit_reference(opt->repo, a)) ||
1170             !(commit_b = lookup_commit_reference(opt->repo, b))) {
1171                 output(opt, 1, _("Failed to merge submodule %s (commits not present)"), path);
1172                 return 0;
1173         }
1174
1175         /* check whether both changes are forward */
1176         if (!in_merge_bases(commit_base, commit_a) ||
1177             !in_merge_bases(commit_base, commit_b)) {
1178                 output(opt, 1, _("Failed to merge submodule %s (commits don't follow merge-base)"), path);
1179                 return 0;
1180         }
1181
1182         /* Case #1: a is contained in b or vice versa */
1183         if (in_merge_bases(commit_a, commit_b)) {
1184                 oidcpy(result, b);
1185                 if (show(opt, 3)) {
1186                         output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
1187                         output_commit_title(opt, commit_b);
1188                 } else if (show(opt, 2))
1189                         output(opt, 2, _("Fast-forwarding submodule %s"), path);
1190                 else
1191                         ; /* no output */
1192
1193                 return 1;
1194         }
1195         if (in_merge_bases(commit_b, commit_a)) {
1196                 oidcpy(result, a);
1197                 if (show(opt, 3)) {
1198                         output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
1199                         output_commit_title(opt, commit_a);
1200                 } else if (show(opt, 2))
1201                         output(opt, 2, _("Fast-forwarding submodule %s"), path);
1202                 else
1203                         ; /* no output */
1204
1205                 return 1;
1206         }
1207
1208         /*
1209          * Case #2: There are one or more merges that contain a and b in
1210          * the submodule. If there is only one, then present it as a
1211          * suggestion to the user, but leave it marked unmerged so the
1212          * user needs to confirm the resolution.
1213          */
1214
1215         /* Skip the search if makes no sense to the calling context.  */
1216         if (!search)
1217                 return 0;
1218
1219         /* find commit which merges them */
1220         parent_count = find_first_merges(opt->repo, &merges, path,
1221                                          commit_a, commit_b);
1222         switch (parent_count) {
1223         case 0:
1224                 output(opt, 1, _("Failed to merge submodule %s (merge following commits not found)"), path);
1225                 break;
1226
1227         case 1:
1228                 output(opt, 1, _("Failed to merge submodule %s (not fast-forward)"), path);
1229                 output(opt, 2, _("Found a possible merge resolution for the submodule:\n"));
1230                 print_commit((struct commit *) merges.objects[0].item);
1231                 output(opt, 2, _(
1232                        "If this is correct simply add it to the index "
1233                        "for example\n"
1234                        "by using:\n\n"
1235                        "  git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1236                        "which will accept this suggestion.\n"),
1237                        oid_to_hex(&merges.objects[0].item->oid), path);
1238                 break;
1239
1240         default:
1241                 output(opt, 1, _("Failed to merge submodule %s (multiple merges found)"), path);
1242                 for (i = 0; i < merges.nr; i++)
1243                         print_commit((struct commit *) merges.objects[i].item);
1244         }
1245
1246         object_array_clear(&merges);
1247         return 0;
1248 }
1249
1250 static int merge_mode_and_contents(struct merge_options *opt,
1251                                    const struct diff_filespec *o,
1252                                    const struct diff_filespec *a,
1253                                    const struct diff_filespec *b,
1254                                    const char *filename,
1255                                    const char *branch1,
1256                                    const char *branch2,
1257                                    const int extra_marker_size,
1258                                    struct merge_file_info *result)
1259 {
1260         if (opt->branch1 != branch1) {
1261                 /*
1262                  * It's weird getting a reverse merge with HEAD on the bottom
1263                  * side of the conflict markers and the other branch on the
1264                  * top.  Fix that.
1265                  */
1266                 return merge_mode_and_contents(opt, o, b, a,
1267                                                filename,
1268                                                branch2, branch1,
1269                                                extra_marker_size, result);
1270         }
1271
1272         result->merge = 0;
1273         result->clean = 1;
1274
1275         if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
1276                 result->clean = 0;
1277                 if (S_ISREG(a->mode)) {
1278                         result->blob.mode = a->mode;
1279                         oidcpy(&result->blob.oid, &a->oid);
1280                 } else {
1281                         result->blob.mode = b->mode;
1282                         oidcpy(&result->blob.oid, &b->oid);
1283                 }
1284         } else {
1285                 if (!oid_eq(&a->oid, &o->oid) && !oid_eq(&b->oid, &o->oid))
1286                         result->merge = 1;
1287
1288                 /*
1289                  * Merge modes
1290                  */
1291                 if (a->mode == b->mode || a->mode == o->mode)
1292                         result->blob.mode = b->mode;
1293                 else {
1294                         result->blob.mode = a->mode;
1295                         if (b->mode != o->mode) {
1296                                 result->clean = 0;
1297                                 result->merge = 1;
1298                         }
1299                 }
1300
1301                 if (oid_eq(&a->oid, &b->oid) || oid_eq(&a->oid, &o->oid))
1302                         oidcpy(&result->blob.oid, &b->oid);
1303                 else if (oid_eq(&b->oid, &o->oid))
1304                         oidcpy(&result->blob.oid, &a->oid);
1305                 else if (S_ISREG(a->mode)) {
1306                         mmbuffer_t result_buf;
1307                         int ret = 0, merge_status;
1308
1309                         merge_status = merge_3way(opt, &result_buf, o, a, b,
1310                                                   branch1, branch2,
1311                                                   extra_marker_size);
1312
1313                         if ((merge_status < 0) || !result_buf.ptr)
1314                                 ret = err(opt, _("Failed to execute internal merge"));
1315
1316                         if (!ret &&
1317                             write_object_file(result_buf.ptr, result_buf.size,
1318                                               blob_type, &result->blob.oid))
1319                                 ret = err(opt, _("Unable to add %s to database"),
1320                                           a->path);
1321
1322                         free(result_buf.ptr);
1323                         if (ret)
1324                                 return ret;
1325                         result->clean = (merge_status == 0);
1326                 } else if (S_ISGITLINK(a->mode)) {
1327                         result->clean = merge_submodule(opt, &result->blob.oid,
1328                                                         o->path,
1329                                                         &o->oid,
1330                                                         &a->oid,
1331                                                         &b->oid);
1332                 } else if (S_ISLNK(a->mode)) {
1333                         switch (opt->recursive_variant) {
1334                         case MERGE_RECURSIVE_NORMAL:
1335                                 oidcpy(&result->blob.oid, &a->oid);
1336                                 if (!oid_eq(&a->oid, &b->oid))
1337                                         result->clean = 0;
1338                                 break;
1339                         case MERGE_RECURSIVE_OURS:
1340                                 oidcpy(&result->blob.oid, &a->oid);
1341                                 break;
1342                         case MERGE_RECURSIVE_THEIRS:
1343                                 oidcpy(&result->blob.oid, &b->oid);
1344                                 break;
1345                         }
1346                 } else
1347                         BUG("unsupported object type in the tree");
1348         }
1349
1350         if (result->merge)
1351                 output(opt, 2, _("Auto-merging %s"), filename);
1352
1353         return 0;
1354 }
1355
1356 static int handle_rename_via_dir(struct merge_options *opt,
1357                                  struct rename_conflict_info *ci)
1358 {
1359         /*
1360          * Handle file adds that need to be renamed due to directory rename
1361          * detection.  This differs from handle_rename_normal, because
1362          * there is no content merge to do; just move the file into the
1363          * desired final location.
1364          */
1365         const struct rename *ren = ci->ren1;
1366         const struct diff_filespec *dest = ren->pair->two;
1367
1368         if (!opt->call_depth && would_lose_untracked(opt, dest->path)) {
1369                 char *alt_path = unique_path(opt, dest->path, ren->branch);
1370
1371                 output(opt, 1, _("Error: Refusing to lose untracked file at %s; "
1372                                "writing to %s instead."),
1373                        dest->path, alt_path);
1374                 /*
1375                  * Write the file in worktree at alt_path, but not in the
1376                  * index.  Instead, write to dest->path for the index but
1377                  * only at the higher appropriate stage.
1378                  */
1379                 if (update_file(opt, 0, dest, alt_path))
1380                         return -1;
1381                 free(alt_path);
1382                 return update_stages(opt, dest->path, NULL,
1383                                      ren->branch == opt->branch1 ? dest : NULL,
1384                                      ren->branch == opt->branch1 ? NULL : dest);
1385         }
1386
1387         /* Update dest->path both in index and in worktree */
1388         if (update_file(opt, 1, dest, dest->path))
1389                 return -1;
1390         return 0;
1391 }
1392
1393 static int handle_change_delete(struct merge_options *opt,
1394                                 const char *path, const char *old_path,
1395                                 const struct diff_filespec *o,
1396                                 const struct diff_filespec *changed,
1397                                 const char *change_branch,
1398                                 const char *delete_branch,
1399                                 const char *change, const char *change_past)
1400 {
1401         char *alt_path = NULL;
1402         const char *update_path = path;
1403         int ret = 0;
1404
1405         if (dir_in_way(opt->repo->index, path, !opt->call_depth, 0) ||
1406             (!opt->call_depth && would_lose_untracked(opt, path))) {
1407                 update_path = alt_path = unique_path(opt, path, change_branch);
1408         }
1409
1410         if (opt->call_depth) {
1411                 /*
1412                  * We cannot arbitrarily accept either a_sha or b_sha as
1413                  * correct; since there is no true "middle point" between
1414                  * them, simply reuse the base version for virtual merge base.
1415                  */
1416                 ret = remove_file_from_index(opt->repo->index, path);
1417                 if (!ret)
1418                         ret = update_file(opt, 0, o, update_path);
1419         } else {
1420                 /*
1421                  * Despite the four nearly duplicate messages and argument
1422                  * lists below and the ugliness of the nested if-statements,
1423                  * having complete messages makes the job easier for
1424                  * translators.
1425                  *
1426                  * The slight variance among the cases is due to the fact
1427                  * that:
1428                  *   1) directory/file conflicts (in effect if
1429                  *      !alt_path) could cause us to need to write the
1430                  *      file to a different path.
1431                  *   2) renames (in effect if !old_path) could mean that
1432                  *      there are two names for the path that the user
1433                  *      may know the file by.
1434                  */
1435                 if (!alt_path) {
1436                         if (!old_path) {
1437                                 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1438                                        "and %s in %s. Version %s of %s left in tree."),
1439                                        change, path, delete_branch, change_past,
1440                                        change_branch, change_branch, path);
1441                         } else {
1442                                 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1443                                        "and %s to %s in %s. Version %s of %s left in tree."),
1444                                        change, old_path, delete_branch, change_past, path,
1445                                        change_branch, change_branch, path);
1446                         }
1447                 } else {
1448                         if (!old_path) {
1449                                 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1450                                        "and %s in %s. Version %s of %s left in tree at %s."),
1451                                        change, path, delete_branch, change_past,
1452                                        change_branch, change_branch, path, alt_path);
1453                         } else {
1454                                 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1455                                        "and %s to %s in %s. Version %s of %s left in tree at %s."),
1456                                        change, old_path, delete_branch, change_past, path,
1457                                        change_branch, change_branch, path, alt_path);
1458                         }
1459                 }
1460                 /*
1461                  * No need to call update_file() on path when change_branch ==
1462                  * opt->branch1 && !alt_path, since that would needlessly touch
1463                  * path.  We could call update_file_flags() with update_cache=0
1464                  * and update_wd=0, but that's a no-op.
1465                  */
1466                 if (change_branch != opt->branch1 || alt_path)
1467                         ret = update_file(opt, 0, changed, update_path);
1468         }
1469         free(alt_path);
1470
1471         return ret;
1472 }
1473
1474 static int handle_rename_delete(struct merge_options *opt,
1475                                 struct rename_conflict_info *ci)
1476 {
1477         const struct rename *ren = ci->ren1;
1478         const struct diff_filespec *orig = ren->pair->one;
1479         const struct diff_filespec *dest = ren->pair->two;
1480         const char *rename_branch = ren->branch;
1481         const char *delete_branch = (opt->branch1 == ren->branch ?
1482                                      opt->branch2 : opt->branch1);
1483
1484         if (handle_change_delete(opt,
1485                                  opt->call_depth ? orig->path : dest->path,
1486                                  opt->call_depth ? NULL : orig->path,
1487                                  orig, dest,
1488                                  rename_branch, delete_branch,
1489                                  _("rename"), _("renamed")))
1490                 return -1;
1491
1492         if (opt->call_depth)
1493                 return remove_file_from_index(opt->repo->index, dest->path);
1494         else
1495                 return update_stages(opt, dest->path, NULL,
1496                                      rename_branch == opt->branch1 ? dest : NULL,
1497                                      rename_branch == opt->branch1 ? NULL : dest);
1498 }
1499
1500 static int handle_file_collision(struct merge_options *opt,
1501                                  const char *collide_path,
1502                                  const char *prev_path1,
1503                                  const char *prev_path2,
1504                                  const char *branch1, const char *branch2,
1505                                  struct diff_filespec *a,
1506                                  struct diff_filespec *b)
1507 {
1508         struct merge_file_info mfi;
1509         struct diff_filespec null;
1510         char *alt_path = NULL;
1511         const char *update_path = collide_path;
1512
1513         /*
1514          * It's easiest to get the correct things into stage 2 and 3, and
1515          * to make sure that the content merge puts HEAD before the other
1516          * branch if we just ensure that branch1 == opt->branch1.  So, simply
1517          * flip arguments around if we don't have that.
1518          */
1519         if (branch1 != opt->branch1) {
1520                 return handle_file_collision(opt, collide_path,
1521                                              prev_path2, prev_path1,
1522                                              branch2, branch1,
1523                                              b, a);
1524         }
1525
1526         /*
1527          * In the recursive case, we just opt to undo renames
1528          */
1529         if (opt->call_depth && (prev_path1 || prev_path2)) {
1530                 /* Put first file (a->oid, a->mode) in its original spot */
1531                 if (prev_path1) {
1532                         if (update_file(opt, 1, a, prev_path1))
1533                                 return -1;
1534                 } else {
1535                         if (update_file(opt, 1, a, collide_path))
1536                                 return -1;
1537                 }
1538
1539                 /* Put second file (b->oid, b->mode) in its original spot */
1540                 if (prev_path2) {
1541                         if (update_file(opt, 1, b, prev_path2))
1542                                 return -1;
1543                 } else {
1544                         if (update_file(opt, 1, b, collide_path))
1545                                 return -1;
1546                 }
1547
1548                 /* Don't leave something at collision path if unrenaming both */
1549                 if (prev_path1 && prev_path2)
1550                         remove_file(opt, 1, collide_path, 0);
1551
1552                 return 0;
1553         }
1554
1555         /* Remove rename sources if rename/add or rename/rename(2to1) */
1556         if (prev_path1)
1557                 remove_file(opt, 1, prev_path1,
1558                             opt->call_depth || would_lose_untracked(opt, prev_path1));
1559         if (prev_path2)
1560                 remove_file(opt, 1, prev_path2,
1561                             opt->call_depth || would_lose_untracked(opt, prev_path2));
1562
1563         /*
1564          * Remove the collision path, if it wouldn't cause dirty contents
1565          * or an untracked file to get lost.  We'll either overwrite with
1566          * merged contents, or just write out to differently named files.
1567          */
1568         if (was_dirty(opt, collide_path)) {
1569                 output(opt, 1, _("Refusing to lose dirty file at %s"),
1570                        collide_path);
1571                 update_path = alt_path = unique_path(opt, collide_path, "merged");
1572         } else if (would_lose_untracked(opt, collide_path)) {
1573                 /*
1574                  * Only way we get here is if both renames were from
1575                  * a directory rename AND user had an untracked file
1576                  * at the location where both files end up after the
1577                  * two directory renames.  See testcase 10d of t6043.
1578                  */
1579                 output(opt, 1, _("Refusing to lose untracked file at "
1580                                "%s, even though it's in the way."),
1581                        collide_path);
1582                 update_path = alt_path = unique_path(opt, collide_path, "merged");
1583         } else {
1584                 /*
1585                  * FIXME: It's possible that the two files are identical
1586                  * and that the current working copy happens to match, in
1587                  * which case we are unnecessarily touching the working
1588                  * tree file.  It's not a likely enough scenario that I
1589                  * want to code up the checks for it and a better fix is
1590                  * available if we restructure how unpack_trees() and
1591                  * merge-recursive interoperate anyway, so punting for
1592                  * now...
1593                  */
1594                 remove_file(opt, 0, collide_path, 0);
1595         }
1596
1597         /* Store things in diff_filespecs for functions that need it */
1598         null.path = (char *)collide_path;
1599         oidcpy(&null.oid, &null_oid);
1600         null.mode = 0;
1601
1602         if (merge_mode_and_contents(opt, &null, a, b, collide_path,
1603                                     branch1, branch2, opt->call_depth * 2, &mfi))
1604                 return -1;
1605         mfi.clean &= !alt_path;
1606         if (update_file(opt, mfi.clean, &mfi.blob, update_path))
1607                 return -1;
1608         if (!mfi.clean && !opt->call_depth &&
1609             update_stages(opt, collide_path, NULL, a, b))
1610                 return -1;
1611         free(alt_path);
1612         /*
1613          * FIXME: If both a & b both started with conflicts (only possible
1614          * if they came from a rename/rename(2to1)), but had IDENTICAL
1615          * contents including those conflicts, then in the next line we claim
1616          * it was clean.  If someone cares about this case, we should have the
1617          * caller notify us if we started with conflicts.
1618          */
1619         return mfi.clean;
1620 }
1621
1622 static int handle_rename_add(struct merge_options *opt,
1623                              struct rename_conflict_info *ci)
1624 {
1625         /* a was renamed to c, and a separate c was added. */
1626         struct diff_filespec *a = ci->ren1->pair->one;
1627         struct diff_filespec *c = ci->ren1->pair->two;
1628         char *path = c->path;
1629         char *prev_path_desc;
1630         struct merge_file_info mfi;
1631
1632         const char *rename_branch = ci->ren1->branch;
1633         const char *add_branch = (opt->branch1 == rename_branch ?
1634                                   opt->branch2 : opt->branch1);
1635         int other_stage = (ci->ren1->branch == opt->branch1 ? 3 : 2);
1636
1637         output(opt, 1, _("CONFLICT (rename/add): "
1638                "Rename %s->%s in %s.  Added %s in %s"),
1639                a->path, c->path, rename_branch,
1640                c->path, add_branch);
1641
1642         prev_path_desc = xstrfmt("version of %s from %s", path, a->path);
1643         if (merge_mode_and_contents(opt, a, c,
1644                                     &ci->ren1->src_entry->stages[other_stage],
1645                                     prev_path_desc,
1646                                     opt->branch1, opt->branch2,
1647                                     1 + opt->call_depth * 2, &mfi))
1648                 return -1;
1649         free(prev_path_desc);
1650
1651         ci->ren1->dst_entry->stages[other_stage].path = mfi.blob.path = c->path;
1652         return handle_file_collision(opt,
1653                                      c->path, a->path, NULL,
1654                                      rename_branch, add_branch,
1655                                      &mfi.blob,
1656                                      &ci->ren1->dst_entry->stages[other_stage]);
1657 }
1658
1659 static char *find_path_for_conflict(struct merge_options *opt,
1660                                     const char *path,
1661                                     const char *branch1,
1662                                     const char *branch2)
1663 {
1664         char *new_path = NULL;
1665         if (dir_in_way(opt->repo->index, path, !opt->call_depth, 0)) {
1666                 new_path = unique_path(opt, path, branch1);
1667                 output(opt, 1, _("%s is a directory in %s adding "
1668                                "as %s instead"),
1669                        path, branch2, new_path);
1670         } else if (would_lose_untracked(opt, path)) {
1671                 new_path = unique_path(opt, path, branch1);
1672                 output(opt, 1, _("Refusing to lose untracked file"
1673                                " at %s; adding as %s instead"),
1674                        path, new_path);
1675         }
1676
1677         return new_path;
1678 }
1679
1680 static int handle_rename_rename_1to2(struct merge_options *opt,
1681                                      struct rename_conflict_info *ci)
1682 {
1683         /* One file was renamed in both branches, but to different names. */
1684         struct merge_file_info mfi;
1685         struct diff_filespec *add;
1686         struct diff_filespec *o = ci->ren1->pair->one;
1687         struct diff_filespec *a = ci->ren1->pair->two;
1688         struct diff_filespec *b = ci->ren2->pair->two;
1689         char *path_desc;
1690
1691         output(opt, 1, _("CONFLICT (rename/rename): "
1692                "Rename \"%s\"->\"%s\" in branch \"%s\" "
1693                "rename \"%s\"->\"%s\" in \"%s\"%s"),
1694                o->path, a->path, ci->ren1->branch,
1695                o->path, b->path, ci->ren2->branch,
1696                opt->call_depth ? _(" (left unresolved)") : "");
1697
1698         path_desc = xstrfmt("%s and %s, both renamed from %s",
1699                             a->path, b->path, o->path);
1700         if (merge_mode_and_contents(opt, o, a, b, path_desc,
1701                                     ci->ren1->branch, ci->ren2->branch,
1702                                     opt->call_depth * 2, &mfi))
1703                 return -1;
1704         free(path_desc);
1705
1706         if (opt->call_depth) {
1707                 /*
1708                  * FIXME: For rename/add-source conflicts (if we could detect
1709                  * such), this is wrong.  We should instead find a unique
1710                  * pathname and then either rename the add-source file to that
1711                  * unique path, or use that unique path instead of src here.
1712                  */
1713                 if (update_file(opt, 0, &mfi.blob, o->path))
1714                         return -1;
1715
1716                 /*
1717                  * Above, we put the merged content at the merge-base's
1718                  * path.  Now we usually need to delete both a->path and
1719                  * b->path.  However, the rename on each side of the merge
1720                  * could also be involved in a rename/add conflict.  In
1721                  * such cases, we should keep the added file around,
1722                  * resolving the conflict at that path in its favor.
1723                  */
1724                 add = &ci->ren1->dst_entry->stages[2 ^ 1];
1725                 if (is_valid(add)) {
1726                         if (update_file(opt, 0, add, a->path))
1727                                 return -1;
1728                 }
1729                 else
1730                         remove_file_from_index(opt->repo->index, a->path);
1731                 add = &ci->ren2->dst_entry->stages[3 ^ 1];
1732                 if (is_valid(add)) {
1733                         if (update_file(opt, 0, add, b->path))
1734                                 return -1;
1735                 }
1736                 else
1737                         remove_file_from_index(opt->repo->index, b->path);
1738         } else {
1739                 /*
1740                  * For each destination path, we need to see if there is a
1741                  * rename/add collision.  If not, we can write the file out
1742                  * to the specified location.
1743                  */
1744                 add = &ci->ren1->dst_entry->stages[2 ^ 1];
1745                 if (is_valid(add)) {
1746                         add->path = mfi.blob.path = a->path;
1747                         if (handle_file_collision(opt, a->path,
1748                                                   NULL, NULL,
1749                                                   ci->ren1->branch,
1750                                                   ci->ren2->branch,
1751                                                   &mfi.blob, add) < 0)
1752                                 return -1;
1753                 } else {
1754                         char *new_path = find_path_for_conflict(opt, a->path,
1755                                                                 ci->ren1->branch,
1756                                                                 ci->ren2->branch);
1757                         if (update_file(opt, 0, &mfi.blob,
1758                                         new_path ? new_path : a->path))
1759                                 return -1;
1760                         free(new_path);
1761                         if (update_stages(opt, a->path, NULL, a, NULL))
1762                                 return -1;
1763                 }
1764
1765                 add = &ci->ren2->dst_entry->stages[3 ^ 1];
1766                 if (is_valid(add)) {
1767                         add->path = mfi.blob.path = b->path;
1768                         if (handle_file_collision(opt, b->path,
1769                                                   NULL, NULL,
1770                                                   ci->ren1->branch,
1771                                                   ci->ren2->branch,
1772                                                   add, &mfi.blob) < 0)
1773                                 return -1;
1774                 } else {
1775                         char *new_path = find_path_for_conflict(opt, b->path,
1776                                                                 ci->ren2->branch,
1777                                                                 ci->ren1->branch);
1778                         if (update_file(opt, 0, &mfi.blob,
1779                                         new_path ? new_path : b->path))
1780                                 return -1;
1781                         free(new_path);
1782                         if (update_stages(opt, b->path, NULL, NULL, b))
1783                                 return -1;
1784                 }
1785         }
1786
1787         return 0;
1788 }
1789
1790 static int handle_rename_rename_2to1(struct merge_options *opt,
1791                                      struct rename_conflict_info *ci)
1792 {
1793         /* Two files, a & b, were renamed to the same thing, c. */
1794         struct diff_filespec *a = ci->ren1->pair->one;
1795         struct diff_filespec *b = ci->ren2->pair->one;
1796         struct diff_filespec *c1 = ci->ren1->pair->two;
1797         struct diff_filespec *c2 = ci->ren2->pair->two;
1798         char *path = c1->path; /* == c2->path */
1799         char *path_side_1_desc;
1800         char *path_side_2_desc;
1801         struct merge_file_info mfi_c1;
1802         struct merge_file_info mfi_c2;
1803         int ostage1, ostage2;
1804
1805         output(opt, 1, _("CONFLICT (rename/rename): "
1806                "Rename %s->%s in %s. "
1807                "Rename %s->%s in %s"),
1808                a->path, c1->path, ci->ren1->branch,
1809                b->path, c2->path, ci->ren2->branch);
1810
1811         path_side_1_desc = xstrfmt("version of %s from %s", path, a->path);
1812         path_side_2_desc = xstrfmt("version of %s from %s", path, b->path);
1813         ostage1 = ci->ren1->branch == opt->branch1 ? 3 : 2;
1814         ostage2 = ostage1 ^ 1;
1815         ci->ren1->src_entry->stages[ostage1].path = a->path;
1816         ci->ren2->src_entry->stages[ostage2].path = b->path;
1817         if (merge_mode_and_contents(opt, a, c1,
1818                                     &ci->ren1->src_entry->stages[ostage1],
1819                                     path_side_1_desc,
1820                                     opt->branch1, opt->branch2,
1821                                     1 + opt->call_depth * 2, &mfi_c1) ||
1822             merge_mode_and_contents(opt, b,
1823                                     &ci->ren2->src_entry->stages[ostage2],
1824                                     c2, path_side_2_desc,
1825                                     opt->branch1, opt->branch2,
1826                                     1 + opt->call_depth * 2, &mfi_c2))
1827                 return -1;
1828         free(path_side_1_desc);
1829         free(path_side_2_desc);
1830         mfi_c1.blob.path = path;
1831         mfi_c2.blob.path = path;
1832
1833         return handle_file_collision(opt, path, a->path, b->path,
1834                                      ci->ren1->branch, ci->ren2->branch,
1835                                      &mfi_c1.blob, &mfi_c2.blob);
1836 }
1837
1838 /*
1839  * Get the diff_filepairs changed between o_tree and tree.
1840  */
1841 static struct diff_queue_struct *get_diffpairs(struct merge_options *opt,
1842                                                struct tree *o_tree,
1843                                                struct tree *tree)
1844 {
1845         struct diff_queue_struct *ret;
1846         struct diff_options opts;
1847
1848         repo_diff_setup(opt->repo, &opts);
1849         opts.flags.recursive = 1;
1850         opts.flags.rename_empty = 0;
1851         opts.detect_rename = merge_detect_rename(opt);
1852         /*
1853          * We do not have logic to handle the detection of copies.  In
1854          * fact, it may not even make sense to add such logic: would we
1855          * really want a change to a base file to be propagated through
1856          * multiple other files by a merge?
1857          */
1858         if (opts.detect_rename > DIFF_DETECT_RENAME)
1859                 opts.detect_rename = DIFF_DETECT_RENAME;
1860         opts.rename_limit = opt->merge_rename_limit >= 0 ? opt->merge_rename_limit :
1861                             opt->diff_rename_limit >= 0 ? opt->diff_rename_limit :
1862                             1000;
1863         opts.rename_score = opt->rename_score;
1864         opts.show_rename_progress = opt->show_rename_progress;
1865         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1866         diff_setup_done(&opts);
1867         diff_tree_oid(&o_tree->object.oid, &tree->object.oid, "", &opts);
1868         diffcore_std(&opts);
1869         if (opts.needed_rename_limit > opt->needed_rename_limit)
1870                 opt->needed_rename_limit = opts.needed_rename_limit;
1871
1872         ret = xmalloc(sizeof(*ret));
1873         *ret = diff_queued_diff;
1874
1875         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1876         diff_queued_diff.nr = 0;
1877         diff_queued_diff.queue = NULL;
1878         diff_flush(&opts);
1879         return ret;
1880 }
1881
1882 static int tree_has_path(struct tree *tree, const char *path)
1883 {
1884         struct object_id hashy;
1885         unsigned short mode_o;
1886
1887         return !get_tree_entry(&tree->object.oid, path,
1888                                &hashy, &mode_o);
1889 }
1890
1891 /*
1892  * Return a new string that replaces the beginning portion (which matches
1893  * entry->dir), with entry->new_dir.  In perl-speak:
1894  *   new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);
1895  * NOTE:
1896  *   Caller must ensure that old_path starts with entry->dir + '/'.
1897  */
1898 static char *apply_dir_rename(struct dir_rename_entry *entry,
1899                               const char *old_path)
1900 {
1901         struct strbuf new_path = STRBUF_INIT;
1902         int oldlen, newlen;
1903
1904         if (entry->non_unique_new_dir)
1905                 return NULL;
1906
1907         oldlen = strlen(entry->dir);
1908         newlen = entry->new_dir.len + (strlen(old_path) - oldlen) + 1;
1909         strbuf_grow(&new_path, newlen);
1910         strbuf_addbuf(&new_path, &entry->new_dir);
1911         strbuf_addstr(&new_path, &old_path[oldlen]);
1912
1913         return strbuf_detach(&new_path, NULL);
1914 }
1915
1916 static void get_renamed_dir_portion(const char *old_path, const char *new_path,
1917                                     char **old_dir, char **new_dir)
1918 {
1919         char *end_of_old, *end_of_new;
1920         int old_len, new_len;
1921
1922         *old_dir = NULL;
1923         *new_dir = NULL;
1924
1925         /*
1926          * For
1927          *    "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
1928          * the "e/foo.c" part is the same, we just want to know that
1929          *    "a/b/c/d" was renamed to "a/b/some/thing/else"
1930          * so, for this example, this function returns "a/b/c/d" in
1931          * *old_dir and "a/b/some/thing/else" in *new_dir.
1932          *
1933          * Also, if the basename of the file changed, we don't care.  We
1934          * want to know which portion of the directory, if any, changed.
1935          */
1936         end_of_old = strrchr(old_path, '/');
1937         end_of_new = strrchr(new_path, '/');
1938
1939         if (end_of_old == NULL || end_of_new == NULL)
1940                 return;
1941         while (*--end_of_new == *--end_of_old &&
1942                end_of_old != old_path &&
1943                end_of_new != new_path)
1944                 ; /* Do nothing; all in the while loop */
1945         /*
1946          * We've found the first non-matching character in the directory
1947          * paths.  That means the current directory we were comparing
1948          * represents the rename.  Move end_of_old and end_of_new back
1949          * to the full directory name.
1950          */
1951         if (*end_of_old == '/')
1952                 end_of_old++;
1953         if (*end_of_old != '/')
1954                 end_of_new++;
1955         end_of_old = strchr(end_of_old, '/');
1956         end_of_new = strchr(end_of_new, '/');
1957
1958         /*
1959          * It may have been the case that old_path and new_path were the same
1960          * directory all along.  Don't claim a rename if they're the same.
1961          */
1962         old_len = end_of_old - old_path;
1963         new_len = end_of_new - new_path;
1964
1965         if (old_len != new_len || strncmp(old_path, new_path, old_len)) {
1966                 *old_dir = xstrndup(old_path, old_len);
1967                 *new_dir = xstrndup(new_path, new_len);
1968         }
1969 }
1970
1971 static void remove_hashmap_entries(struct hashmap *dir_renames,
1972                                    struct string_list *items_to_remove)
1973 {
1974         int i;
1975         struct dir_rename_entry *entry;
1976
1977         for (i = 0; i < items_to_remove->nr; i++) {
1978                 entry = items_to_remove->items[i].util;
1979                 hashmap_remove(dir_renames, entry, NULL);
1980         }
1981         string_list_clear(items_to_remove, 0);
1982 }
1983
1984 /*
1985  * See if there is a directory rename for path, and if there are any file
1986  * level conflicts for the renamed location.  If there is a rename and
1987  * there are no conflicts, return the new name.  Otherwise, return NULL.
1988  */
1989 static char *handle_path_level_conflicts(struct merge_options *opt,
1990                                          const char *path,
1991                                          struct dir_rename_entry *entry,
1992                                          struct hashmap *collisions,
1993                                          struct tree *tree)
1994 {
1995         char *new_path = NULL;
1996         struct collision_entry *collision_ent;
1997         int clean = 1;
1998         struct strbuf collision_paths = STRBUF_INIT;
1999
2000         /*
2001          * entry has the mapping of old directory name to new directory name
2002          * that we want to apply to path.
2003          */
2004         new_path = apply_dir_rename(entry, path);
2005
2006         if (!new_path) {
2007                 /* This should only happen when entry->non_unique_new_dir set */
2008                 if (!entry->non_unique_new_dir)
2009                         BUG("entry->non_unqiue_dir not set and !new_path");
2010                 output(opt, 1, _("CONFLICT (directory rename split): "
2011                                "Unclear where to place %s because directory "
2012                                "%s was renamed to multiple other directories, "
2013                                "with no destination getting a majority of the "
2014                                "files."),
2015                        path, entry->dir);
2016                 clean = 0;
2017                 return NULL;
2018         }
2019
2020         /*
2021          * The caller needs to have ensured that it has pre-populated
2022          * collisions with all paths that map to new_path.  Do a quick check
2023          * to ensure that's the case.
2024          */
2025         collision_ent = collision_find_entry(collisions, new_path);
2026         if (collision_ent == NULL)
2027                 BUG("collision_ent is NULL");
2028
2029         /*
2030          * Check for one-sided add/add/.../add conflicts, i.e.
2031          * where implicit renames from the other side doing
2032          * directory rename(s) can affect this side of history
2033          * to put multiple paths into the same location.  Warn
2034          * and bail on directory renames for such paths.
2035          */
2036         if (collision_ent->reported_already) {
2037                 clean = 0;
2038         } else if (tree_has_path(tree, new_path)) {
2039                 collision_ent->reported_already = 1;
2040                 strbuf_add_separated_string_list(&collision_paths, ", ",
2041                                                  &collision_ent->source_files);
2042                 output(opt, 1, _("CONFLICT (implicit dir rename): Existing "
2043                                "file/dir at %s in the way of implicit "
2044                                "directory rename(s) putting the following "
2045                                "path(s) there: %s."),
2046                        new_path, collision_paths.buf);
2047                 clean = 0;
2048         } else if (collision_ent->source_files.nr > 1) {
2049                 collision_ent->reported_already = 1;
2050                 strbuf_add_separated_string_list(&collision_paths, ", ",
2051                                                  &collision_ent->source_files);
2052                 output(opt, 1, _("CONFLICT (implicit dir rename): Cannot map "
2053                                "more than one path to %s; implicit directory "
2054                                "renames tried to put these paths there: %s"),
2055                        new_path, collision_paths.buf);
2056                 clean = 0;
2057         }
2058
2059         /* Free memory we no longer need */
2060         strbuf_release(&collision_paths);
2061         if (!clean && new_path) {
2062                 free(new_path);
2063                 return NULL;
2064         }
2065
2066         return new_path;
2067 }
2068
2069 /*
2070  * There are a couple things we want to do at the directory level:
2071  *   1. Check for both sides renaming to the same thing, in order to avoid
2072  *      implicit renaming of files that should be left in place.  (See
2073  *      testcase 6b in t6043 for details.)
2074  *   2. Prune directory renames if there are still files left in the
2075  *      the original directory.  These represent a partial directory rename,
2076  *      i.e. a rename where only some of the files within the directory
2077  *      were renamed elsewhere.  (Technically, this could be done earlier
2078  *      in get_directory_renames(), except that would prevent us from
2079  *      doing the previous check and thus failing testcase 6b.)
2080  *   3. Check for rename/rename(1to2) conflicts (at the directory level).
2081  *      In the future, we could potentially record this info as well and
2082  *      omit reporting rename/rename(1to2) conflicts for each path within
2083  *      the affected directories, thus cleaning up the merge output.
2084  *   NOTE: We do NOT check for rename/rename(2to1) conflicts at the
2085  *         directory level, because merging directories is fine.  If it
2086  *         causes conflicts for files within those merged directories, then
2087  *         that should be detected at the individual path level.
2088  */
2089 static void handle_directory_level_conflicts(struct merge_options *opt,
2090                                              struct hashmap *dir_re_head,
2091                                              struct tree *head,
2092                                              struct hashmap *dir_re_merge,
2093                                              struct tree *merge)
2094 {
2095         struct hashmap_iter iter;
2096         struct dir_rename_entry *head_ent;
2097         struct dir_rename_entry *merge_ent;
2098
2099         struct string_list remove_from_head = STRING_LIST_INIT_NODUP;
2100         struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;
2101
2102         hashmap_iter_init(dir_re_head, &iter);
2103         while ((head_ent = hashmap_iter_next(&iter))) {
2104                 merge_ent = dir_rename_find_entry(dir_re_merge, head_ent->dir);
2105                 if (merge_ent &&
2106                     !head_ent->non_unique_new_dir &&
2107                     !merge_ent->non_unique_new_dir &&
2108                     !strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {
2109                         /* 1. Renamed identically; remove it from both sides */
2110                         string_list_append(&remove_from_head,
2111                                            head_ent->dir)->util = head_ent;
2112                         strbuf_release(&head_ent->new_dir);
2113                         string_list_append(&remove_from_merge,
2114                                            merge_ent->dir)->util = merge_ent;
2115                         strbuf_release(&merge_ent->new_dir);
2116                 } else if (tree_has_path(head, head_ent->dir)) {
2117                         /* 2. This wasn't a directory rename after all */
2118                         string_list_append(&remove_from_head,
2119                                            head_ent->dir)->util = head_ent;
2120                         strbuf_release(&head_ent->new_dir);
2121                 }
2122         }
2123
2124         remove_hashmap_entries(dir_re_head, &remove_from_head);
2125         remove_hashmap_entries(dir_re_merge, &remove_from_merge);
2126
2127         hashmap_iter_init(dir_re_merge, &iter);
2128         while ((merge_ent = hashmap_iter_next(&iter))) {
2129                 head_ent = dir_rename_find_entry(dir_re_head, merge_ent->dir);
2130                 if (tree_has_path(merge, merge_ent->dir)) {
2131                         /* 2. This wasn't a directory rename after all */
2132                         string_list_append(&remove_from_merge,
2133                                            merge_ent->dir)->util = merge_ent;
2134                 } else if (head_ent &&
2135                            !head_ent->non_unique_new_dir &&
2136                            !merge_ent->non_unique_new_dir) {
2137                         /* 3. rename/rename(1to2) */
2138                         /*
2139                          * We can assume it's not rename/rename(1to1) because
2140                          * that was case (1), already checked above.  So we
2141                          * know that head_ent->new_dir and merge_ent->new_dir
2142                          * are different strings.
2143                          */
2144                         output(opt, 1, _("CONFLICT (rename/rename): "
2145                                        "Rename directory %s->%s in %s. "
2146                                        "Rename directory %s->%s in %s"),
2147                                head_ent->dir, head_ent->new_dir.buf, opt->branch1,
2148                                head_ent->dir, merge_ent->new_dir.buf, opt->branch2);
2149                         string_list_append(&remove_from_head,
2150                                            head_ent->dir)->util = head_ent;
2151                         strbuf_release(&head_ent->new_dir);
2152                         string_list_append(&remove_from_merge,
2153                                            merge_ent->dir)->util = merge_ent;
2154                         strbuf_release(&merge_ent->new_dir);
2155                 }
2156         }
2157
2158         remove_hashmap_entries(dir_re_head, &remove_from_head);
2159         remove_hashmap_entries(dir_re_merge, &remove_from_merge);
2160 }
2161
2162 static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs)
2163 {
2164         struct hashmap *dir_renames;
2165         struct hashmap_iter iter;
2166         struct dir_rename_entry *entry;
2167         int i;
2168
2169         /*
2170          * Typically, we think of a directory rename as all files from a
2171          * certain directory being moved to a target directory.  However,
2172          * what if someone first moved two files from the original
2173          * directory in one commit, and then renamed the directory
2174          * somewhere else in a later commit?  At merge time, we just know
2175          * that files from the original directory went to two different
2176          * places, and that the bulk of them ended up in the same place.
2177          * We want each directory rename to represent where the bulk of the
2178          * files from that directory end up; this function exists to find
2179          * where the bulk of the files went.
2180          *
2181          * The first loop below simply iterates through the list of file
2182          * renames, finding out how often each directory rename pair
2183          * possibility occurs.
2184          */
2185         dir_renames = xmalloc(sizeof(*dir_renames));
2186         dir_rename_init(dir_renames);
2187         for (i = 0; i < pairs->nr; ++i) {
2188                 struct string_list_item *item;
2189                 int *count;
2190                 struct diff_filepair *pair = pairs->queue[i];
2191                 char *old_dir, *new_dir;
2192
2193                 /* File not part of directory rename if it wasn't renamed */
2194                 if (pair->status != 'R')
2195                         continue;
2196
2197                 get_renamed_dir_portion(pair->one->path, pair->two->path,
2198                                         &old_dir,        &new_dir);
2199                 if (!old_dir)
2200                         /* Directory didn't change at all; ignore this one. */
2201                         continue;
2202
2203                 entry = dir_rename_find_entry(dir_renames, old_dir);
2204                 if (!entry) {
2205                         entry = xmalloc(sizeof(*entry));
2206                         dir_rename_entry_init(entry, old_dir);
2207                         hashmap_put(dir_renames, entry);
2208                 } else {
2209                         free(old_dir);
2210                 }
2211                 item = string_list_lookup(&entry->possible_new_dirs, new_dir);
2212                 if (!item) {
2213                         item = string_list_insert(&entry->possible_new_dirs,
2214                                                   new_dir);
2215                         item->util = xcalloc(1, sizeof(int));
2216                 } else {
2217                         free(new_dir);
2218                 }
2219                 count = item->util;
2220                 *count += 1;
2221         }
2222
2223         /*
2224          * For each directory with files moved out of it, we find out which
2225          * target directory received the most files so we can declare it to
2226          * be the "winning" target location for the directory rename.  This
2227          * winner gets recorded in new_dir.  If there is no winner
2228          * (multiple target directories received the same number of files),
2229          * we set non_unique_new_dir.  Once we've determined the winner (or
2230          * that there is no winner), we no longer need possible_new_dirs.
2231          */
2232         hashmap_iter_init(dir_renames, &iter);
2233         while ((entry = hashmap_iter_next(&iter))) {
2234                 int max = 0;
2235                 int bad_max = 0;
2236                 char *best = NULL;
2237
2238                 for (i = 0; i < entry->possible_new_dirs.nr; i++) {
2239                         int *count = entry->possible_new_dirs.items[i].util;
2240
2241                         if (*count == max)
2242                                 bad_max = max;
2243                         else if (*count > max) {
2244                                 max = *count;
2245                                 best = entry->possible_new_dirs.items[i].string;
2246                         }
2247                 }
2248                 if (bad_max == max)
2249                         entry->non_unique_new_dir = 1;
2250                 else {
2251                         assert(entry->new_dir.len == 0);
2252                         strbuf_addstr(&entry->new_dir, best);
2253                 }
2254                 /*
2255                  * The relevant directory sub-portion of the original full
2256                  * filepaths were xstrndup'ed before inserting into
2257                  * possible_new_dirs, and instead of manually iterating the
2258                  * list and free'ing each, just lie and tell
2259                  * possible_new_dirs that it did the strdup'ing so that it
2260                  * will free them for us.
2261                  */
2262                 entry->possible_new_dirs.strdup_strings = 1;
2263                 string_list_clear(&entry->possible_new_dirs, 1);
2264         }
2265
2266         return dir_renames;
2267 }
2268
2269 static struct dir_rename_entry *check_dir_renamed(const char *path,
2270                                                   struct hashmap *dir_renames)
2271 {
2272         char *temp = xstrdup(path);
2273         char *end;
2274         struct dir_rename_entry *entry = NULL;
2275
2276         while ((end = strrchr(temp, '/'))) {
2277                 *end = '\0';
2278                 entry = dir_rename_find_entry(dir_renames, temp);
2279                 if (entry)
2280                         break;
2281         }
2282         free(temp);
2283         return entry;
2284 }
2285
2286 static void compute_collisions(struct hashmap *collisions,
2287                                struct hashmap *dir_renames,
2288                                struct diff_queue_struct *pairs)
2289 {
2290         int i;
2291
2292         /*
2293          * Multiple files can be mapped to the same path due to directory
2294          * renames done by the other side of history.  Since that other
2295          * side of history could have merged multiple directories into one,
2296          * if our side of history added the same file basename to each of
2297          * those directories, then all N of them would get implicitly
2298          * renamed by the directory rename detection into the same path,
2299          * and we'd get an add/add/.../add conflict, and all those adds
2300          * from *this* side of history.  This is not representable in the
2301          * index, and users aren't going to easily be able to make sense of
2302          * it.  So we need to provide a good warning about what's
2303          * happening, and fall back to no-directory-rename detection
2304          * behavior for those paths.
2305          *
2306          * See testcases 9e and all of section 5 from t6043 for examples.
2307          */
2308         collision_init(collisions);
2309
2310         for (i = 0; i < pairs->nr; ++i) {
2311                 struct dir_rename_entry *dir_rename_ent;
2312                 struct collision_entry *collision_ent;
2313                 char *new_path;
2314                 struct diff_filepair *pair = pairs->queue[i];
2315
2316                 if (pair->status != 'A' && pair->status != 'R')
2317                         continue;
2318                 dir_rename_ent = check_dir_renamed(pair->two->path,
2319                                                    dir_renames);
2320                 if (!dir_rename_ent)
2321                         continue;
2322
2323                 new_path = apply_dir_rename(dir_rename_ent, pair->two->path);
2324                 if (!new_path)
2325                         /*
2326                          * dir_rename_ent->non_unique_new_path is true, which
2327                          * means there is no directory rename for us to use,
2328                          * which means it won't cause us any additional
2329                          * collisions.
2330                          */
2331                         continue;
2332                 collision_ent = collision_find_entry(collisions, new_path);
2333                 if (!collision_ent) {
2334                         collision_ent = xcalloc(1,
2335                                                 sizeof(struct collision_entry));
2336                         hashmap_entry_init(collision_ent, strhash(new_path));
2337                         hashmap_put(collisions, collision_ent);
2338                         collision_ent->target_file = new_path;
2339                 } else {
2340                         free(new_path);
2341                 }
2342                 string_list_insert(&collision_ent->source_files,
2343                                    pair->two->path);
2344         }
2345 }
2346
2347 static char *check_for_directory_rename(struct merge_options *opt,
2348                                         const char *path,
2349                                         struct tree *tree,
2350                                         struct hashmap *dir_renames,
2351                                         struct hashmap *dir_rename_exclusions,
2352                                         struct hashmap *collisions,
2353                                         int *clean_merge)
2354 {
2355         char *new_path = NULL;
2356         struct dir_rename_entry *entry = check_dir_renamed(path, dir_renames);
2357         struct dir_rename_entry *oentry = NULL;
2358
2359         if (!entry)
2360                 return new_path;
2361
2362         /*
2363          * This next part is a little weird.  We do not want to do an
2364          * implicit rename into a directory we renamed on our side, because
2365          * that will result in a spurious rename/rename(1to2) conflict.  An
2366          * example:
2367          *   Base commit: dumbdir/afile, otherdir/bfile
2368          *   Side 1:      smrtdir/afile, otherdir/bfile
2369          *   Side 2:      dumbdir/afile, dumbdir/bfile
2370          * Here, while working on Side 1, we could notice that otherdir was
2371          * renamed/merged to dumbdir, and change the diff_filepair for
2372          * otherdir/bfile into a rename into dumbdir/bfile.  However, Side
2373          * 2 will notice the rename from dumbdir to smrtdir, and do the
2374          * transitive rename to move it from dumbdir/bfile to
2375          * smrtdir/bfile.  That gives us bfile in dumbdir vs being in
2376          * smrtdir, a rename/rename(1to2) conflict.  We really just want
2377          * the file to end up in smrtdir.  And the way to achieve that is
2378          * to not let Side1 do the rename to dumbdir, since we know that is
2379          * the source of one of our directory renames.
2380          *
2381          * That's why oentry and dir_rename_exclusions is here.
2382          *
2383          * As it turns out, this also prevents N-way transient rename
2384          * confusion; See testcases 9c and 9d of t6043.
2385          */
2386         oentry = dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);
2387         if (oentry) {
2388                 output(opt, 1, _("WARNING: Avoiding applying %s -> %s rename "
2389                                "to %s, because %s itself was renamed."),
2390                        entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);
2391         } else {
2392                 new_path = handle_path_level_conflicts(opt, path, entry,
2393                                                        collisions, tree);
2394                 *clean_merge &= (new_path != NULL);
2395         }
2396
2397         return new_path;
2398 }
2399
2400 static void apply_directory_rename_modifications(struct merge_options *opt,
2401                                                  struct diff_filepair *pair,
2402                                                  char *new_path,
2403                                                  struct rename *re,
2404                                                  struct tree *tree,
2405                                                  struct tree *o_tree,
2406                                                  struct tree *a_tree,
2407                                                  struct tree *b_tree,
2408                                                  struct string_list *entries)
2409 {
2410         struct string_list_item *item;
2411         int stage = (tree == a_tree ? 2 : 3);
2412         int update_wd;
2413
2414         /*
2415          * In all cases where we can do directory rename detection,
2416          * unpack_trees() will have read pair->two->path into the
2417          * index and the working copy.  We need to remove it so that
2418          * we can instead place it at new_path.  It is guaranteed to
2419          * not be untracked (unpack_trees() would have errored out
2420          * saying the file would have been overwritten), but it might
2421          * be dirty, though.
2422          */
2423         update_wd = !was_dirty(opt, pair->two->path);
2424         if (!update_wd)
2425                 output(opt, 1, _("Refusing to lose dirty file at %s"),
2426                        pair->two->path);
2427         remove_file(opt, 1, pair->two->path, !update_wd);
2428
2429         /* Find or create a new re->dst_entry */
2430         item = string_list_lookup(entries, new_path);
2431         if (item) {
2432                 /*
2433                  * Since we're renaming on this side of history, and it's
2434                  * due to a directory rename on the other side of history
2435                  * (which we only allow when the directory in question no
2436                  * longer exists on the other side of history), the
2437                  * original entry for re->dst_entry is no longer
2438                  * necessary...
2439                  */
2440                 re->dst_entry->processed = 1;
2441
2442                 /*
2443                  * ...because we'll be using this new one.
2444                  */
2445                 re->dst_entry = item->util;
2446         } else {
2447                 /*
2448                  * re->dst_entry is for the before-dir-rename path, and we
2449                  * need it to hold information for the after-dir-rename
2450                  * path.  Before creating a new entry, we need to mark the
2451                  * old one as unnecessary (...unless it is shared by
2452                  * src_entry, i.e. this didn't use to be a rename, in which
2453                  * case we can just allow the normal processing to happen
2454                  * for it).
2455                  */
2456                 if (pair->status == 'R')
2457                         re->dst_entry->processed = 1;
2458
2459                 re->dst_entry = insert_stage_data(new_path,
2460                                                   o_tree, a_tree, b_tree,
2461                                                   entries);
2462                 item = string_list_insert(entries, new_path);
2463                 item->util = re->dst_entry;
2464         }
2465
2466         /*
2467          * Update the stage_data with the information about the path we are
2468          * moving into place.  That slot will be empty and available for us
2469          * to write to because of the collision checks in
2470          * handle_path_level_conflicts().  In other words,
2471          * re->dst_entry->stages[stage].oid will be the null_oid, so it's
2472          * open for us to write to.
2473          *
2474          * It may be tempting to actually update the index at this point as
2475          * well, using update_stages_for_stage_data(), but as per the big
2476          * "NOTE" in update_stages(), doing so will modify the current
2477          * in-memory index which will break calls to would_lose_untracked()
2478          * that we need to make.  Instead, we need to just make sure that
2479          * the various handle_rename_*() functions update the index
2480          * explicitly rather than relying on unpack_trees() to have done it.
2481          */
2482         get_tree_entry(&tree->object.oid,
2483                        pair->two->path,
2484                        &re->dst_entry->stages[stage].oid,
2485                        &re->dst_entry->stages[stage].mode);
2486
2487         /* Update pair status */
2488         if (pair->status == 'A') {
2489                 /*
2490                  * Recording rename information for this add makes it look
2491                  * like a rename/delete conflict.  Make sure we can
2492                  * correctly handle this as an add that was moved to a new
2493                  * directory instead of reporting a rename/delete conflict.
2494                  */
2495                 re->add_turned_into_rename = 1;
2496         }
2497         /*
2498          * We don't actually look at pair->status again, but it seems
2499          * pedagogically correct to adjust it.
2500          */
2501         pair->status = 'R';
2502
2503         /*
2504          * Finally, record the new location.
2505          */
2506         pair->two->path = new_path;
2507 }
2508
2509 /*
2510  * Get information of all renames which occurred in 'pairs', making use of
2511  * any implicit directory renames inferred from the other side of history.
2512  * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')
2513  * to be able to associate the correct cache entries with the rename
2514  * information; tree is always equal to either a_tree or b_tree.
2515  */
2516 static struct string_list *get_renames(struct merge_options *opt,
2517                                        const char *branch,
2518                                        struct diff_queue_struct *pairs,
2519                                        struct hashmap *dir_renames,
2520                                        struct hashmap *dir_rename_exclusions,
2521                                        struct tree *tree,
2522                                        struct tree *o_tree,
2523                                        struct tree *a_tree,
2524                                        struct tree *b_tree,
2525                                        struct string_list *entries,
2526                                        int *clean_merge)
2527 {
2528         int i;
2529         struct hashmap collisions;
2530         struct hashmap_iter iter;
2531         struct collision_entry *e;
2532         struct string_list *renames;
2533
2534         compute_collisions(&collisions, dir_renames, pairs);
2535         renames = xcalloc(1, sizeof(struct string_list));
2536
2537         for (i = 0; i < pairs->nr; ++i) {
2538                 struct string_list_item *item;
2539                 struct rename *re;
2540                 struct diff_filepair *pair = pairs->queue[i];
2541                 char *new_path; /* non-NULL only with directory renames */
2542
2543                 if (pair->status != 'A' && pair->status != 'R') {
2544                         diff_free_filepair(pair);
2545                         continue;
2546                 }
2547                 new_path = check_for_directory_rename(opt, pair->two->path, tree,
2548                                                       dir_renames,
2549                                                       dir_rename_exclusions,
2550                                                       &collisions,
2551                                                       clean_merge);
2552                 if (pair->status != 'R' && !new_path) {
2553                         diff_free_filepair(pair);
2554                         continue;
2555                 }
2556
2557                 re = xmalloc(sizeof(*re));
2558                 re->processed = 0;
2559                 re->add_turned_into_rename = 0;
2560                 re->pair = pair;
2561                 re->branch = branch;
2562                 item = string_list_lookup(entries, re->pair->one->path);
2563                 if (!item)
2564                         re->src_entry = insert_stage_data(re->pair->one->path,
2565                                         o_tree, a_tree, b_tree, entries);
2566                 else
2567                         re->src_entry = item->util;
2568
2569                 item = string_list_lookup(entries, re->pair->two->path);
2570                 if (!item)
2571                         re->dst_entry = insert_stage_data(re->pair->two->path,
2572                                         o_tree, a_tree, b_tree, entries);
2573                 else
2574                         re->dst_entry = item->util;
2575                 item = string_list_insert(renames, pair->one->path);
2576                 item->util = re;
2577                 if (new_path)
2578                         apply_directory_rename_modifications(opt, pair, new_path,
2579                                                              re, tree, o_tree,
2580                                                              a_tree, b_tree,
2581                                                              entries);
2582         }
2583
2584         hashmap_iter_init(&collisions, &iter);
2585         while ((e = hashmap_iter_next(&iter))) {
2586                 free(e->target_file);
2587                 string_list_clear(&e->source_files, 0);
2588         }
2589         hashmap_free(&collisions, 1);
2590         return renames;
2591 }
2592
2593 static int process_renames(struct merge_options *opt,
2594                            struct string_list *a_renames,
2595                            struct string_list *b_renames)
2596 {
2597         int clean_merge = 1, i, j;
2598         struct string_list a_by_dst = STRING_LIST_INIT_NODUP;
2599         struct string_list b_by_dst = STRING_LIST_INIT_NODUP;
2600         const struct rename *sre;
2601
2602         for (i = 0; i < a_renames->nr; i++) {
2603                 sre = a_renames->items[i].util;
2604                 string_list_insert(&a_by_dst, sre->pair->two->path)->util
2605                         = (void *)sre;
2606         }
2607         for (i = 0; i < b_renames->nr; i++) {
2608                 sre = b_renames->items[i].util;
2609                 string_list_insert(&b_by_dst, sre->pair->two->path)->util
2610                         = (void *)sre;
2611         }
2612
2613         for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
2614                 struct string_list *renames1, *renames2Dst;
2615                 struct rename *ren1 = NULL, *ren2 = NULL;
2616                 const char *ren1_src, *ren1_dst;
2617                 struct string_list_item *lookup;
2618
2619                 if (i >= a_renames->nr) {
2620                         ren2 = b_renames->items[j++].util;
2621                 } else if (j >= b_renames->nr) {
2622                         ren1 = a_renames->items[i++].util;
2623                 } else {
2624                         int compare = strcmp(a_renames->items[i].string,
2625                                              b_renames->items[j].string);
2626                         if (compare <= 0)
2627                                 ren1 = a_renames->items[i++].util;
2628                         if (compare >= 0)
2629                                 ren2 = b_renames->items[j++].util;
2630                 }
2631
2632                 /* TODO: refactor, so that 1/2 are not needed */
2633                 if (ren1) {
2634                         renames1 = a_renames;
2635                         renames2Dst = &b_by_dst;
2636                 } else {
2637                         renames1 = b_renames;
2638                         renames2Dst = &a_by_dst;
2639                         SWAP(ren2, ren1);
2640                 }
2641
2642                 if (ren1->processed)
2643                         continue;
2644                 ren1->processed = 1;
2645                 ren1->dst_entry->processed = 1;
2646                 /* BUG: We should only mark src_entry as processed if we
2647                  * are not dealing with a rename + add-source case.
2648                  */
2649                 ren1->src_entry->processed = 1;
2650
2651                 ren1_src = ren1->pair->one->path;
2652                 ren1_dst = ren1->pair->two->path;
2653
2654                 if (ren2) {
2655                         /* One file renamed on both sides */
2656                         const char *ren2_src = ren2->pair->one->path;
2657                         const char *ren2_dst = ren2->pair->two->path;
2658                         enum rename_type rename_type;
2659                         if (strcmp(ren1_src, ren2_src) != 0)
2660                                 BUG("ren1_src != ren2_src");
2661                         ren2->dst_entry->processed = 1;
2662                         ren2->processed = 1;
2663                         if (strcmp(ren1_dst, ren2_dst) != 0) {
2664                                 rename_type = RENAME_ONE_FILE_TO_TWO;
2665                                 clean_merge = 0;
2666                         } else {
2667                                 rename_type = RENAME_ONE_FILE_TO_ONE;
2668                                 /* BUG: We should only remove ren1_src in
2669                                  * the base stage (think of rename +
2670                                  * add-source cases).
2671                                  */
2672                                 remove_file(opt, 1, ren1_src, 1);
2673                                 update_entry(ren1->dst_entry,
2674                                              ren1->pair->one,
2675                                              ren1->pair->two,
2676                                              ren2->pair->two);
2677                         }
2678                         setup_rename_conflict_info(rename_type, opt, ren1, ren2);
2679                 } else if ((lookup = string_list_lookup(renames2Dst, ren1_dst))) {
2680                         /* Two different files renamed to the same thing */
2681                         char *ren2_dst;
2682                         ren2 = lookup->util;
2683                         ren2_dst = ren2->pair->two->path;
2684                         if (strcmp(ren1_dst, ren2_dst) != 0)
2685                                 BUG("ren1_dst != ren2_dst");
2686
2687                         clean_merge = 0;
2688                         ren2->processed = 1;
2689                         /*
2690                          * BUG: We should only mark src_entry as processed
2691                          * if we are not dealing with a rename + add-source
2692                          * case.
2693                          */
2694                         ren2->src_entry->processed = 1;
2695
2696                         setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,
2697                                                    opt, ren1, ren2);
2698                 } else {
2699                         /* Renamed in 1, maybe changed in 2 */
2700                         /* we only use sha1 and mode of these */
2701                         struct diff_filespec src_other, dst_other;
2702                         int try_merge;
2703
2704                         /*
2705                          * unpack_trees loads entries from common-commit
2706                          * into stage 1, from head-commit into stage 2, and
2707                          * from merge-commit into stage 3.  We keep track
2708                          * of which side corresponds to the rename.
2709                          */
2710                         int renamed_stage = a_renames == renames1 ? 2 : 3;
2711                         int other_stage =   a_renames == renames1 ? 3 : 2;
2712
2713                         /* BUG: We should only remove ren1_src in the base
2714                          * stage and in other_stage (think of rename +
2715                          * add-source case).
2716                          */
2717                         remove_file(opt, 1, ren1_src,
2718                                     renamed_stage == 2 || !was_tracked(opt, ren1_src));
2719
2720                         oidcpy(&src_other.oid,
2721                                &ren1->src_entry->stages[other_stage].oid);
2722                         src_other.mode = ren1->src_entry->stages[other_stage].mode;
2723                         oidcpy(&dst_other.oid,
2724                                &ren1->dst_entry->stages[other_stage].oid);
2725                         dst_other.mode = ren1->dst_entry->stages[other_stage].mode;
2726                         try_merge = 0;
2727
2728                         if (oid_eq(&src_other.oid, &null_oid) &&
2729                             ren1->add_turned_into_rename) {
2730                                 setup_rename_conflict_info(RENAME_VIA_DIR,
2731                                                            opt, ren1, NULL);
2732                         } else if (oid_eq(&src_other.oid, &null_oid)) {
2733                                 setup_rename_conflict_info(RENAME_DELETE,
2734                                                            opt, ren1, NULL);
2735                         } else if ((dst_other.mode == ren1->pair->two->mode) &&
2736                                    oid_eq(&dst_other.oid, &ren1->pair->two->oid)) {
2737                                 /*
2738                                  * Added file on the other side identical to
2739                                  * the file being renamed: clean merge.
2740                                  * Also, there is no need to overwrite the
2741                                  * file already in the working copy, so call
2742                                  * update_file_flags() instead of
2743                                  * update_file().
2744                                  */
2745                                 if (update_file_flags(opt,
2746                                                       ren1->pair->two,
2747                                                       ren1_dst,
2748                                                       1, /* update_cache */
2749                                                       0  /* update_wd    */))
2750                                         clean_merge = -1;
2751                         } else if (!oid_eq(&dst_other.oid, &null_oid)) {
2752                                 /*
2753                                  * Probably not a clean merge, but it's
2754                                  * premature to set clean_merge to 0 here,
2755                                  * because if the rename merges cleanly and
2756                                  * the merge exactly matches the newly added
2757                                  * file, then the merge will be clean.
2758                                  */
2759                                 setup_rename_conflict_info(RENAME_ADD,
2760                                                            opt, ren1, NULL);
2761                         } else
2762                                 try_merge = 1;
2763
2764                         if (clean_merge < 0)
2765                                 goto cleanup_and_return;
2766                         if (try_merge) {
2767                                 struct diff_filespec *o, *a, *b;
2768                                 src_other.path = (char *)ren1_src;
2769
2770                                 o = ren1->pair->one;
2771                                 if (a_renames == renames1) {
2772                                         a = ren1->pair->two;
2773                                         b = &src_other;
2774                                 } else {
2775                                         b = ren1->pair->two;
2776                                         a = &src_other;
2777                                 }
2778                                 update_entry(ren1->dst_entry, o, a, b);
2779                                 setup_rename_conflict_info(RENAME_NORMAL,
2780                                                            opt, ren1, NULL);
2781                         }
2782                 }
2783         }
2784 cleanup_and_return:
2785         string_list_clear(&a_by_dst, 0);
2786         string_list_clear(&b_by_dst, 0);
2787
2788         return clean_merge;
2789 }
2790
2791 struct rename_info {
2792         struct string_list *head_renames;
2793         struct string_list *merge_renames;
2794 };
2795
2796 static void initial_cleanup_rename(struct diff_queue_struct *pairs,
2797                                    struct hashmap *dir_renames)
2798 {
2799         struct hashmap_iter iter;
2800         struct dir_rename_entry *e;
2801
2802         hashmap_iter_init(dir_renames, &iter);
2803         while ((e = hashmap_iter_next(&iter))) {
2804                 free(e->dir);
2805                 strbuf_release(&e->new_dir);
2806                 /* possible_new_dirs already cleared in get_directory_renames */
2807         }
2808         hashmap_free(dir_renames, 1);
2809         free(dir_renames);
2810
2811         free(pairs->queue);
2812         free(pairs);
2813 }
2814
2815 static int detect_and_process_renames(struct merge_options *opt,
2816                                       struct tree *common,
2817                                       struct tree *head,
2818                                       struct tree *merge,
2819                                       struct string_list *entries,
2820                                       struct rename_info *ri)
2821 {
2822         struct diff_queue_struct *head_pairs, *merge_pairs;
2823         struct hashmap *dir_re_head, *dir_re_merge;
2824         int clean = 1;
2825
2826         ri->head_renames = NULL;
2827         ri->merge_renames = NULL;
2828
2829         if (!merge_detect_rename(opt))
2830                 return 1;
2831
2832         head_pairs = get_diffpairs(opt, common, head);
2833         merge_pairs = get_diffpairs(opt, common, merge);
2834
2835         if (opt->detect_directory_renames) {
2836                 dir_re_head = get_directory_renames(head_pairs);
2837                 dir_re_merge = get_directory_renames(merge_pairs);
2838
2839                 handle_directory_level_conflicts(opt,
2840                                                  dir_re_head, head,
2841                                                  dir_re_merge, merge);
2842         } else {
2843                 dir_re_head  = xmalloc(sizeof(*dir_re_head));
2844                 dir_re_merge = xmalloc(sizeof(*dir_re_merge));
2845                 dir_rename_init(dir_re_head);
2846                 dir_rename_init(dir_re_merge);
2847         }
2848
2849         ri->head_renames  = get_renames(opt, opt->branch1, head_pairs,
2850                                         dir_re_merge, dir_re_head, head,
2851                                         common, head, merge, entries,
2852                                         &clean);
2853         if (clean < 0)
2854                 goto cleanup;
2855         ri->merge_renames = get_renames(opt, opt->branch2, merge_pairs,
2856                                         dir_re_head, dir_re_merge, merge,
2857                                         common, head, merge, entries,
2858                                         &clean);
2859         if (clean < 0)
2860                 goto cleanup;
2861         clean &= process_renames(opt, ri->head_renames, ri->merge_renames);
2862
2863 cleanup:
2864         /*
2865          * Some cleanup is deferred until cleanup_renames() because the
2866          * data structures are still needed and referenced in
2867          * process_entry().  But there are a few things we can free now.
2868          */
2869         initial_cleanup_rename(head_pairs, dir_re_head);
2870         initial_cleanup_rename(merge_pairs, dir_re_merge);
2871
2872         return clean;
2873 }
2874
2875 static void final_cleanup_rename(struct string_list *rename)
2876 {
2877         const struct rename *re;
2878         int i;
2879
2880         if (rename == NULL)
2881                 return;
2882
2883         for (i = 0; i < rename->nr; i++) {
2884                 re = rename->items[i].util;
2885                 diff_free_filepair(re->pair);
2886         }
2887         string_list_clear(rename, 1);
2888         free(rename);
2889 }
2890
2891 static void final_cleanup_renames(struct rename_info *re_info)
2892 {
2893         final_cleanup_rename(re_info->head_renames);
2894         final_cleanup_rename(re_info->merge_renames);
2895 }
2896
2897 static int read_oid_strbuf(struct merge_options *opt,
2898                            const struct object_id *oid,
2899                            struct strbuf *dst)
2900 {
2901         void *buf;
2902         enum object_type type;
2903         unsigned long size;
2904         buf = read_object_file(oid, &type, &size);
2905         if (!buf)
2906                 return err(opt, _("cannot read object %s"), oid_to_hex(oid));
2907         if (type != OBJ_BLOB) {
2908                 free(buf);
2909                 return err(opt, _("object %s is not a blob"), oid_to_hex(oid));
2910         }
2911         strbuf_attach(dst, buf, size, size + 1);
2912         return 0;
2913 }
2914
2915 static int blob_unchanged(struct merge_options *opt,
2916                           const struct diff_filespec *o,
2917                           const struct diff_filespec *a,
2918                           int renormalize, const char *path)
2919 {
2920         struct strbuf obuf = STRBUF_INIT;
2921         struct strbuf abuf = STRBUF_INIT;
2922         int ret = 0; /* assume changed for safety */
2923         const struct index_state *idx = opt->repo->index;
2924
2925         if (a->mode != o->mode)
2926                 return 0;
2927         if (oid_eq(&o->oid, &a->oid))
2928                 return 1;
2929         if (!renormalize)
2930                 return 0;
2931
2932         if (read_oid_strbuf(opt, &o->oid, &obuf) ||
2933             read_oid_strbuf(opt, &a->oid, &abuf))
2934                 goto error_return;
2935         /*
2936          * Note: binary | is used so that both renormalizations are
2937          * performed.  Comparison can be skipped if both files are
2938          * unchanged since their sha1s have already been compared.
2939          */
2940         if (renormalize_buffer(idx, path, obuf.buf, obuf.len, &obuf) |
2941             renormalize_buffer(idx, path, abuf.buf, abuf.len, &abuf))
2942                 ret = (obuf.len == abuf.len && !memcmp(obuf.buf, abuf.buf, obuf.len));
2943
2944 error_return:
2945         strbuf_release(&obuf);
2946         strbuf_release(&abuf);
2947         return ret;
2948 }
2949
2950 static int handle_modify_delete(struct merge_options *opt,
2951                                 const char *path,
2952                                 const struct diff_filespec *o,
2953                                 const struct diff_filespec *a,
2954                                 const struct diff_filespec *b)
2955 {
2956         const char *modify_branch, *delete_branch;
2957         const struct diff_filespec *changed;
2958
2959         if (is_valid(a)) {
2960                 modify_branch = opt->branch1;
2961                 delete_branch = opt->branch2;
2962                 changed = a;
2963         } else {
2964                 modify_branch = opt->branch2;
2965                 delete_branch = opt->branch1;
2966                 changed = b;
2967         }
2968
2969         return handle_change_delete(opt,
2970                                     path, NULL,
2971                                     o, changed,
2972                                     modify_branch, delete_branch,
2973                                     _("modify"), _("modified"));
2974 }
2975
2976 static int handle_content_merge(struct merge_options *opt,
2977                                 const char *path,
2978                                 int is_dirty,
2979                                 const struct diff_filespec *o,
2980                                 const struct diff_filespec *a,
2981                                 const struct diff_filespec *b,
2982                                 struct rename_conflict_info *ci)
2983 {
2984         const char *reason = _("content");
2985         struct merge_file_info mfi;
2986         unsigned df_conflict_remains = 0;
2987
2988         if (!is_valid(o))
2989                 reason = _("add/add");
2990
2991         assert(o->path && a->path && b->path);
2992         if (ci && dir_in_way(opt->repo->index, path, !opt->call_depth,
2993                              S_ISGITLINK(ci->ren1->pair->two->mode)))
2994                 df_conflict_remains = 1;
2995
2996         if (merge_mode_and_contents(opt, o, a, b, path,
2997                                     opt->branch1, opt->branch2,
2998                                     opt->call_depth * 2, &mfi))
2999                 return -1;
3000
3001         /*
3002          * We can skip updating the working tree file iff:
3003          *   a) The merge is clean
3004          *   b) The merge matches what was in HEAD (content, mode, pathname)
3005          *   c) The target path is usable (i.e. not involved in D/F conflict)
3006          */
3007         if (mfi.clean && was_tracked_and_matches(opt, path, &mfi.blob) &&
3008             !df_conflict_remains) {
3009                 int pos;
3010                 struct cache_entry *ce;
3011
3012                 output(opt, 3, _("Skipped %s (merged same as existing)"), path);
3013                 if (add_cacheinfo(opt, &mfi.blob, path,
3014                                   0, (!opt->call_depth && !is_dirty), 0))
3015                         return -1;
3016                 /*
3017                  * However, add_cacheinfo() will delete the old cache entry
3018                  * and add a new one.  We need to copy over any skip_worktree
3019                  * flag to avoid making the file appear as if it were
3020                  * deleted by the user.
3021                  */
3022                 pos = index_name_pos(&opt->orig_index, path, strlen(path));
3023                 ce = opt->orig_index.cache[pos];
3024                 if (ce_skip_worktree(ce)) {
3025                         pos = index_name_pos(opt->repo->index, path, strlen(path));
3026                         ce = opt->repo->index->cache[pos];
3027                         ce->ce_flags |= CE_SKIP_WORKTREE;
3028                 }
3029                 return mfi.clean;
3030         }
3031
3032         if (!mfi.clean) {
3033                 if (S_ISGITLINK(mfi.blob.mode))
3034                         reason = _("submodule");
3035                 output(opt, 1, _("CONFLICT (%s): Merge conflict in %s"),
3036                                 reason, path);
3037                 if (ci && !df_conflict_remains)
3038                         if (update_stages(opt, path, o, a, b))
3039                                 return -1;
3040         }
3041
3042         if (df_conflict_remains || is_dirty) {
3043                 char *new_path;
3044                 if (opt->call_depth) {
3045                         remove_file_from_index(opt->repo->index, path);
3046                 } else {
3047                         if (!mfi.clean) {
3048                                 if (update_stages(opt, path, o, a, b))
3049                                         return -1;
3050                         } else {
3051                                 int file_from_stage2 = was_tracked(opt, path);
3052
3053                                 if (update_stages(opt, path, NULL,
3054                                                   file_from_stage2 ? &mfi.blob : NULL,
3055                                                   file_from_stage2 ? NULL : &mfi.blob))
3056                                         return -1;
3057                         }
3058
3059                 }
3060                 new_path = unique_path(opt, path, ci->ren1->branch);
3061                 if (is_dirty) {
3062                         output(opt, 1, _("Refusing to lose dirty file at %s"),
3063                                path);
3064                 }
3065                 output(opt, 1, _("Adding as %s instead"), new_path);
3066                 if (update_file(opt, 0, &mfi.blob, new_path)) {
3067                         free(new_path);
3068                         return -1;
3069                 }
3070                 free(new_path);
3071                 mfi.clean = 0;
3072         } else if (update_file(opt, mfi.clean, &mfi.blob, path))
3073                 return -1;
3074         return !is_dirty && mfi.clean;
3075 }
3076
3077 static int handle_rename_normal(struct merge_options *opt,
3078                                 const char *path,
3079                                 const struct diff_filespec *o,
3080                                 const struct diff_filespec *a,
3081                                 const struct diff_filespec *b,
3082                                 struct rename_conflict_info *ci)
3083 {
3084         /* Merge the content and write it out */
3085         return handle_content_merge(opt, path, was_dirty(opt, path),
3086                                     o, a, b, ci);
3087 }
3088
3089 /* Per entry merge function */
3090 static int process_entry(struct merge_options *opt,
3091                          const char *path, struct stage_data *entry)
3092 {
3093         int clean_merge = 1;
3094         int normalize = opt->renormalize;
3095
3096         struct diff_filespec *o = &entry->stages[1];
3097         struct diff_filespec *a = &entry->stages[2];
3098         struct diff_filespec *b = &entry->stages[3];
3099         int o_valid = is_valid(o);
3100         int a_valid = is_valid(a);
3101         int b_valid = is_valid(b);
3102         o->path = a->path = b->path = (char*)path;
3103
3104         entry->processed = 1;
3105         if (entry->rename_conflict_info) {
3106                 struct rename_conflict_info *ci = entry->rename_conflict_info;
3107                 struct diff_filespec *temp;
3108
3109                 /*
3110                  * For cases with a single rename, {o,a,b}->path have all been
3111                  * set to the rename target path; we need to set two of these
3112                  * back to the rename source.
3113                  * For rename/rename conflicts, we'll manually fix paths below.
3114                  */
3115                 temp = (opt->branch1 == ci->ren1->branch) ? b : a;
3116                 o->path = temp->path = ci->ren1->pair->one->path;
3117                 if (ci->ren2) {
3118                         assert(opt->branch1 == ci->ren1->branch);
3119                 }
3120
3121                 switch (ci->rename_type) {
3122                 case RENAME_NORMAL:
3123                 case RENAME_ONE_FILE_TO_ONE:
3124                         clean_merge = handle_rename_normal(opt, path, o, a, b,
3125                                                            ci);
3126                         break;
3127                 case RENAME_VIA_DIR:
3128                         clean_merge = 1;
3129                         if (handle_rename_via_dir(opt, ci))
3130                                 clean_merge = -1;
3131                         break;
3132                 case RENAME_ADD:
3133                         /*
3134                          * Probably unclean merge, but if the renamed file
3135                          * merges cleanly and the result can then be
3136                          * two-way merged cleanly with the added file, I
3137                          * guess it's a clean merge?
3138                          */
3139                         clean_merge = handle_rename_add(opt, ci);
3140                         break;
3141                 case RENAME_DELETE:
3142                         clean_merge = 0;
3143                         if (handle_rename_delete(opt, ci))
3144                                 clean_merge = -1;
3145                         break;
3146                 case RENAME_ONE_FILE_TO_TWO:
3147                         /*
3148                          * Manually fix up paths; note:
3149                          * ren[12]->pair->one->path are equal.
3150                          */
3151                         o->path = ci->ren1->pair->one->path;
3152                         a->path = ci->ren1->pair->two->path;
3153                         b->path = ci->ren2->pair->two->path;
3154
3155                         clean_merge = 0;
3156                         if (handle_rename_rename_1to2(opt, ci))
3157                                 clean_merge = -1;
3158                         break;
3159                 case RENAME_TWO_FILES_TO_ONE:
3160                         /*
3161                          * Manually fix up paths; note,
3162                          * ren[12]->pair->two->path are actually equal.
3163                          */
3164                         o->path = NULL;
3165                         a->path = ci->ren1->pair->two->path;
3166                         b->path = ci->ren2->pair->two->path;
3167
3168                         /*
3169                          * Probably unclean merge, but if the two renamed
3170                          * files merge cleanly and the two resulting files
3171                          * can then be two-way merged cleanly, I guess it's
3172                          * a clean merge?
3173                          */
3174                         clean_merge = handle_rename_rename_2to1(opt, ci);
3175                         break;
3176                 default:
3177                         entry->processed = 0;
3178                         break;
3179                 }
3180         } else if (o_valid && (!a_valid || !b_valid)) {
3181                 /* Case A: Deleted in one */
3182                 if ((!a_valid && !b_valid) ||
3183                     (!b_valid && blob_unchanged(opt, o, a, normalize, path)) ||
3184                     (!a_valid && blob_unchanged(opt, o, b, normalize, path))) {
3185                         /* Deleted in both or deleted in one and
3186                          * unchanged in the other */
3187                         if (a_valid)
3188                                 output(opt, 2, _("Removing %s"), path);
3189                         /* do not touch working file if it did not exist */
3190                         remove_file(opt, 1, path, !a_valid);
3191                 } else {
3192                         /* Modify/delete; deleted side may have put a directory in the way */
3193                         clean_merge = 0;
3194                         if (handle_modify_delete(opt, path, o, a, b))
3195                                 clean_merge = -1;
3196                 }
3197         } else if ((!o_valid && a_valid && !b_valid) ||
3198                    (!o_valid && !a_valid && b_valid)) {
3199                 /* Case B: Added in one. */
3200                 /* [nothing|directory] -> ([nothing|directory], file) */
3201
3202                 const char *add_branch;
3203                 const char *other_branch;
3204                 const char *conf;
3205                 const struct diff_filespec *contents;
3206
3207                 if (a_valid) {
3208                         add_branch = opt->branch1;
3209                         other_branch = opt->branch2;
3210                         contents = a;
3211                         conf = _("file/directory");
3212                 } else {
3213                         add_branch = opt->branch2;
3214                         other_branch = opt->branch1;
3215                         contents = b;
3216                         conf = _("directory/file");
3217                 }
3218                 if (dir_in_way(opt->repo->index, path,
3219                                !opt->call_depth && !S_ISGITLINK(a->mode),
3220                                0)) {
3221                         char *new_path = unique_path(opt, path, add_branch);
3222                         clean_merge = 0;
3223                         output(opt, 1, _("CONFLICT (%s): There is a directory with name %s in %s. "
3224                                "Adding %s as %s"),
3225                                conf, path, other_branch, path, new_path);
3226                         if (update_file(opt, 0, contents, new_path))
3227                                 clean_merge = -1;
3228                         else if (opt->call_depth)
3229                                 remove_file_from_index(opt->repo->index, path);
3230                         free(new_path);
3231                 } else {
3232                         output(opt, 2, _("Adding %s"), path);
3233                         /* do not overwrite file if already present */
3234                         if (update_file_flags(opt, contents, path, 1, !a_valid))
3235                                 clean_merge = -1;
3236                 }
3237         } else if (a_valid && b_valid) {
3238                 if (!o_valid) {
3239                         /* Case C: Added in both (check for same permissions) */
3240                         output(opt, 1,
3241                                _("CONFLICT (add/add): Merge conflict in %s"),
3242                                path);
3243                         clean_merge = handle_file_collision(opt,
3244                                                             path, NULL, NULL,
3245                                                             opt->branch1,
3246                                                             opt->branch2,
3247                                                             a, b);
3248                 } else {
3249                         /* case D: Modified in both, but differently. */
3250                         int is_dirty = 0; /* unpack_trees would have bailed if dirty */
3251                         clean_merge = handle_content_merge(opt, path, is_dirty,
3252                                                            o, a, b, NULL);
3253                 }
3254         } else if (!o_valid && !a_valid && !b_valid) {
3255                 /*
3256                  * this entry was deleted altogether. a_mode == 0 means
3257                  * we had that path and want to actively remove it.
3258                  */
3259                 remove_file(opt, 1, path, !a->mode);
3260         } else
3261                 BUG("fatal merge failure, shouldn't happen.");
3262
3263         return clean_merge;
3264 }
3265
3266 int merge_trees(struct merge_options *opt,
3267                 struct tree *head,
3268                 struct tree *merge,
3269                 struct tree *common,
3270                 struct tree **result)
3271 {
3272         struct index_state *istate = opt->repo->index;
3273         int code, clean;
3274         struct strbuf sb = STRBUF_INIT;
3275
3276         if (!opt->call_depth && repo_index_has_changes(opt->repo, head, &sb)) {
3277                 err(opt, _("Your local changes to the following files would be overwritten by merge:\n  %s"),
3278                     sb.buf);
3279                 return -1;
3280         }
3281
3282         if (opt->subtree_shift) {
3283                 merge = shift_tree_object(opt->repo, head, merge, opt->subtree_shift);
3284                 common = shift_tree_object(opt->repo, head, common, opt->subtree_shift);
3285         }
3286
3287         if (oid_eq(&common->object.oid, &merge->object.oid)) {
3288                 output(opt, 0, _("Already up to date!"));
3289                 *result = head;
3290                 return 1;
3291         }
3292
3293         code = unpack_trees_start(opt, common, head, merge);
3294
3295         if (code != 0) {
3296                 if (show(opt, 4) || opt->call_depth)
3297                         err(opt, _("merging of trees %s and %s failed"),
3298                             oid_to_hex(&head->object.oid),
3299                             oid_to_hex(&merge->object.oid));
3300                 unpack_trees_finish(opt);
3301                 return -1;
3302         }
3303
3304         if (unmerged_index(istate)) {
3305                 struct string_list *entries;
3306                 struct rename_info re_info;
3307                 int i;
3308                 /*
3309                  * Only need the hashmap while processing entries, so
3310                  * initialize it here and free it when we are done running
3311                  * through the entries. Keeping it in the merge_options as
3312                  * opposed to decaring a local hashmap is for convenience
3313                  * so that we don't have to pass it to around.
3314                  */
3315                 hashmap_init(&opt->current_file_dir_set, path_hashmap_cmp, NULL, 512);
3316                 get_files_dirs(opt, head);
3317                 get_files_dirs(opt, merge);
3318
3319                 entries = get_unmerged(opt->repo->index);
3320                 clean = detect_and_process_renames(opt, common, head, merge,
3321                                                    entries, &re_info);
3322                 record_df_conflict_files(opt, entries);
3323                 if (clean < 0)
3324                         goto cleanup;
3325                 for (i = entries->nr-1; 0 <= i; i--) {
3326                         const char *path = entries->items[i].string;
3327                         struct stage_data *e = entries->items[i].util;
3328                         if (!e->processed) {
3329                                 int ret = process_entry(opt, path, e);
3330                                 if (!ret)
3331                                         clean = 0;
3332                                 else if (ret < 0) {
3333                                         clean = ret;
3334                                         goto cleanup;
3335                                 }
3336                         }
3337                 }
3338                 for (i = 0; i < entries->nr; i++) {
3339                         struct stage_data *e = entries->items[i].util;
3340                         if (!e->processed)
3341                                 BUG("unprocessed path??? %s",
3342                                     entries->items[i].string);
3343                 }
3344
3345         cleanup:
3346                 final_cleanup_renames(&re_info);
3347
3348                 string_list_clear(entries, 1);
3349                 free(entries);
3350
3351                 hashmap_free(&opt->current_file_dir_set, 1);
3352
3353                 if (clean < 0) {
3354                         unpack_trees_finish(opt);
3355                         return clean;
3356                 }
3357         }
3358         else
3359                 clean = 1;
3360
3361         unpack_trees_finish(opt);
3362
3363         if (opt->call_depth && !(*result = write_tree_from_memory(opt)))
3364                 return -1;
3365
3366         return clean;
3367 }
3368
3369 static struct commit_list *reverse_commit_list(struct commit_list *list)
3370 {
3371         struct commit_list *next = NULL, *current, *backup;
3372         for (current = list; current; current = backup) {
3373                 backup = current->next;
3374                 current->next = next;
3375                 next = current;
3376         }
3377         return next;
3378 }
3379
3380 /*
3381  * Merge the commits h1 and h2, return the resulting virtual
3382  * commit object and a flag indicating the cleanness of the merge.
3383  */
3384 int merge_recursive(struct merge_options *opt,
3385                     struct commit *h1,
3386                     struct commit *h2,
3387                     struct commit_list *ca,
3388                     struct commit **result)
3389 {
3390         struct commit_list *iter;
3391         struct commit *merged_common_ancestors;
3392         struct tree *mrtree;
3393         int clean;
3394
3395         if (show(opt, 4)) {
3396                 output(opt, 4, _("Merging:"));
3397                 output_commit_title(opt, h1);
3398                 output_commit_title(opt, h2);
3399         }
3400
3401         if (!ca) {
3402                 ca = get_merge_bases(h1, h2);
3403                 ca = reverse_commit_list(ca);
3404         }
3405
3406         if (show(opt, 5)) {
3407                 unsigned cnt = commit_list_count(ca);
3408
3409                 output(opt, 5, Q_("found %u common ancestor:",
3410                                 "found %u common ancestors:", cnt), cnt);
3411                 for (iter = ca; iter; iter = iter->next)
3412                         output_commit_title(opt, iter->item);
3413         }
3414
3415         merged_common_ancestors = pop_commit(&ca);
3416         if (merged_common_ancestors == NULL) {
3417                 /* if there is no common ancestor, use an empty tree */
3418                 struct tree *tree;
3419
3420                 tree = lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);
3421                 merged_common_ancestors = make_virtual_commit(opt->repo, tree, "ancestor");
3422         }
3423
3424         for (iter = ca; iter; iter = iter->next) {
3425                 const char *saved_b1, *saved_b2;
3426                 opt->call_depth++;
3427                 /*
3428                  * When the merge fails, the result contains files
3429                  * with conflict markers. The cleanness flag is
3430                  * ignored (unless indicating an error), it was never
3431                  * actually used, as result of merge_trees has always
3432                  * overwritten it: the committed "conflicts" were
3433                  * already resolved.
3434                  */
3435                 discard_index(opt->repo->index);
3436                 saved_b1 = opt->branch1;
3437                 saved_b2 = opt->branch2;
3438                 opt->branch1 = "Temporary merge branch 1";
3439                 opt->branch2 = "Temporary merge branch 2";
3440                 if (merge_recursive(opt, merged_common_ancestors, iter->item,
3441                                     NULL, &merged_common_ancestors) < 0)
3442                         return -1;
3443                 opt->branch1 = saved_b1;
3444                 opt->branch2 = saved_b2;
3445                 opt->call_depth--;
3446
3447                 if (!merged_common_ancestors)
3448                         return err(opt, _("merge returned no commit"));
3449         }
3450
3451         discard_index(opt->repo->index);
3452         if (!opt->call_depth)
3453                 repo_read_index(opt->repo);
3454
3455         opt->ancestor = "merged common ancestors";
3456         clean = merge_trees(opt, get_commit_tree(h1), get_commit_tree(h2),
3457                             get_commit_tree(merged_common_ancestors),
3458                             &mrtree);
3459         if (clean < 0) {
3460                 flush_output(opt);
3461                 return clean;
3462         }
3463
3464         if (opt->call_depth) {
3465                 *result = make_virtual_commit(opt->repo, mrtree, "merged tree");
3466                 commit_list_insert(h1, &(*result)->parents);
3467                 commit_list_insert(h2, &(*result)->parents->next);
3468         }
3469         flush_output(opt);
3470         if (!opt->call_depth && opt->buffer_output < 2)
3471                 strbuf_release(&opt->obuf);
3472         if (show(opt, 2))
3473                 diff_warn_rename_limit("merge.renamelimit",
3474                                        opt->needed_rename_limit, 0);
3475         return clean;
3476 }
3477
3478 static struct commit *get_ref(struct repository *repo, const struct object_id *oid,
3479                               const char *name)
3480 {
3481         struct object *object;
3482
3483         object = deref_tag(repo, parse_object(repo, oid),
3484                            name, strlen(name));
3485         if (!object)
3486                 return NULL;
3487         if (object->type == OBJ_TREE)
3488                 return make_virtual_commit(repo, (struct tree*)object, name);
3489         if (object->type != OBJ_COMMIT)
3490                 return NULL;
3491         if (parse_commit((struct commit *)object))
3492                 return NULL;
3493         return (struct commit *)object;
3494 }
3495
3496 int merge_recursive_generic(struct merge_options *opt,
3497                             const struct object_id *head,
3498                             const struct object_id *merge,
3499                             int num_base_list,
3500                             const struct object_id **base_list,
3501                             struct commit **result)
3502 {
3503         int clean;
3504         struct lock_file lock = LOCK_INIT;
3505         struct commit *head_commit = get_ref(opt->repo, head, opt->branch1);
3506         struct commit *next_commit = get_ref(opt->repo, merge, opt->branch2);
3507         struct commit_list *ca = NULL;
3508
3509         if (base_list) {
3510                 int i;
3511                 for (i = 0; i < num_base_list; ++i) {
3512                         struct commit *base;
3513                         if (!(base = get_ref(opt->repo, base_list[i], oid_to_hex(base_list[i]))))
3514                                 return err(opt, _("Could not parse object '%s'"),
3515                                            oid_to_hex(base_list[i]));
3516                         commit_list_insert(base, &ca);
3517                 }
3518         }
3519
3520         repo_hold_locked_index(opt->repo, &lock, LOCK_DIE_ON_ERROR);
3521         clean = merge_recursive(opt, head_commit, next_commit, ca,
3522                                 result);
3523         if (clean < 0) {
3524                 rollback_lock_file(&lock);
3525                 return clean;
3526         }
3527
3528         if (write_locked_index(opt->repo->index, &lock,
3529                                COMMIT_LOCK | SKIP_IF_UNCHANGED))
3530                 return err(opt, _("Unable to write index."));
3531
3532         return clean ? 0 : 1;
3533 }
3534
3535 static void merge_recursive_config(struct merge_options *opt)
3536 {
3537         char *value = NULL;
3538         git_config_get_int("merge.verbosity", &opt->verbosity);
3539         git_config_get_int("diff.renamelimit", &opt->diff_rename_limit);
3540         git_config_get_int("merge.renamelimit", &opt->merge_rename_limit);
3541         if (!git_config_get_string("diff.renames", &value)) {
3542                 opt->diff_detect_rename = git_config_rename("diff.renames", value);
3543                 free(value);
3544         }
3545         if (!git_config_get_string("merge.renames", &value)) {
3546                 opt->merge_detect_rename = git_config_rename("merge.renames", value);
3547                 free(value);
3548         }
3549         git_config(git_xmerge_config, NULL);
3550 }
3551
3552 void init_merge_options(struct merge_options *opt,
3553                         struct repository *repo)
3554 {
3555         const char *merge_verbosity;
3556         memset(opt, 0, sizeof(struct merge_options));
3557         opt->repo = repo;
3558         opt->verbosity = 2;
3559         opt->buffer_output = 1;
3560         opt->diff_rename_limit = -1;
3561         opt->merge_rename_limit = -1;
3562         opt->renormalize = 0;
3563         opt->diff_detect_rename = -1;
3564         opt->merge_detect_rename = -1;
3565         opt->detect_directory_renames = 1;
3566         merge_recursive_config(opt);
3567         merge_verbosity = getenv("GIT_MERGE_VERBOSITY");
3568         if (merge_verbosity)
3569                 opt->verbosity = strtol(merge_verbosity, NULL, 10);
3570         if (opt->verbosity >= 5)
3571                 opt->buffer_output = 0;
3572         strbuf_init(&opt->obuf, 0);
3573         string_list_init(&opt->df_conflict_file_set, 1);
3574 }
3575
3576 int parse_merge_opt(struct merge_options *opt, const char *s)
3577 {
3578         const char *arg;
3579
3580         if (!s || !*s)
3581                 return -1;
3582         if (!strcmp(s, "ours"))
3583                 opt->recursive_variant = MERGE_RECURSIVE_OURS;
3584         else if (!strcmp(s, "theirs"))
3585                 opt->recursive_variant = MERGE_RECURSIVE_THEIRS;
3586         else if (!strcmp(s, "subtree"))
3587                 opt->subtree_shift = "";
3588         else if (skip_prefix(s, "subtree=", &arg))
3589                 opt->subtree_shift = arg;
3590         else if (!strcmp(s, "patience"))
3591                 opt->xdl_opts = DIFF_WITH_ALG(opt, PATIENCE_DIFF);
3592         else if (!strcmp(s, "histogram"))
3593                 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
3594         else if (skip_prefix(s, "diff-algorithm=", &arg)) {
3595                 long value = parse_algorithm_value(arg);
3596                 if (value < 0)
3597                         return -1;
3598                 /* clear out previous settings */
3599                 DIFF_XDL_CLR(opt, NEED_MINIMAL);
3600                 opt->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3601                 opt->xdl_opts |= value;
3602         }
3603         else if (!strcmp(s, "ignore-space-change"))
3604                 DIFF_XDL_SET(opt, IGNORE_WHITESPACE_CHANGE);
3605         else if (!strcmp(s, "ignore-all-space"))
3606                 DIFF_XDL_SET(opt, IGNORE_WHITESPACE);
3607         else if (!strcmp(s, "ignore-space-at-eol"))
3608                 DIFF_XDL_SET(opt, IGNORE_WHITESPACE_AT_EOL);
3609         else if (!strcmp(s, "ignore-cr-at-eol"))
3610                 DIFF_XDL_SET(opt, IGNORE_CR_AT_EOL);
3611         else if (!strcmp(s, "renormalize"))
3612                 opt->renormalize = 1;
3613         else if (!strcmp(s, "no-renormalize"))
3614                 opt->renormalize = 0;
3615         else if (!strcmp(s, "no-renames"))
3616                 opt->merge_detect_rename = 0;
3617         else if (!strcmp(s, "find-renames")) {
3618                 opt->merge_detect_rename = 1;
3619                 opt->rename_score = 0;
3620         }
3621         else if (skip_prefix(s, "find-renames=", &arg) ||
3622                  skip_prefix(s, "rename-threshold=", &arg)) {
3623                 if ((opt->rename_score = parse_rename_score(&arg)) == -1 || *arg != 0)
3624                         return -1;
3625                 opt->merge_detect_rename = 1;
3626         }
3627         /*
3628          * Please update $__git_merge_strategy_options in
3629          * git-completion.bash when you add new options
3630          */
3631         else
3632                 return -1;
3633         return 0;
3634 }