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