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