merge-recursive: make !o->detect_rename codepath more obvious
[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 "commit.h"
12 #include "blob.h"
13 #include "builtin.h"
14 #include "tree-walk.h"
15 #include "diff.h"
16 #include "diffcore.h"
17 #include "tag.h"
18 #include "unpack-trees.h"
19 #include "string-list.h"
20 #include "xdiff-interface.h"
21 #include "ll-merge.h"
22 #include "attr.h"
23 #include "merge-recursive.h"
24 #include "dir.h"
25 #include "submodule.h"
26
27 struct path_hashmap_entry {
28         struct hashmap_entry e;
29         char path[FLEX_ARRAY];
30 };
31
32 static int path_hashmap_cmp(const void *cmp_data,
33                             const void *entry,
34                             const void *entry_or_key,
35                             const void *keydata)
36 {
37         const struct path_hashmap_entry *a = entry;
38         const struct path_hashmap_entry *b = entry_or_key;
39         const char *key = keydata;
40
41         if (ignore_case)
42                 return strcasecmp(a->path, key ? key : b->path);
43         else
44                 return strcmp(a->path, key ? key : b->path);
45 }
46
47 static unsigned int path_hash(const char *path)
48 {
49         return ignore_case ? strihash(path) : strhash(path);
50 }
51
52 static void flush_output(struct merge_options *o)
53 {
54         if (o->buffer_output < 2 && o->obuf.len) {
55                 fputs(o->obuf.buf, stdout);
56                 strbuf_reset(&o->obuf);
57         }
58 }
59
60 static int err(struct merge_options *o, const char *err, ...)
61 {
62         va_list params;
63
64         if (o->buffer_output < 2)
65                 flush_output(o);
66         else {
67                 strbuf_complete(&o->obuf, '\n');
68                 strbuf_addstr(&o->obuf, "error: ");
69         }
70         va_start(params, err);
71         strbuf_vaddf(&o->obuf, err, params);
72         va_end(params);
73         if (o->buffer_output > 1)
74                 strbuf_addch(&o->obuf, '\n');
75         else {
76                 error("%s", o->obuf.buf);
77                 strbuf_reset(&o->obuf);
78         }
79
80         return -1;
81 }
82
83 static struct tree *shift_tree_object(struct tree *one, struct tree *two,
84                                       const char *subtree_shift)
85 {
86         struct object_id shifted;
87
88         if (!*subtree_shift) {
89                 shift_tree(&one->object.oid, &two->object.oid, &shifted, 0);
90         } else {
91                 shift_tree_by(&one->object.oid, &two->object.oid, &shifted,
92                               subtree_shift);
93         }
94         if (!oidcmp(&two->object.oid, &shifted))
95                 return two;
96         return lookup_tree(&shifted);
97 }
98
99 static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
100 {
101         struct commit *commit = alloc_commit_node();
102
103         set_merge_remote_desc(commit, comment, (struct object *)commit);
104         commit->tree = tree;
105         commit->object.parsed = 1;
106         return commit;
107 }
108
109 /*
110  * Since we use get_tree_entry(), which does not put the read object into
111  * the object pool, we cannot rely on a == b.
112  */
113 static int oid_eq(const struct object_id *a, const struct object_id *b)
114 {
115         if (!a && !b)
116                 return 2;
117         return a && b && oidcmp(a, b) == 0;
118 }
119
120 enum rename_type {
121         RENAME_NORMAL = 0,
122         RENAME_DELETE,
123         RENAME_ONE_FILE_TO_ONE,
124         RENAME_ONE_FILE_TO_TWO,
125         RENAME_TWO_FILES_TO_ONE
126 };
127
128 struct rename_conflict_info {
129         enum rename_type rename_type;
130         struct diff_filepair *pair1;
131         struct diff_filepair *pair2;
132         const char *branch1;
133         const char *branch2;
134         struct stage_data *dst_entry1;
135         struct stage_data *dst_entry2;
136         struct diff_filespec ren1_other;
137         struct diff_filespec ren2_other;
138 };
139
140 /*
141  * Since we want to write the index eventually, we cannot reuse the index
142  * for these (temporary) data.
143  */
144 struct stage_data {
145         struct {
146                 unsigned mode;
147                 struct object_id oid;
148         } stages[4];
149         struct rename_conflict_info *rename_conflict_info;
150         unsigned processed:1;
151 };
152
153 static inline void setup_rename_conflict_info(enum rename_type rename_type,
154                                               struct diff_filepair *pair1,
155                                               struct diff_filepair *pair2,
156                                               const char *branch1,
157                                               const char *branch2,
158                                               struct stage_data *dst_entry1,
159                                               struct stage_data *dst_entry2,
160                                               struct merge_options *o,
161                                               struct stage_data *src_entry1,
162                                               struct stage_data *src_entry2)
163 {
164         struct rename_conflict_info *ci = xcalloc(1, sizeof(struct rename_conflict_info));
165         ci->rename_type = rename_type;
166         ci->pair1 = pair1;
167         ci->branch1 = branch1;
168         ci->branch2 = branch2;
169
170         ci->dst_entry1 = dst_entry1;
171         dst_entry1->rename_conflict_info = ci;
172         dst_entry1->processed = 0;
173
174         assert(!pair2 == !dst_entry2);
175         if (dst_entry2) {
176                 ci->dst_entry2 = dst_entry2;
177                 ci->pair2 = pair2;
178                 dst_entry2->rename_conflict_info = ci;
179         }
180
181         if (rename_type == RENAME_TWO_FILES_TO_ONE) {
182                 /*
183                  * For each rename, there could have been
184                  * modifications on the side of history where that
185                  * file was not renamed.
186                  */
187                 int ostage1 = o->branch1 == branch1 ? 3 : 2;
188                 int ostage2 = ostage1 ^ 1;
189
190                 ci->ren1_other.path = pair1->one->path;
191                 oidcpy(&ci->ren1_other.oid, &src_entry1->stages[ostage1].oid);
192                 ci->ren1_other.mode = src_entry1->stages[ostage1].mode;
193
194                 ci->ren2_other.path = pair2->one->path;
195                 oidcpy(&ci->ren2_other.oid, &src_entry2->stages[ostage2].oid);
196                 ci->ren2_other.mode = src_entry2->stages[ostage2].mode;
197         }
198 }
199
200 static int show(struct merge_options *o, int v)
201 {
202         return (!o->call_depth && o->verbosity >= v) || o->verbosity >= 5;
203 }
204
205 __attribute__((format (printf, 3, 4)))
206 static void output(struct merge_options *o, int v, const char *fmt, ...)
207 {
208         va_list ap;
209
210         if (!show(o, v))
211                 return;
212
213         strbuf_addchars(&o->obuf, ' ', o->call_depth * 2);
214
215         va_start(ap, fmt);
216         strbuf_vaddf(&o->obuf, fmt, ap);
217         va_end(ap);
218
219         strbuf_addch(&o->obuf, '\n');
220         if (!o->buffer_output)
221                 flush_output(o);
222 }
223
224 static void output_commit_title(struct merge_options *o, struct commit *commit)
225 {
226         strbuf_addchars(&o->obuf, ' ', o->call_depth * 2);
227         if (commit->util)
228                 strbuf_addf(&o->obuf, "virtual %s\n",
229                         merge_remote_util(commit)->name);
230         else {
231                 strbuf_add_unique_abbrev(&o->obuf, commit->object.oid.hash,
232                                          DEFAULT_ABBREV);
233                 strbuf_addch(&o->obuf, ' ');
234                 if (parse_commit(commit) != 0)
235                         strbuf_addstr(&o->obuf, _("(bad commit)\n"));
236                 else {
237                         const char *title;
238                         const char *msg = get_commit_buffer(commit, NULL);
239                         int len = find_commit_subject(msg, &title);
240                         if (len)
241                                 strbuf_addf(&o->obuf, "%.*s\n", len, title);
242                         unuse_commit_buffer(commit, msg);
243                 }
244         }
245         flush_output(o);
246 }
247
248 static int add_cacheinfo(struct merge_options *o,
249                 unsigned int mode, const struct object_id *oid,
250                 const char *path, int stage, int refresh, int options)
251 {
252         struct cache_entry *ce;
253         int ret;
254
255         ce = make_cache_entry(mode, oid ? oid->hash : null_sha1, path, stage, 0);
256         if (!ce)
257                 return err(o, _("addinfo_cache failed for path '%s'"), path);
258
259         ret = add_cache_entry(ce, options);
260         if (refresh) {
261                 struct cache_entry *nce;
262
263                 nce = refresh_cache_entry(ce, CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING);
264                 if (!nce)
265                         return err(o, _("addinfo_cache failed for path '%s'"), path);
266                 if (nce != ce)
267                         ret = add_cache_entry(nce, options);
268         }
269         return ret;
270 }
271
272 static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
273 {
274         parse_tree(tree);
275         init_tree_desc(desc, tree->buffer, tree->size);
276 }
277
278 static int git_merge_trees(int index_only,
279                            struct tree *common,
280                            struct tree *head,
281                            struct tree *merge)
282 {
283         int rc;
284         struct tree_desc t[3];
285         struct unpack_trees_options opts;
286
287         memset(&opts, 0, sizeof(opts));
288         if (index_only)
289                 opts.index_only = 1;
290         else
291                 opts.update = 1;
292         opts.merge = 1;
293         opts.head_idx = 2;
294         opts.fn = threeway_merge;
295         opts.src_index = &the_index;
296         opts.dst_index = &the_index;
297         setup_unpack_trees_porcelain(&opts, "merge");
298
299         init_tree_desc_from_tree(t+0, common);
300         init_tree_desc_from_tree(t+1, head);
301         init_tree_desc_from_tree(t+2, merge);
302
303         rc = unpack_trees(3, t, &opts);
304         cache_tree_free(&active_cache_tree);
305         return rc;
306 }
307
308 struct tree *write_tree_from_memory(struct merge_options *o)
309 {
310         struct tree *result = NULL;
311
312         if (unmerged_cache()) {
313                 int i;
314                 fprintf(stderr, "BUG: There are unmerged index entries:\n");
315                 for (i = 0; i < active_nr; i++) {
316                         const struct cache_entry *ce = active_cache[i];
317                         if (ce_stage(ce))
318                                 fprintf(stderr, "BUG: %d %.*s\n", ce_stage(ce),
319                                         (int)ce_namelen(ce), ce->name);
320                 }
321                 die("BUG: unmerged index entries in merge-recursive.c");
322         }
323
324         if (!active_cache_tree)
325                 active_cache_tree = cache_tree();
326
327         if (!cache_tree_fully_valid(active_cache_tree) &&
328             cache_tree_update(&the_index, 0) < 0) {
329                 err(o, _("error building trees"));
330                 return NULL;
331         }
332
333         result = lookup_tree(&active_cache_tree->oid);
334
335         return result;
336 }
337
338 static int save_files_dirs(const unsigned char *sha1,
339                 struct strbuf *base, const char *path,
340                 unsigned int mode, int stage, void *context)
341 {
342         struct path_hashmap_entry *entry;
343         int baselen = base->len;
344         struct merge_options *o = context;
345
346         strbuf_addstr(base, path);
347
348         FLEX_ALLOC_MEM(entry, path, base->buf, base->len);
349         hashmap_entry_init(entry, path_hash(entry->path));
350         hashmap_add(&o->current_file_dir_set, entry);
351
352         strbuf_setlen(base, baselen);
353         return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
354 }
355
356 static void get_files_dirs(struct merge_options *o, struct tree *tree)
357 {
358         struct pathspec match_all;
359         memset(&match_all, 0, sizeof(match_all));
360         read_tree_recursive(tree, "", 0, 0, &match_all, save_files_dirs, o);
361 }
362
363 /*
364  * Returns an index_entry instance which doesn't have to correspond to
365  * a real cache entry in Git's index.
366  */
367 static struct stage_data *insert_stage_data(const char *path,
368                 struct tree *o, struct tree *a, struct tree *b,
369                 struct string_list *entries)
370 {
371         struct string_list_item *item;
372         struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
373         get_tree_entry(o->object.oid.hash, path,
374                         e->stages[1].oid.hash, &e->stages[1].mode);
375         get_tree_entry(a->object.oid.hash, path,
376                         e->stages[2].oid.hash, &e->stages[2].mode);
377         get_tree_entry(b->object.oid.hash, path,
378                         e->stages[3].oid.hash, &e->stages[3].mode);
379         item = string_list_insert(entries, path);
380         item->util = e;
381         return e;
382 }
383
384 /*
385  * Create a dictionary mapping file names to stage_data objects. The
386  * dictionary contains one entry for every path with a non-zero stage entry.
387  */
388 static struct string_list *get_unmerged(void)
389 {
390         struct string_list *unmerged = xcalloc(1, sizeof(struct string_list));
391         int i;
392
393         unmerged->strdup_strings = 1;
394
395         for (i = 0; i < active_nr; i++) {
396                 struct string_list_item *item;
397                 struct stage_data *e;
398                 const struct cache_entry *ce = active_cache[i];
399                 if (!ce_stage(ce))
400                         continue;
401
402                 item = string_list_lookup(unmerged, ce->name);
403                 if (!item) {
404                         item = string_list_insert(unmerged, ce->name);
405                         item->util = xcalloc(1, sizeof(struct stage_data));
406                 }
407                 e = item->util;
408                 e->stages[ce_stage(ce)].mode = ce->ce_mode;
409                 oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid);
410         }
411
412         return unmerged;
413 }
414
415 static int string_list_df_name_compare(const char *one, const char *two)
416 {
417         int onelen = strlen(one);
418         int twolen = strlen(two);
419         /*
420          * Here we only care that entries for D/F conflicts are
421          * adjacent, in particular with the file of the D/F conflict
422          * appearing before files below the corresponding directory.
423          * The order of the rest of the list is irrelevant for us.
424          *
425          * To achieve this, we sort with df_name_compare and provide
426          * the mode S_IFDIR so that D/F conflicts will sort correctly.
427          * We use the mode S_IFDIR for everything else for simplicity,
428          * since in other cases any changes in their order due to
429          * sorting cause no problems for us.
430          */
431         int cmp = df_name_compare(one, onelen, S_IFDIR,
432                                   two, twolen, S_IFDIR);
433         /*
434          * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
435          * that 'foo' comes before 'foo/bar'.
436          */
437         if (cmp)
438                 return cmp;
439         return onelen - twolen;
440 }
441
442 static void record_df_conflict_files(struct merge_options *o,
443                                      struct string_list *entries)
444 {
445         /* If there is a D/F conflict and the file for such a conflict
446          * currently exist in the working tree, we want to allow it to be
447          * removed to make room for the corresponding directory if needed.
448          * The files underneath the directories of such D/F conflicts will
449          * be processed before the corresponding file involved in the D/F
450          * conflict.  If the D/F directory ends up being removed by the
451          * merge, then we won't have to touch the D/F file.  If the D/F
452          * directory needs to be written to the working copy, then the D/F
453          * file will simply be removed (in make_room_for_path()) to make
454          * room for the necessary paths.  Note that if both the directory
455          * and the file need to be present, then the D/F file will be
456          * reinstated with a new unique name at the time it is processed.
457          */
458         struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP;
459         const char *last_file = NULL;
460         int last_len = 0;
461         int i;
462
463         /*
464          * If we're merging merge-bases, we don't want to bother with
465          * any working directory changes.
466          */
467         if (o->call_depth)
468                 return;
469
470         /* Ensure D/F conflicts are adjacent in the entries list. */
471         for (i = 0; i < entries->nr; i++) {
472                 struct string_list_item *next = &entries->items[i];
473                 string_list_append(&df_sorted_entries, next->string)->util =
474                                    next->util;
475         }
476         df_sorted_entries.cmp = string_list_df_name_compare;
477         string_list_sort(&df_sorted_entries);
478
479         string_list_clear(&o->df_conflict_file_set, 1);
480         for (i = 0; i < df_sorted_entries.nr; i++) {
481                 const char *path = df_sorted_entries.items[i].string;
482                 int len = strlen(path);
483                 struct stage_data *e = df_sorted_entries.items[i].util;
484
485                 /*
486                  * Check if last_file & path correspond to a D/F conflict;
487                  * i.e. whether path is last_file+'/'+<something>.
488                  * If so, record that it's okay to remove last_file to make
489                  * room for path and friends if needed.
490                  */
491                 if (last_file &&
492                     len > last_len &&
493                     memcmp(path, last_file, last_len) == 0 &&
494                     path[last_len] == '/') {
495                         string_list_insert(&o->df_conflict_file_set, last_file);
496                 }
497
498                 /*
499                  * Determine whether path could exist as a file in the
500                  * working directory as a possible D/F conflict.  This
501                  * will only occur when it exists in stage 2 as a
502                  * file.
503                  */
504                 if (S_ISREG(e->stages[2].mode) || S_ISLNK(e->stages[2].mode)) {
505                         last_file = path;
506                         last_len = len;
507                 } else {
508                         last_file = NULL;
509                 }
510         }
511         string_list_clear(&df_sorted_entries, 0);
512 }
513
514 struct rename {
515         struct diff_filepair *pair;
516         /*
517          * Purpose of src_entry and dst_entry:
518          *
519          * If 'before' is renamed to 'after' then src_entry will contain
520          * the versions of 'before' from the merge_base, HEAD, and MERGE in
521          * stages 1, 2, and 3; dst_entry will contain the respective
522          * versions of 'after' in corresponding locations.  Thus, we have a
523          * total of six modes and oids, though some will be null.  (Stage 0
524          * is ignored; we're interested in handling conflicts.)
525          *
526          * Since we don't turn on break-rewrites by default, neither
527          * src_entry nor dst_entry can have all three of their stages have
528          * non-null oids, meaning at most four of the six will be non-null.
529          * Also, since this is a rename, both src_entry and dst_entry will
530          * have at least one non-null oid, meaning at least two will be
531          * non-null.  Of the six oids, a typical rename will have three be
532          * non-null.  Only two implies a rename/delete, and four implies a
533          * rename/add.
534          */
535         struct stage_data *src_entry;
536         struct stage_data *dst_entry;
537         unsigned processed:1;
538 };
539
540 static int update_stages(struct merge_options *opt, const char *path,
541                          const struct diff_filespec *o,
542                          const struct diff_filespec *a,
543                          const struct diff_filespec *b)
544 {
545
546         /*
547          * NOTE: It is usually a bad idea to call update_stages on a path
548          * before calling update_file on that same path, since it can
549          * sometimes lead to spurious "refusing to lose untracked file..."
550          * messages from update_file (via make_room_for path via
551          * would_lose_untracked).  Instead, reverse the order of the calls
552          * (executing update_file first and then update_stages).
553          */
554         int clear = 1;
555         int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK;
556         if (clear)
557                 if (remove_file_from_cache(path))
558                         return -1;
559         if (o)
560                 if (add_cacheinfo(opt, o->mode, &o->oid, path, 1, 0, options))
561                         return -1;
562         if (a)
563                 if (add_cacheinfo(opt, a->mode, &a->oid, path, 2, 0, options))
564                         return -1;
565         if (b)
566                 if (add_cacheinfo(opt, b->mode, &b->oid, path, 3, 0, options))
567                         return -1;
568         return 0;
569 }
570
571 static void update_entry(struct stage_data *entry,
572                          struct diff_filespec *o,
573                          struct diff_filespec *a,
574                          struct diff_filespec *b)
575 {
576         entry->processed = 0;
577         entry->stages[1].mode = o->mode;
578         entry->stages[2].mode = a->mode;
579         entry->stages[3].mode = b->mode;
580         oidcpy(&entry->stages[1].oid, &o->oid);
581         oidcpy(&entry->stages[2].oid, &a->oid);
582         oidcpy(&entry->stages[3].oid, &b->oid);
583 }
584
585 static int remove_file(struct merge_options *o, int clean,
586                        const char *path, int no_wd)
587 {
588         int update_cache = o->call_depth || clean;
589         int update_working_directory = !o->call_depth && !no_wd;
590
591         if (update_cache) {
592                 if (remove_file_from_cache(path))
593                         return -1;
594         }
595         if (update_working_directory) {
596                 if (ignore_case) {
597                         struct cache_entry *ce;
598                         ce = cache_file_exists(path, strlen(path), ignore_case);
599                         if (ce && ce_stage(ce) == 0 && strcmp(path, ce->name))
600                                 return 0;
601                 }
602                 if (remove_path(path))
603                         return -1;
604         }
605         return 0;
606 }
607
608 /* add a string to a strbuf, but converting "/" to "_" */
609 static void add_flattened_path(struct strbuf *out, const char *s)
610 {
611         size_t i = out->len;
612         strbuf_addstr(out, s);
613         for (; i < out->len; i++)
614                 if (out->buf[i] == '/')
615                         out->buf[i] = '_';
616 }
617
618 static char *unique_path(struct merge_options *o, const char *path, const char *branch)
619 {
620         struct path_hashmap_entry *entry;
621         struct strbuf newpath = STRBUF_INIT;
622         int suffix = 0;
623         size_t base_len;
624
625         strbuf_addf(&newpath, "%s~", path);
626         add_flattened_path(&newpath, branch);
627
628         base_len = newpath.len;
629         while (hashmap_get_from_hash(&o->current_file_dir_set,
630                                      path_hash(newpath.buf), newpath.buf) ||
631                (!o->call_depth && file_exists(newpath.buf))) {
632                 strbuf_setlen(&newpath, base_len);
633                 strbuf_addf(&newpath, "_%d", suffix++);
634         }
635
636         FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len);
637         hashmap_entry_init(entry, path_hash(entry->path));
638         hashmap_add(&o->current_file_dir_set, entry);
639         return strbuf_detach(&newpath, NULL);
640 }
641
642 /**
643  * Check whether a directory in the index is in the way of an incoming
644  * file.  Return 1 if so.  If check_working_copy is non-zero, also
645  * check the working directory.  If empty_ok is non-zero, also return
646  * 0 in the case where the working-tree dir exists but is empty.
647  */
648 static int dir_in_way(const char *path, int check_working_copy, int empty_ok)
649 {
650         int pos;
651         struct strbuf dirpath = STRBUF_INIT;
652         struct stat st;
653
654         strbuf_addstr(&dirpath, path);
655         strbuf_addch(&dirpath, '/');
656
657         pos = cache_name_pos(dirpath.buf, dirpath.len);
658
659         if (pos < 0)
660                 pos = -1 - pos;
661         if (pos < active_nr &&
662             !strncmp(dirpath.buf, active_cache[pos]->name, dirpath.len)) {
663                 strbuf_release(&dirpath);
664                 return 1;
665         }
666
667         strbuf_release(&dirpath);
668         return check_working_copy && !lstat(path, &st) && S_ISDIR(st.st_mode) &&
669                 !(empty_ok && is_empty_dir(path));
670 }
671
672 static int was_tracked(const char *path)
673 {
674         int pos = cache_name_pos(path, strlen(path));
675
676         if (0 <= pos)
677                 /* we have been tracking this path */
678                 return 1;
679
680         /*
681          * Look for an unmerged entry for the path,
682          * specifically stage #2, which would indicate
683          * that "our" side before the merge started
684          * had the path tracked (and resulted in a conflict).
685          */
686         for (pos = -1 - pos;
687              pos < active_nr && !strcmp(path, active_cache[pos]->name);
688              pos++)
689                 if (ce_stage(active_cache[pos]) == 2)
690                         return 1;
691         return 0;
692 }
693
694 static int would_lose_untracked(const char *path)
695 {
696         return !was_tracked(path) && file_exists(path);
697 }
698
699 static int make_room_for_path(struct merge_options *o, const char *path)
700 {
701         int status, i;
702         const char *msg = _("failed to create path '%s'%s");
703
704         /* Unlink any D/F conflict files that are in the way */
705         for (i = 0; i < o->df_conflict_file_set.nr; i++) {
706                 const char *df_path = o->df_conflict_file_set.items[i].string;
707                 size_t pathlen = strlen(path);
708                 size_t df_pathlen = strlen(df_path);
709                 if (df_pathlen < pathlen &&
710                     path[df_pathlen] == '/' &&
711                     strncmp(path, df_path, df_pathlen) == 0) {
712                         output(o, 3,
713                                _("Removing %s to make room for subdirectory\n"),
714                                df_path);
715                         unlink(df_path);
716                         unsorted_string_list_delete_item(&o->df_conflict_file_set,
717                                                          i, 0);
718                         break;
719                 }
720         }
721
722         /* Make sure leading directories are created */
723         status = safe_create_leading_directories_const(path);
724         if (status) {
725                 if (status == SCLD_EXISTS)
726                         /* something else exists */
727                         return err(o, msg, path, _(": perhaps a D/F conflict?"));
728                 return err(o, msg, path, "");
729         }
730
731         /*
732          * Do not unlink a file in the work tree if we are not
733          * tracking it.
734          */
735         if (would_lose_untracked(path))
736                 return err(o, _("refusing to lose untracked file at '%s'"),
737                              path);
738
739         /* Successful unlink is good.. */
740         if (!unlink(path))
741                 return 0;
742         /* .. and so is no existing file */
743         if (errno == ENOENT)
744                 return 0;
745         /* .. but not some other error (who really cares what?) */
746         return err(o, msg, path, _(": perhaps a D/F conflict?"));
747 }
748
749 static int update_file_flags(struct merge_options *o,
750                              const struct object_id *oid,
751                              unsigned mode,
752                              const char *path,
753                              int update_cache,
754                              int update_wd)
755 {
756         int ret = 0;
757
758         if (o->call_depth)
759                 update_wd = 0;
760
761         if (update_wd) {
762                 enum object_type type;
763                 void *buf;
764                 unsigned long size;
765
766                 if (S_ISGITLINK(mode)) {
767                         /*
768                          * We may later decide to recursively descend into
769                          * the submodule directory and update its index
770                          * and/or work tree, but we do not do that now.
771                          */
772                         update_wd = 0;
773                         goto update_index;
774                 }
775
776                 buf = read_sha1_file(oid->hash, &type, &size);
777                 if (!buf)
778                         return err(o, _("cannot read object %s '%s'"), oid_to_hex(oid), path);
779                 if (type != OBJ_BLOB) {
780                         ret = err(o, _("blob expected for %s '%s'"), oid_to_hex(oid), path);
781                         goto free_buf;
782                 }
783                 if (S_ISREG(mode)) {
784                         struct strbuf strbuf = STRBUF_INIT;
785                         if (convert_to_working_tree(path, buf, size, &strbuf)) {
786                                 free(buf);
787                                 size = strbuf.len;
788                                 buf = strbuf_detach(&strbuf, NULL);
789                         }
790                 }
791
792                 if (make_room_for_path(o, path) < 0) {
793                         update_wd = 0;
794                         goto free_buf;
795                 }
796                 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
797                         int fd;
798                         if (mode & 0100)
799                                 mode = 0777;
800                         else
801                                 mode = 0666;
802                         fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
803                         if (fd < 0) {
804                                 ret = err(o, _("failed to open '%s': %s"),
805                                           path, strerror(errno));
806                                 goto free_buf;
807                         }
808                         write_in_full(fd, buf, size);
809                         close(fd);
810                 } else if (S_ISLNK(mode)) {
811                         char *lnk = xmemdupz(buf, size);
812                         safe_create_leading_directories_const(path);
813                         unlink(path);
814                         if (symlink(lnk, path))
815                                 ret = err(o, _("failed to symlink '%s': %s"),
816                                         path, strerror(errno));
817                         free(lnk);
818                 } else
819                         ret = err(o,
820                                   _("do not know what to do with %06o %s '%s'"),
821                                   mode, oid_to_hex(oid), path);
822  free_buf:
823                 free(buf);
824         }
825  update_index:
826         if (!ret && update_cache)
827                 add_cacheinfo(o, mode, oid, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
828         return ret;
829 }
830
831 static int update_file(struct merge_options *o,
832                        int clean,
833                        const struct object_id *oid,
834                        unsigned mode,
835                        const char *path)
836 {
837         return update_file_flags(o, oid, mode, path, o->call_depth || clean, !o->call_depth);
838 }
839
840 /* Low level file merging, update and removal */
841
842 struct merge_file_info {
843         struct object_id oid;
844         unsigned mode;
845         unsigned clean:1,
846                  merge:1;
847 };
848
849 static int merge_3way(struct merge_options *o,
850                       mmbuffer_t *result_buf,
851                       const struct diff_filespec *one,
852                       const struct diff_filespec *a,
853                       const struct diff_filespec *b,
854                       const char *branch1,
855                       const char *branch2)
856 {
857         mmfile_t orig, src1, src2;
858         struct ll_merge_options ll_opts = {0};
859         char *base_name, *name1, *name2;
860         int merge_status;
861
862         ll_opts.renormalize = o->renormalize;
863         ll_opts.xdl_opts = o->xdl_opts;
864
865         if (o->call_depth) {
866                 ll_opts.virtual_ancestor = 1;
867                 ll_opts.variant = 0;
868         } else {
869                 switch (o->recursive_variant) {
870                 case MERGE_RECURSIVE_OURS:
871                         ll_opts.variant = XDL_MERGE_FAVOR_OURS;
872                         break;
873                 case MERGE_RECURSIVE_THEIRS:
874                         ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
875                         break;
876                 default:
877                         ll_opts.variant = 0;
878                         break;
879                 }
880         }
881
882         if (strcmp(a->path, b->path) ||
883             (o->ancestor != NULL && strcmp(a->path, one->path) != 0)) {
884                 base_name = o->ancestor == NULL ? NULL :
885                         mkpathdup("%s:%s", o->ancestor, one->path);
886                 name1 = mkpathdup("%s:%s", branch1, a->path);
887                 name2 = mkpathdup("%s:%s", branch2, b->path);
888         } else {
889                 base_name = o->ancestor == NULL ? NULL :
890                         mkpathdup("%s", o->ancestor);
891                 name1 = mkpathdup("%s", branch1);
892                 name2 = mkpathdup("%s", branch2);
893         }
894
895         read_mmblob(&orig, &one->oid);
896         read_mmblob(&src1, &a->oid);
897         read_mmblob(&src2, &b->oid);
898
899         merge_status = ll_merge(result_buf, a->path, &orig, base_name,
900                                 &src1, name1, &src2, name2, &ll_opts);
901
902         free(base_name);
903         free(name1);
904         free(name2);
905         free(orig.ptr);
906         free(src1.ptr);
907         free(src2.ptr);
908         return merge_status;
909 }
910
911 static int merge_file_1(struct merge_options *o,
912                                            const struct diff_filespec *one,
913                                            const struct diff_filespec *a,
914                                            const struct diff_filespec *b,
915                                            const char *branch1,
916                                            const char *branch2,
917                                            struct merge_file_info *result)
918 {
919         result->merge = 0;
920         result->clean = 1;
921
922         if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
923                 result->clean = 0;
924                 if (S_ISREG(a->mode)) {
925                         result->mode = a->mode;
926                         oidcpy(&result->oid, &a->oid);
927                 } else {
928                         result->mode = b->mode;
929                         oidcpy(&result->oid, &b->oid);
930                 }
931         } else {
932                 if (!oid_eq(&a->oid, &one->oid) && !oid_eq(&b->oid, &one->oid))
933                         result->merge = 1;
934
935                 /*
936                  * Merge modes
937                  */
938                 if (a->mode == b->mode || a->mode == one->mode)
939                         result->mode = b->mode;
940                 else {
941                         result->mode = a->mode;
942                         if (b->mode != one->mode) {
943                                 result->clean = 0;
944                                 result->merge = 1;
945                         }
946                 }
947
948                 if (oid_eq(&a->oid, &b->oid) || oid_eq(&a->oid, &one->oid))
949                         oidcpy(&result->oid, &b->oid);
950                 else if (oid_eq(&b->oid, &one->oid))
951                         oidcpy(&result->oid, &a->oid);
952                 else if (S_ISREG(a->mode)) {
953                         mmbuffer_t result_buf;
954                         int ret = 0, merge_status;
955
956                         merge_status = merge_3way(o, &result_buf, one, a, b,
957                                                   branch1, branch2);
958
959                         if ((merge_status < 0) || !result_buf.ptr)
960                                 ret = err(o, _("Failed to execute internal merge"));
961
962                         if (!ret && write_sha1_file(result_buf.ptr, result_buf.size,
963                                                     blob_type, result->oid.hash))
964                                 ret = err(o, _("Unable to add %s to database"),
965                                           a->path);
966
967                         free(result_buf.ptr);
968                         if (ret)
969                                 return ret;
970                         result->clean = (merge_status == 0);
971                 } else if (S_ISGITLINK(a->mode)) {
972                         result->clean = merge_submodule(&result->oid,
973                                                        one->path,
974                                                        &one->oid,
975                                                        &a->oid,
976                                                        &b->oid,
977                                                        !o->call_depth);
978                 } else if (S_ISLNK(a->mode)) {
979                         oidcpy(&result->oid, &a->oid);
980
981                         if (!oid_eq(&a->oid, &b->oid))
982                                 result->clean = 0;
983                 } else
984                         die("BUG: unsupported object type in the tree");
985         }
986
987         return 0;
988 }
989
990 static int merge_file_special_markers(struct merge_options *o,
991                            const struct diff_filespec *one,
992                            const struct diff_filespec *a,
993                            const struct diff_filespec *b,
994                            const char *branch1,
995                            const char *filename1,
996                            const char *branch2,
997                            const char *filename2,
998                            struct merge_file_info *mfi)
999 {
1000         char *side1 = NULL;
1001         char *side2 = NULL;
1002         int ret;
1003
1004         if (filename1)
1005                 side1 = xstrfmt("%s:%s", branch1, filename1);
1006         if (filename2)
1007                 side2 = xstrfmt("%s:%s", branch2, filename2);
1008
1009         ret = merge_file_1(o, one, a, b,
1010                            side1 ? side1 : branch1,
1011                            side2 ? side2 : branch2, mfi);
1012         free(side1);
1013         free(side2);
1014         return ret;
1015 }
1016
1017 static int merge_file_one(struct merge_options *o,
1018                                          const char *path,
1019                                          const struct object_id *o_oid, int o_mode,
1020                                          const struct object_id *a_oid, int a_mode,
1021                                          const struct object_id *b_oid, int b_mode,
1022                                          const char *branch1,
1023                                          const char *branch2,
1024                                          struct merge_file_info *mfi)
1025 {
1026         struct diff_filespec one, a, b;
1027
1028         one.path = a.path = b.path = (char *)path;
1029         oidcpy(&one.oid, o_oid);
1030         one.mode = o_mode;
1031         oidcpy(&a.oid, a_oid);
1032         a.mode = a_mode;
1033         oidcpy(&b.oid, b_oid);
1034         b.mode = b_mode;
1035         return merge_file_1(o, &one, &a, &b, branch1, branch2, mfi);
1036 }
1037
1038 static int handle_change_delete(struct merge_options *o,
1039                                  const char *path, const char *old_path,
1040                                  const struct object_id *o_oid, int o_mode,
1041                                  const struct object_id *changed_oid,
1042                                  int changed_mode,
1043                                  const char *change_branch,
1044                                  const char *delete_branch,
1045                                  const char *change, const char *change_past)
1046 {
1047         char *alt_path = NULL;
1048         const char *update_path = path;
1049         int ret = 0;
1050
1051         if (dir_in_way(path, !o->call_depth, 0)) {
1052                 update_path = alt_path = unique_path(o, path, change_branch);
1053         }
1054
1055         if (o->call_depth) {
1056                 /*
1057                  * We cannot arbitrarily accept either a_sha or b_sha as
1058                  * correct; since there is no true "middle point" between
1059                  * them, simply reuse the base version for virtual merge base.
1060                  */
1061                 ret = remove_file_from_cache(path);
1062                 if (!ret)
1063                         ret = update_file(o, 0, o_oid, o_mode, update_path);
1064         } else {
1065                 if (!alt_path) {
1066                         if (!old_path) {
1067                                 output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1068                                        "and %s in %s. Version %s of %s left in tree."),
1069                                        change, path, delete_branch, change_past,
1070                                        change_branch, change_branch, path);
1071                         } else {
1072                                 output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1073                                        "and %s to %s in %s. Version %s of %s left in tree."),
1074                                        change, old_path, delete_branch, change_past, path,
1075                                        change_branch, change_branch, path);
1076                         }
1077                 } else {
1078                         if (!old_path) {
1079                                 output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1080                                        "and %s in %s. Version %s of %s left in tree at %s."),
1081                                        change, path, delete_branch, change_past,
1082                                        change_branch, change_branch, path, alt_path);
1083                         } else {
1084                                 output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1085                                        "and %s to %s in %s. Version %s of %s left in tree at %s."),
1086                                        change, old_path, delete_branch, change_past, path,
1087                                        change_branch, change_branch, path, alt_path);
1088                         }
1089                 }
1090                 /*
1091                  * No need to call update_file() on path when change_branch ==
1092                  * o->branch1 && !alt_path, since that would needlessly touch
1093                  * path.  We could call update_file_flags() with update_cache=0
1094                  * and update_wd=0, but that's a no-op.
1095                  */
1096                 if (change_branch != o->branch1 || alt_path)
1097                         ret = update_file(o, 0, changed_oid, changed_mode, update_path);
1098         }
1099         free(alt_path);
1100
1101         return ret;
1102 }
1103
1104 static int conflict_rename_delete(struct merge_options *o,
1105                                    struct diff_filepair *pair,
1106                                    const char *rename_branch,
1107                                    const char *delete_branch)
1108 {
1109         const struct diff_filespec *orig = pair->one;
1110         const struct diff_filespec *dest = pair->two;
1111
1112         if (handle_change_delete(o,
1113                                  o->call_depth ? orig->path : dest->path,
1114                                  o->call_depth ? NULL : orig->path,
1115                                  &orig->oid, orig->mode,
1116                                  &dest->oid, dest->mode,
1117                                  rename_branch, delete_branch,
1118                                  _("rename"), _("renamed")))
1119                 return -1;
1120
1121         if (o->call_depth)
1122                 return remove_file_from_cache(dest->path);
1123         else
1124                 return update_stages(o, dest->path, NULL,
1125                                      rename_branch == o->branch1 ? dest : NULL,
1126                                      rename_branch == o->branch1 ? NULL : dest);
1127 }
1128
1129 static struct diff_filespec *filespec_from_entry(struct diff_filespec *target,
1130                                                  struct stage_data *entry,
1131                                                  int stage)
1132 {
1133         struct object_id *oid = &entry->stages[stage].oid;
1134         unsigned mode = entry->stages[stage].mode;
1135         if (mode == 0 || is_null_oid(oid))
1136                 return NULL;
1137         oidcpy(&target->oid, oid);
1138         target->mode = mode;
1139         return target;
1140 }
1141
1142 static int handle_file(struct merge_options *o,
1143                         struct diff_filespec *rename,
1144                         int stage,
1145                         struct rename_conflict_info *ci)
1146 {
1147         char *dst_name = rename->path;
1148         struct stage_data *dst_entry;
1149         const char *cur_branch, *other_branch;
1150         struct diff_filespec other;
1151         struct diff_filespec *add;
1152         int ret;
1153
1154         if (stage == 2) {
1155                 dst_entry = ci->dst_entry1;
1156                 cur_branch = ci->branch1;
1157                 other_branch = ci->branch2;
1158         } else {
1159                 dst_entry = ci->dst_entry2;
1160                 cur_branch = ci->branch2;
1161                 other_branch = ci->branch1;
1162         }
1163
1164         add = filespec_from_entry(&other, dst_entry, stage ^ 1);
1165         if (add) {
1166                 char *add_name = unique_path(o, rename->path, other_branch);
1167                 if (update_file(o, 0, &add->oid, add->mode, add_name))
1168                         return -1;
1169
1170                 remove_file(o, 0, rename->path, 0);
1171                 dst_name = unique_path(o, rename->path, cur_branch);
1172         } else {
1173                 if (dir_in_way(rename->path, !o->call_depth, 0)) {
1174                         dst_name = unique_path(o, rename->path, cur_branch);
1175                         output(o, 1, _("%s is a directory in %s adding as %s instead"),
1176                                rename->path, other_branch, dst_name);
1177                 }
1178         }
1179         if ((ret = update_file(o, 0, &rename->oid, rename->mode, dst_name)))
1180                 ; /* fall through, do allow dst_name to be released */
1181         else if (stage == 2)
1182                 ret = update_stages(o, rename->path, NULL, rename, add);
1183         else
1184                 ret = update_stages(o, rename->path, NULL, add, rename);
1185
1186         if (dst_name != rename->path)
1187                 free(dst_name);
1188
1189         return ret;
1190 }
1191
1192 static int conflict_rename_rename_1to2(struct merge_options *o,
1193                                         struct rename_conflict_info *ci)
1194 {
1195         /* One file was renamed in both branches, but to different names. */
1196         struct diff_filespec *one = ci->pair1->one;
1197         struct diff_filespec *a = ci->pair1->two;
1198         struct diff_filespec *b = ci->pair2->two;
1199
1200         output(o, 1, _("CONFLICT (rename/rename): "
1201                "Rename \"%s\"->\"%s\" in branch \"%s\" "
1202                "rename \"%s\"->\"%s\" in \"%s\"%s"),
1203                one->path, a->path, ci->branch1,
1204                one->path, b->path, ci->branch2,
1205                o->call_depth ? _(" (left unresolved)") : "");
1206         if (o->call_depth) {
1207                 struct merge_file_info mfi;
1208                 struct diff_filespec other;
1209                 struct diff_filespec *add;
1210                 if (merge_file_one(o, one->path,
1211                                  &one->oid, one->mode,
1212                                  &a->oid, a->mode,
1213                                  &b->oid, b->mode,
1214                                  ci->branch1, ci->branch2, &mfi))
1215                         return -1;
1216
1217                 /*
1218                  * FIXME: For rename/add-source conflicts (if we could detect
1219                  * such), this is wrong.  We should instead find a unique
1220                  * pathname and then either rename the add-source file to that
1221                  * unique path, or use that unique path instead of src here.
1222                  */
1223                 if (update_file(o, 0, &mfi.oid, mfi.mode, one->path))
1224                         return -1;
1225
1226                 /*
1227                  * Above, we put the merged content at the merge-base's
1228                  * path.  Now we usually need to delete both a->path and
1229                  * b->path.  However, the rename on each side of the merge
1230                  * could also be involved in a rename/add conflict.  In
1231                  * such cases, we should keep the added file around,
1232                  * resolving the conflict at that path in its favor.
1233                  */
1234                 add = filespec_from_entry(&other, ci->dst_entry1, 2 ^ 1);
1235                 if (add) {
1236                         if (update_file(o, 0, &add->oid, add->mode, a->path))
1237                                 return -1;
1238                 }
1239                 else
1240                         remove_file_from_cache(a->path);
1241                 add = filespec_from_entry(&other, ci->dst_entry2, 3 ^ 1);
1242                 if (add) {
1243                         if (update_file(o, 0, &add->oid, add->mode, b->path))
1244                                 return -1;
1245                 }
1246                 else
1247                         remove_file_from_cache(b->path);
1248         } else if (handle_file(o, a, 2, ci) || handle_file(o, b, 3, ci))
1249                 return -1;
1250
1251         return 0;
1252 }
1253
1254 static int conflict_rename_rename_2to1(struct merge_options *o,
1255                                         struct rename_conflict_info *ci)
1256 {
1257         /* Two files, a & b, were renamed to the same thing, c. */
1258         struct diff_filespec *a = ci->pair1->one;
1259         struct diff_filespec *b = ci->pair2->one;
1260         struct diff_filespec *c1 = ci->pair1->two;
1261         struct diff_filespec *c2 = ci->pair2->two;
1262         char *path = c1->path; /* == c2->path */
1263         struct merge_file_info mfi_c1;
1264         struct merge_file_info mfi_c2;
1265         int ret;
1266
1267         output(o, 1, _("CONFLICT (rename/rename): "
1268                "Rename %s->%s in %s. "
1269                "Rename %s->%s in %s"),
1270                a->path, c1->path, ci->branch1,
1271                b->path, c2->path, ci->branch2);
1272
1273         remove_file(o, 1, a->path, o->call_depth || would_lose_untracked(a->path));
1274         remove_file(o, 1, b->path, o->call_depth || would_lose_untracked(b->path));
1275
1276         if (merge_file_special_markers(o, a, c1, &ci->ren1_other,
1277                                        o->branch1, c1->path,
1278                                        o->branch2, ci->ren1_other.path, &mfi_c1) ||
1279             merge_file_special_markers(o, b, &ci->ren2_other, c2,
1280                                        o->branch1, ci->ren2_other.path,
1281                                        o->branch2, c2->path, &mfi_c2))
1282                 return -1;
1283
1284         if (o->call_depth) {
1285                 /*
1286                  * If mfi_c1.clean && mfi_c2.clean, then it might make
1287                  * sense to do a two-way merge of those results.  But, I
1288                  * think in all cases, it makes sense to have the virtual
1289                  * merge base just undo the renames; they can be detected
1290                  * again later for the non-recursive merge.
1291                  */
1292                 remove_file(o, 0, path, 0);
1293                 ret = update_file(o, 0, &mfi_c1.oid, mfi_c1.mode, a->path);
1294                 if (!ret)
1295                         ret = update_file(o, 0, &mfi_c2.oid, mfi_c2.mode,
1296                                           b->path);
1297         } else {
1298                 char *new_path1 = unique_path(o, path, ci->branch1);
1299                 char *new_path2 = unique_path(o, path, ci->branch2);
1300                 output(o, 1, _("Renaming %s to %s and %s to %s instead"),
1301                        a->path, new_path1, b->path, new_path2);
1302                 remove_file(o, 0, path, 0);
1303                 ret = update_file(o, 0, &mfi_c1.oid, mfi_c1.mode, new_path1);
1304                 if (!ret)
1305                         ret = update_file(o, 0, &mfi_c2.oid, mfi_c2.mode,
1306                                           new_path2);
1307                 free(new_path2);
1308                 free(new_path1);
1309         }
1310
1311         return ret;
1312 }
1313
1314 /*
1315  * Get information of all renames which occurred between 'o_tree' and
1316  * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
1317  * 'b_tree') to be able to associate the correct cache entries with
1318  * the rename information. 'tree' is always equal to either a_tree or b_tree.
1319  */
1320 static struct string_list *get_renames(struct merge_options *o,
1321                                        struct tree *tree,
1322                                        struct tree *o_tree,
1323                                        struct tree *a_tree,
1324                                        struct tree *b_tree,
1325                                        struct string_list *entries)
1326 {
1327         int i;
1328         struct string_list *renames;
1329         struct diff_options opts;
1330
1331         renames = xcalloc(1, sizeof(struct string_list));
1332
1333         diff_setup(&opts);
1334         opts.flags.recursive = 1;
1335         opts.flags.rename_empty = 0;
1336         opts.detect_rename = DIFF_DETECT_RENAME;
1337         opts.rename_limit = o->merge_rename_limit >= 0 ? o->merge_rename_limit :
1338                             o->diff_rename_limit >= 0 ? o->diff_rename_limit :
1339                             1000;
1340         opts.rename_score = o->rename_score;
1341         opts.show_rename_progress = o->show_rename_progress;
1342         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1343         diff_setup_done(&opts);
1344         diff_tree_oid(&o_tree->object.oid, &tree->object.oid, "", &opts);
1345         diffcore_std(&opts);
1346         if (opts.needed_rename_limit > o->needed_rename_limit)
1347                 o->needed_rename_limit = opts.needed_rename_limit;
1348         for (i = 0; i < diff_queued_diff.nr; ++i) {
1349                 struct string_list_item *item;
1350                 struct rename *re;
1351                 struct diff_filepair *pair = diff_queued_diff.queue[i];
1352
1353                 if (pair->status != 'R') {
1354                         diff_free_filepair(pair);
1355                         continue;
1356                 }
1357                 re = xmalloc(sizeof(*re));
1358                 re->processed = 0;
1359                 re->pair = pair;
1360                 item = string_list_lookup(entries, re->pair->one->path);
1361                 if (!item)
1362                         re->src_entry = insert_stage_data(re->pair->one->path,
1363                                         o_tree, a_tree, b_tree, entries);
1364                 else
1365                         re->src_entry = item->util;
1366
1367                 item = string_list_lookup(entries, re->pair->two->path);
1368                 if (!item)
1369                         re->dst_entry = insert_stage_data(re->pair->two->path,
1370                                         o_tree, a_tree, b_tree, entries);
1371                 else
1372                         re->dst_entry = item->util;
1373                 item = string_list_insert(renames, pair->one->path);
1374                 item->util = re;
1375         }
1376         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1377         diff_queued_diff.nr = 0;
1378         diff_flush(&opts);
1379         return renames;
1380 }
1381
1382 static int process_renames(struct merge_options *o,
1383                            struct string_list *a_renames,
1384                            struct string_list *b_renames)
1385 {
1386         int clean_merge = 1, i, j;
1387         struct string_list a_by_dst = STRING_LIST_INIT_NODUP;
1388         struct string_list b_by_dst = STRING_LIST_INIT_NODUP;
1389         const struct rename *sre;
1390
1391         for (i = 0; i < a_renames->nr; i++) {
1392                 sre = a_renames->items[i].util;
1393                 string_list_insert(&a_by_dst, sre->pair->two->path)->util
1394                         = (void *)sre;
1395         }
1396         for (i = 0; i < b_renames->nr; i++) {
1397                 sre = b_renames->items[i].util;
1398                 string_list_insert(&b_by_dst, sre->pair->two->path)->util
1399                         = (void *)sre;
1400         }
1401
1402         for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
1403                 struct string_list *renames1, *renames2Dst;
1404                 struct rename *ren1 = NULL, *ren2 = NULL;
1405                 const char *branch1, *branch2;
1406                 const char *ren1_src, *ren1_dst;
1407                 struct string_list_item *lookup;
1408
1409                 if (i >= a_renames->nr) {
1410                         ren2 = b_renames->items[j++].util;
1411                 } else if (j >= b_renames->nr) {
1412                         ren1 = a_renames->items[i++].util;
1413                 } else {
1414                         int compare = strcmp(a_renames->items[i].string,
1415                                              b_renames->items[j].string);
1416                         if (compare <= 0)
1417                                 ren1 = a_renames->items[i++].util;
1418                         if (compare >= 0)
1419                                 ren2 = b_renames->items[j++].util;
1420                 }
1421
1422                 /* TODO: refactor, so that 1/2 are not needed */
1423                 if (ren1) {
1424                         renames1 = a_renames;
1425                         renames2Dst = &b_by_dst;
1426                         branch1 = o->branch1;
1427                         branch2 = o->branch2;
1428                 } else {
1429                         renames1 = b_renames;
1430                         renames2Dst = &a_by_dst;
1431                         branch1 = o->branch2;
1432                         branch2 = o->branch1;
1433                         SWAP(ren2, ren1);
1434                 }
1435
1436                 if (ren1->processed)
1437                         continue;
1438                 ren1->processed = 1;
1439                 ren1->dst_entry->processed = 1;
1440                 /* BUG: We should only mark src_entry as processed if we
1441                  * are not dealing with a rename + add-source case.
1442                  */
1443                 ren1->src_entry->processed = 1;
1444
1445                 ren1_src = ren1->pair->one->path;
1446                 ren1_dst = ren1->pair->two->path;
1447
1448                 if (ren2) {
1449                         /* One file renamed on both sides */
1450                         const char *ren2_src = ren2->pair->one->path;
1451                         const char *ren2_dst = ren2->pair->two->path;
1452                         enum rename_type rename_type;
1453                         if (strcmp(ren1_src, ren2_src) != 0)
1454                                 die("BUG: ren1_src != ren2_src");
1455                         ren2->dst_entry->processed = 1;
1456                         ren2->processed = 1;
1457                         if (strcmp(ren1_dst, ren2_dst) != 0) {
1458                                 rename_type = RENAME_ONE_FILE_TO_TWO;
1459                                 clean_merge = 0;
1460                         } else {
1461                                 rename_type = RENAME_ONE_FILE_TO_ONE;
1462                                 /* BUG: We should only remove ren1_src in
1463                                  * the base stage (think of rename +
1464                                  * add-source cases).
1465                                  */
1466                                 remove_file(o, 1, ren1_src, 1);
1467                                 update_entry(ren1->dst_entry,
1468                                              ren1->pair->one,
1469                                              ren1->pair->two,
1470                                              ren2->pair->two);
1471                         }
1472                         setup_rename_conflict_info(rename_type,
1473                                                    ren1->pair,
1474                                                    ren2->pair,
1475                                                    branch1,
1476                                                    branch2,
1477                                                    ren1->dst_entry,
1478                                                    ren2->dst_entry,
1479                                                    o,
1480                                                    NULL,
1481                                                    NULL);
1482                 } else if ((lookup = string_list_lookup(renames2Dst, ren1_dst))) {
1483                         /* Two different files renamed to the same thing */
1484                         char *ren2_dst;
1485                         ren2 = lookup->util;
1486                         ren2_dst = ren2->pair->two->path;
1487                         if (strcmp(ren1_dst, ren2_dst) != 0)
1488                                 die("BUG: ren1_dst != ren2_dst");
1489
1490                         clean_merge = 0;
1491                         ren2->processed = 1;
1492                         /*
1493                          * BUG: We should only mark src_entry as processed
1494                          * if we are not dealing with a rename + add-source
1495                          * case.
1496                          */
1497                         ren2->src_entry->processed = 1;
1498
1499                         setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,
1500                                                    ren1->pair,
1501                                                    ren2->pair,
1502                                                    branch1,
1503                                                    branch2,
1504                                                    ren1->dst_entry,
1505                                                    ren2->dst_entry,
1506                                                    o,
1507                                                    ren1->src_entry,
1508                                                    ren2->src_entry);
1509
1510                 } else {
1511                         /* Renamed in 1, maybe changed in 2 */
1512                         /* we only use sha1 and mode of these */
1513                         struct diff_filespec src_other, dst_other;
1514                         int try_merge;
1515
1516                         /*
1517                          * unpack_trees loads entries from common-commit
1518                          * into stage 1, from head-commit into stage 2, and
1519                          * from merge-commit into stage 3.  We keep track
1520                          * of which side corresponds to the rename.
1521                          */
1522                         int renamed_stage = a_renames == renames1 ? 2 : 3;
1523                         int other_stage =   a_renames == renames1 ? 3 : 2;
1524
1525                         /* BUG: We should only remove ren1_src in the base
1526                          * stage and in other_stage (think of rename +
1527                          * add-source case).
1528                          */
1529                         remove_file(o, 1, ren1_src,
1530                                     renamed_stage == 2 || !was_tracked(ren1_src));
1531
1532                         oidcpy(&src_other.oid,
1533                                &ren1->src_entry->stages[other_stage].oid);
1534                         src_other.mode = ren1->src_entry->stages[other_stage].mode;
1535                         oidcpy(&dst_other.oid,
1536                                &ren1->dst_entry->stages[other_stage].oid);
1537                         dst_other.mode = ren1->dst_entry->stages[other_stage].mode;
1538                         try_merge = 0;
1539
1540                         if (oid_eq(&src_other.oid, &null_oid)) {
1541                                 setup_rename_conflict_info(RENAME_DELETE,
1542                                                            ren1->pair,
1543                                                            NULL,
1544                                                            branch1,
1545                                                            branch2,
1546                                                            ren1->dst_entry,
1547                                                            NULL,
1548                                                            o,
1549                                                            NULL,
1550                                                            NULL);
1551                         } else if ((dst_other.mode == ren1->pair->two->mode) &&
1552                                    oid_eq(&dst_other.oid, &ren1->pair->two->oid)) {
1553                                 /*
1554                                  * Added file on the other side identical to
1555                                  * the file being renamed: clean merge.
1556                                  * Also, there is no need to overwrite the
1557                                  * file already in the working copy, so call
1558                                  * update_file_flags() instead of
1559                                  * update_file().
1560                                  */
1561                                 if (update_file_flags(o,
1562                                                       &ren1->pair->two->oid,
1563                                                       ren1->pair->two->mode,
1564                                                       ren1_dst,
1565                                                       1, /* update_cache */
1566                                                       0  /* update_wd    */))
1567                                         clean_merge = -1;
1568                         } else if (!oid_eq(&dst_other.oid, &null_oid)) {
1569                                 clean_merge = 0;
1570                                 try_merge = 1;
1571                                 output(o, 1, _("CONFLICT (rename/add): Rename %s->%s in %s. "
1572                                        "%s added in %s"),
1573                                        ren1_src, ren1_dst, branch1,
1574                                        ren1_dst, branch2);
1575                                 if (o->call_depth) {
1576                                         struct merge_file_info mfi;
1577                                         if (merge_file_one(o, ren1_dst, &null_oid, 0,
1578                                                            &ren1->pair->two->oid,
1579                                                            ren1->pair->two->mode,
1580                                                            &dst_other.oid,
1581                                                            dst_other.mode,
1582                                                            branch1, branch2, &mfi)) {
1583                                                 clean_merge = -1;
1584                                                 goto cleanup_and_return;
1585                                         }
1586                                         output(o, 1, _("Adding merged %s"), ren1_dst);
1587                                         if (update_file(o, 0, &mfi.oid,
1588                                                         mfi.mode, ren1_dst))
1589                                                 clean_merge = -1;
1590                                         try_merge = 0;
1591                                 } else {
1592                                         char *new_path = unique_path(o, ren1_dst, branch2);
1593                                         output(o, 1, _("Adding as %s instead"), new_path);
1594                                         if (update_file(o, 0, &dst_other.oid,
1595                                                         dst_other.mode, new_path))
1596                                                 clean_merge = -1;
1597                                         free(new_path);
1598                                 }
1599                         } else
1600                                 try_merge = 1;
1601
1602                         if (clean_merge < 0)
1603                                 goto cleanup_and_return;
1604                         if (try_merge) {
1605                                 struct diff_filespec *one, *a, *b;
1606                                 src_other.path = (char *)ren1_src;
1607
1608                                 one = ren1->pair->one;
1609                                 if (a_renames == renames1) {
1610                                         a = ren1->pair->two;
1611                                         b = &src_other;
1612                                 } else {
1613                                         b = ren1->pair->two;
1614                                         a = &src_other;
1615                                 }
1616                                 update_entry(ren1->dst_entry, one, a, b);
1617                                 setup_rename_conflict_info(RENAME_NORMAL,
1618                                                            ren1->pair,
1619                                                            NULL,
1620                                                            branch1,
1621                                                            NULL,
1622                                                            ren1->dst_entry,
1623                                                            NULL,
1624                                                            o,
1625                                                            NULL,
1626                                                            NULL);
1627                         }
1628                 }
1629         }
1630 cleanup_and_return:
1631         string_list_clear(&a_by_dst, 0);
1632         string_list_clear(&b_by_dst, 0);
1633
1634         return clean_merge;
1635 }
1636
1637 struct rename_info {
1638         struct string_list *head_renames;
1639         struct string_list *merge_renames;
1640 };
1641
1642 static int handle_renames(struct merge_options *o,
1643                           struct tree *common,
1644                           struct tree *head,
1645                           struct tree *merge,
1646                           struct string_list *entries,
1647                           struct rename_info *ri)
1648 {
1649         ri->head_renames = NULL;
1650         ri->merge_renames = NULL;
1651
1652         if (!o->detect_rename)
1653                 return 1;
1654
1655         ri->head_renames  = get_renames(o, head, common, head, merge, entries);
1656         ri->merge_renames = get_renames(o, merge, common, head, merge, entries);
1657         return process_renames(o, ri->head_renames, ri->merge_renames);
1658 }
1659
1660 static void cleanup_rename(struct string_list *rename)
1661 {
1662         const struct rename *re;
1663         int i;
1664
1665         if (rename == NULL)
1666                 return;
1667
1668         for (i = 0; i < rename->nr; i++) {
1669                 re = rename->items[i].util;
1670                 diff_free_filepair(re->pair);
1671         }
1672         string_list_clear(rename, 1);
1673         free(rename);
1674 }
1675
1676 static void cleanup_renames(struct rename_info *re_info)
1677 {
1678         cleanup_rename(re_info->head_renames);
1679         cleanup_rename(re_info->merge_renames);
1680 }
1681
1682 static struct object_id *stage_oid(const struct object_id *oid, unsigned mode)
1683 {
1684         return (is_null_oid(oid) || mode == 0) ? NULL: (struct object_id *)oid;
1685 }
1686
1687 static int read_oid_strbuf(struct merge_options *o,
1688         const struct object_id *oid, struct strbuf *dst)
1689 {
1690         void *buf;
1691         enum object_type type;
1692         unsigned long size;
1693         buf = read_sha1_file(oid->hash, &type, &size);
1694         if (!buf)
1695                 return err(o, _("cannot read object %s"), oid_to_hex(oid));
1696         if (type != OBJ_BLOB) {
1697                 free(buf);
1698                 return err(o, _("object %s is not a blob"), oid_to_hex(oid));
1699         }
1700         strbuf_attach(dst, buf, size, size + 1);
1701         return 0;
1702 }
1703
1704 static int blob_unchanged(struct merge_options *opt,
1705                           const struct object_id *o_oid,
1706                           unsigned o_mode,
1707                           const struct object_id *a_oid,
1708                           unsigned a_mode,
1709                           int renormalize, const char *path)
1710 {
1711         struct strbuf o = STRBUF_INIT;
1712         struct strbuf a = STRBUF_INIT;
1713         int ret = 0; /* assume changed for safety */
1714
1715         if (a_mode != o_mode)
1716                 return 0;
1717         if (oid_eq(o_oid, a_oid))
1718                 return 1;
1719         if (!renormalize)
1720                 return 0;
1721
1722         assert(o_oid && a_oid);
1723         if (read_oid_strbuf(opt, o_oid, &o) || read_oid_strbuf(opt, a_oid, &a))
1724                 goto error_return;
1725         /*
1726          * Note: binary | is used so that both renormalizations are
1727          * performed.  Comparison can be skipped if both files are
1728          * unchanged since their sha1s have already been compared.
1729          */
1730         if (renormalize_buffer(&the_index, path, o.buf, o.len, &o) |
1731             renormalize_buffer(&the_index, path, a.buf, a.len, &a))
1732                 ret = (o.len == a.len && !memcmp(o.buf, a.buf, o.len));
1733
1734 error_return:
1735         strbuf_release(&o);
1736         strbuf_release(&a);
1737         return ret;
1738 }
1739
1740 static int handle_modify_delete(struct merge_options *o,
1741                                  const char *path,
1742                                  struct object_id *o_oid, int o_mode,
1743                                  struct object_id *a_oid, int a_mode,
1744                                  struct object_id *b_oid, int b_mode)
1745 {
1746         const char *modify_branch, *delete_branch;
1747         struct object_id *changed_oid;
1748         int changed_mode;
1749
1750         if (a_oid) {
1751                 modify_branch = o->branch1;
1752                 delete_branch = o->branch2;
1753                 changed_oid = a_oid;
1754                 changed_mode = a_mode;
1755         } else {
1756                 modify_branch = o->branch2;
1757                 delete_branch = o->branch1;
1758                 changed_oid = b_oid;
1759                 changed_mode = b_mode;
1760         }
1761
1762         return handle_change_delete(o,
1763                                     path, NULL,
1764                                     o_oid, o_mode,
1765                                     changed_oid, changed_mode,
1766                                     modify_branch, delete_branch,
1767                                     _("modify"), _("modified"));
1768 }
1769
1770 static int merge_content(struct merge_options *o,
1771                          const char *path,
1772                          struct object_id *o_oid, int o_mode,
1773                          struct object_id *a_oid, int a_mode,
1774                          struct object_id *b_oid, int b_mode,
1775                          struct rename_conflict_info *rename_conflict_info)
1776 {
1777         const char *reason = _("content");
1778         const char *path1 = NULL, *path2 = NULL;
1779         struct merge_file_info mfi;
1780         struct diff_filespec one, a, b;
1781         unsigned df_conflict_remains = 0;
1782
1783         if (!o_oid) {
1784                 reason = _("add/add");
1785                 o_oid = (struct object_id *)&null_oid;
1786         }
1787         one.path = a.path = b.path = (char *)path;
1788         oidcpy(&one.oid, o_oid);
1789         one.mode = o_mode;
1790         oidcpy(&a.oid, a_oid);
1791         a.mode = a_mode;
1792         oidcpy(&b.oid, b_oid);
1793         b.mode = b_mode;
1794
1795         if (rename_conflict_info) {
1796                 struct diff_filepair *pair1 = rename_conflict_info->pair1;
1797
1798                 path1 = (o->branch1 == rename_conflict_info->branch1) ?
1799                         pair1->two->path : pair1->one->path;
1800                 /* If rename_conflict_info->pair2 != NULL, we are in
1801                  * RENAME_ONE_FILE_TO_ONE case.  Otherwise, we have a
1802                  * normal rename.
1803                  */
1804                 path2 = (rename_conflict_info->pair2 ||
1805                          o->branch2 == rename_conflict_info->branch1) ?
1806                         pair1->two->path : pair1->one->path;
1807
1808                 if (dir_in_way(path, !o->call_depth,
1809                                S_ISGITLINK(pair1->two->mode)))
1810                         df_conflict_remains = 1;
1811         }
1812         if (merge_file_special_markers(o, &one, &a, &b,
1813                                        o->branch1, path1,
1814                                        o->branch2, path2, &mfi))
1815                 return -1;
1816
1817         if (mfi.clean && !df_conflict_remains &&
1818             oid_eq(&mfi.oid, a_oid) && mfi.mode == a_mode) {
1819                 int path_renamed_outside_HEAD;
1820                 output(o, 3, _("Skipped %s (merged same as existing)"), path);
1821                 /*
1822                  * The content merge resulted in the same file contents we
1823                  * already had.  We can return early if those file contents
1824                  * are recorded at the correct path (which may not be true
1825                  * if the merge involves a rename).
1826                  */
1827                 path_renamed_outside_HEAD = !path2 || !strcmp(path, path2);
1828                 if (!path_renamed_outside_HEAD) {
1829                         add_cacheinfo(o, mfi.mode, &mfi.oid, path,
1830                                       0, (!o->call_depth), 0);
1831                         return mfi.clean;
1832                 }
1833         } else
1834                 output(o, 2, _("Auto-merging %s"), path);
1835
1836         if (!mfi.clean) {
1837                 if (S_ISGITLINK(mfi.mode))
1838                         reason = _("submodule");
1839                 output(o, 1, _("CONFLICT (%s): Merge conflict in %s"),
1840                                 reason, path);
1841                 if (rename_conflict_info && !df_conflict_remains)
1842                         if (update_stages(o, path, &one, &a, &b))
1843                                 return -1;
1844         }
1845
1846         if (df_conflict_remains) {
1847                 char *new_path;
1848                 if (o->call_depth) {
1849                         remove_file_from_cache(path);
1850                 } else {
1851                         if (!mfi.clean) {
1852                                 if (update_stages(o, path, &one, &a, &b))
1853                                         return -1;
1854                         } else {
1855                                 int file_from_stage2 = was_tracked(path);
1856                                 struct diff_filespec merged;
1857                                 oidcpy(&merged.oid, &mfi.oid);
1858                                 merged.mode = mfi.mode;
1859
1860                                 if (update_stages(o, path, NULL,
1861                                                   file_from_stage2 ? &merged : NULL,
1862                                                   file_from_stage2 ? NULL : &merged))
1863                                         return -1;
1864                         }
1865
1866                 }
1867                 new_path = unique_path(o, path, rename_conflict_info->branch1);
1868                 output(o, 1, _("Adding as %s instead"), new_path);
1869                 if (update_file(o, 0, &mfi.oid, mfi.mode, new_path)) {
1870                         free(new_path);
1871                         return -1;
1872                 }
1873                 free(new_path);
1874                 mfi.clean = 0;
1875         } else if (update_file(o, mfi.clean, &mfi.oid, mfi.mode, path))
1876                 return -1;
1877         return mfi.clean;
1878 }
1879
1880 /* Per entry merge function */
1881 static int process_entry(struct merge_options *o,
1882                          const char *path, struct stage_data *entry)
1883 {
1884         int clean_merge = 1;
1885         int normalize = o->renormalize;
1886         unsigned o_mode = entry->stages[1].mode;
1887         unsigned a_mode = entry->stages[2].mode;
1888         unsigned b_mode = entry->stages[3].mode;
1889         struct object_id *o_oid = stage_oid(&entry->stages[1].oid, o_mode);
1890         struct object_id *a_oid = stage_oid(&entry->stages[2].oid, a_mode);
1891         struct object_id *b_oid = stage_oid(&entry->stages[3].oid, b_mode);
1892
1893         entry->processed = 1;
1894         if (entry->rename_conflict_info) {
1895                 struct rename_conflict_info *conflict_info = entry->rename_conflict_info;
1896                 switch (conflict_info->rename_type) {
1897                 case RENAME_NORMAL:
1898                 case RENAME_ONE_FILE_TO_ONE:
1899                         clean_merge = merge_content(o, path,
1900                                                     o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,
1901                                                     conflict_info);
1902                         break;
1903                 case RENAME_DELETE:
1904                         clean_merge = 0;
1905                         if (conflict_rename_delete(o,
1906                                                    conflict_info->pair1,
1907                                                    conflict_info->branch1,
1908                                                    conflict_info->branch2))
1909                                 clean_merge = -1;
1910                         break;
1911                 case RENAME_ONE_FILE_TO_TWO:
1912                         clean_merge = 0;
1913                         if (conflict_rename_rename_1to2(o, conflict_info))
1914                                 clean_merge = -1;
1915                         break;
1916                 case RENAME_TWO_FILES_TO_ONE:
1917                         clean_merge = 0;
1918                         if (conflict_rename_rename_2to1(o, conflict_info))
1919                                 clean_merge = -1;
1920                         break;
1921                 default:
1922                         entry->processed = 0;
1923                         break;
1924                 }
1925         } else if (o_oid && (!a_oid || !b_oid)) {
1926                 /* Case A: Deleted in one */
1927                 if ((!a_oid && !b_oid) ||
1928                     (!b_oid && blob_unchanged(o, o_oid, o_mode, a_oid, a_mode, normalize, path)) ||
1929                     (!a_oid && blob_unchanged(o, o_oid, o_mode, b_oid, b_mode, normalize, path))) {
1930                         /* Deleted in both or deleted in one and
1931                          * unchanged in the other */
1932                         if (a_oid)
1933                                 output(o, 2, _("Removing %s"), path);
1934                         /* do not touch working file if it did not exist */
1935                         remove_file(o, 1, path, !a_oid);
1936                 } else {
1937                         /* Modify/delete; deleted side may have put a directory in the way */
1938                         clean_merge = 0;
1939                         if (handle_modify_delete(o, path, o_oid, o_mode,
1940                                                  a_oid, a_mode, b_oid, b_mode))
1941                                 clean_merge = -1;
1942                 }
1943         } else if ((!o_oid && a_oid && !b_oid) ||
1944                    (!o_oid && !a_oid && b_oid)) {
1945                 /* Case B: Added in one. */
1946                 /* [nothing|directory] -> ([nothing|directory], file) */
1947
1948                 const char *add_branch;
1949                 const char *other_branch;
1950                 unsigned mode;
1951                 const struct object_id *oid;
1952                 const char *conf;
1953
1954                 if (a_oid) {
1955                         add_branch = o->branch1;
1956                         other_branch = o->branch2;
1957                         mode = a_mode;
1958                         oid = a_oid;
1959                         conf = _("file/directory");
1960                 } else {
1961                         add_branch = o->branch2;
1962                         other_branch = o->branch1;
1963                         mode = b_mode;
1964                         oid = b_oid;
1965                         conf = _("directory/file");
1966                 }
1967                 if (dir_in_way(path,
1968                                !o->call_depth && !S_ISGITLINK(a_mode),
1969                                0)) {
1970                         char *new_path = unique_path(o, path, add_branch);
1971                         clean_merge = 0;
1972                         output(o, 1, _("CONFLICT (%s): There is a directory with name %s in %s. "
1973                                "Adding %s as %s"),
1974                                conf, path, other_branch, path, new_path);
1975                         if (update_file(o, 0, oid, mode, new_path))
1976                                 clean_merge = -1;
1977                         else if (o->call_depth)
1978                                 remove_file_from_cache(path);
1979                         free(new_path);
1980                 } else {
1981                         output(o, 2, _("Adding %s"), path);
1982                         /* do not overwrite file if already present */
1983                         if (update_file_flags(o, oid, mode, path, 1, !a_oid))
1984                                 clean_merge = -1;
1985                 }
1986         } else if (a_oid && b_oid) {
1987                 /* Case C: Added in both (check for same permissions) and */
1988                 /* case D: Modified in both, but differently. */
1989                 clean_merge = merge_content(o, path,
1990                                             o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,
1991                                             NULL);
1992         } else if (!o_oid && !a_oid && !b_oid) {
1993                 /*
1994                  * this entry was deleted altogether. a_mode == 0 means
1995                  * we had that path and want to actively remove it.
1996                  */
1997                 remove_file(o, 1, path, !a_mode);
1998         } else
1999                 die("BUG: fatal merge failure, shouldn't happen.");
2000
2001         return clean_merge;
2002 }
2003
2004 int merge_trees(struct merge_options *o,
2005                 struct tree *head,
2006                 struct tree *merge,
2007                 struct tree *common,
2008                 struct tree **result)
2009 {
2010         int code, clean;
2011
2012         if (o->subtree_shift) {
2013                 merge = shift_tree_object(head, merge, o->subtree_shift);
2014                 common = shift_tree_object(head, common, o->subtree_shift);
2015         }
2016
2017         if (oid_eq(&common->object.oid, &merge->object.oid)) {
2018                 struct strbuf sb = STRBUF_INIT;
2019
2020                 if (!o->call_depth && index_has_changes(&sb)) {
2021                         err(o, _("Dirty index: cannot merge (dirty: %s)"),
2022                             sb.buf);
2023                         return 0;
2024                 }
2025                 output(o, 0, _("Already up to date!"));
2026                 *result = head;
2027                 return 1;
2028         }
2029
2030         code = git_merge_trees(o->call_depth, common, head, merge);
2031
2032         if (code != 0) {
2033                 if (show(o, 4) || o->call_depth)
2034                         err(o, _("merging of trees %s and %s failed"),
2035                             oid_to_hex(&head->object.oid),
2036                             oid_to_hex(&merge->object.oid));
2037                 return -1;
2038         }
2039
2040         if (unmerged_cache()) {
2041                 struct string_list *entries;
2042                 struct rename_info re_info;
2043                 int i;
2044                 /*
2045                  * Only need the hashmap while processing entries, so
2046                  * initialize it here and free it when we are done running
2047                  * through the entries. Keeping it in the merge_options as
2048                  * opposed to decaring a local hashmap is for convenience
2049                  * so that we don't have to pass it to around.
2050                  */
2051                 hashmap_init(&o->current_file_dir_set, path_hashmap_cmp, NULL, 512);
2052                 get_files_dirs(o, head);
2053                 get_files_dirs(o, merge);
2054
2055                 entries = get_unmerged();
2056                 clean = handle_renames(o, common, head, merge, entries,
2057                                        &re_info);
2058                 record_df_conflict_files(o, entries);
2059                 if (clean < 0)
2060                         goto cleanup;
2061                 for (i = entries->nr-1; 0 <= i; i--) {
2062                         const char *path = entries->items[i].string;
2063                         struct stage_data *e = entries->items[i].util;
2064                         if (!e->processed) {
2065                                 int ret = process_entry(o, path, e);
2066                                 if (!ret)
2067                                         clean = 0;
2068                                 else if (ret < 0) {
2069                                         clean = ret;
2070                                         goto cleanup;
2071                                 }
2072                         }
2073                 }
2074                 for (i = 0; i < entries->nr; i++) {
2075                         struct stage_data *e = entries->items[i].util;
2076                         if (!e->processed)
2077                                 die("BUG: unprocessed path??? %s",
2078                                     entries->items[i].string);
2079                 }
2080
2081 cleanup:
2082                 cleanup_renames(&re_info);
2083
2084                 string_list_clear(entries, 1);
2085                 free(entries);
2086
2087                 hashmap_free(&o->current_file_dir_set, 1);
2088
2089                 if (clean < 0)
2090                         return clean;
2091         }
2092         else
2093                 clean = 1;
2094
2095         if (o->call_depth && !(*result = write_tree_from_memory(o)))
2096                 return -1;
2097
2098         return clean;
2099 }
2100
2101 static struct commit_list *reverse_commit_list(struct commit_list *list)
2102 {
2103         struct commit_list *next = NULL, *current, *backup;
2104         for (current = list; current; current = backup) {
2105                 backup = current->next;
2106                 current->next = next;
2107                 next = current;
2108         }
2109         return next;
2110 }
2111
2112 /*
2113  * Merge the commits h1 and h2, return the resulting virtual
2114  * commit object and a flag indicating the cleanness of the merge.
2115  */
2116 int merge_recursive(struct merge_options *o,
2117                     struct commit *h1,
2118                     struct commit *h2,
2119                     struct commit_list *ca,
2120                     struct commit **result)
2121 {
2122         struct commit_list *iter;
2123         struct commit *merged_common_ancestors;
2124         struct tree *mrtree = mrtree;
2125         int clean;
2126
2127         if (show(o, 4)) {
2128                 output(o, 4, _("Merging:"));
2129                 output_commit_title(o, h1);
2130                 output_commit_title(o, h2);
2131         }
2132
2133         if (!ca) {
2134                 ca = get_merge_bases(h1, h2);
2135                 ca = reverse_commit_list(ca);
2136         }
2137
2138         if (show(o, 5)) {
2139                 unsigned cnt = commit_list_count(ca);
2140
2141                 output(o, 5, Q_("found %u common ancestor:",
2142                                 "found %u common ancestors:", cnt), cnt);
2143                 for (iter = ca; iter; iter = iter->next)
2144                         output_commit_title(o, iter->item);
2145         }
2146
2147         merged_common_ancestors = pop_commit(&ca);
2148         if (merged_common_ancestors == NULL) {
2149                 /* if there is no common ancestor, use an empty tree */
2150                 struct tree *tree;
2151
2152                 tree = lookup_tree(the_hash_algo->empty_tree);
2153                 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
2154         }
2155
2156         for (iter = ca; iter; iter = iter->next) {
2157                 const char *saved_b1, *saved_b2;
2158                 o->call_depth++;
2159                 /*
2160                  * When the merge fails, the result contains files
2161                  * with conflict markers. The cleanness flag is
2162                  * ignored (unless indicating an error), it was never
2163                  * actually used, as result of merge_trees has always
2164                  * overwritten it: the committed "conflicts" were
2165                  * already resolved.
2166                  */
2167                 discard_cache();
2168                 saved_b1 = o->branch1;
2169                 saved_b2 = o->branch2;
2170                 o->branch1 = "Temporary merge branch 1";
2171                 o->branch2 = "Temporary merge branch 2";
2172                 if (merge_recursive(o, merged_common_ancestors, iter->item,
2173                                     NULL, &merged_common_ancestors) < 0)
2174                         return -1;
2175                 o->branch1 = saved_b1;
2176                 o->branch2 = saved_b2;
2177                 o->call_depth--;
2178
2179                 if (!merged_common_ancestors)
2180                         return err(o, _("merge returned no commit"));
2181         }
2182
2183         discard_cache();
2184         if (!o->call_depth)
2185                 read_cache();
2186
2187         o->ancestor = "merged common ancestors";
2188         clean = merge_trees(o, h1->tree, h2->tree, merged_common_ancestors->tree,
2189                             &mrtree);
2190         if (clean < 0) {
2191                 flush_output(o);
2192                 return clean;
2193         }
2194
2195         if (o->call_depth) {
2196                 *result = make_virtual_commit(mrtree, "merged tree");
2197                 commit_list_insert(h1, &(*result)->parents);
2198                 commit_list_insert(h2, &(*result)->parents->next);
2199         }
2200         flush_output(o);
2201         if (!o->call_depth && o->buffer_output < 2)
2202                 strbuf_release(&o->obuf);
2203         if (show(o, 2))
2204                 diff_warn_rename_limit("merge.renamelimit",
2205                                        o->needed_rename_limit, 0);
2206         return clean;
2207 }
2208
2209 static struct commit *get_ref(const struct object_id *oid, const char *name)
2210 {
2211         struct object *object;
2212
2213         object = deref_tag(parse_object(oid), name, strlen(name));
2214         if (!object)
2215                 return NULL;
2216         if (object->type == OBJ_TREE)
2217                 return make_virtual_commit((struct tree*)object, name);
2218         if (object->type != OBJ_COMMIT)
2219                 return NULL;
2220         if (parse_commit((struct commit *)object))
2221                 return NULL;
2222         return (struct commit *)object;
2223 }
2224
2225 int merge_recursive_generic(struct merge_options *o,
2226                             const struct object_id *head,
2227                             const struct object_id *merge,
2228                             int num_base_list,
2229                             const struct object_id **base_list,
2230                             struct commit **result)
2231 {
2232         int clean;
2233         struct lock_file lock = LOCK_INIT;
2234         struct commit *head_commit = get_ref(head, o->branch1);
2235         struct commit *next_commit = get_ref(merge, o->branch2);
2236         struct commit_list *ca = NULL;
2237
2238         if (base_list) {
2239                 int i;
2240                 for (i = 0; i < num_base_list; ++i) {
2241                         struct commit *base;
2242                         if (!(base = get_ref(base_list[i], oid_to_hex(base_list[i]))))
2243                                 return err(o, _("Could not parse object '%s'"),
2244                                         oid_to_hex(base_list[i]));
2245                         commit_list_insert(base, &ca);
2246                 }
2247         }
2248
2249         hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
2250         clean = merge_recursive(o, head_commit, next_commit, ca,
2251                         result);
2252         if (clean < 0)
2253                 return clean;
2254
2255         if (active_cache_changed &&
2256             write_locked_index(&the_index, &lock, COMMIT_LOCK))
2257                 return err(o, _("Unable to write index."));
2258
2259         return clean ? 0 : 1;
2260 }
2261
2262 static void merge_recursive_config(struct merge_options *o)
2263 {
2264         git_config_get_int("merge.verbosity", &o->verbosity);
2265         git_config_get_int("diff.renamelimit", &o->diff_rename_limit);
2266         git_config_get_int("merge.renamelimit", &o->merge_rename_limit);
2267         git_config(git_xmerge_config, NULL);
2268 }
2269
2270 void init_merge_options(struct merge_options *o)
2271 {
2272         const char *merge_verbosity;
2273         memset(o, 0, sizeof(struct merge_options));
2274         o->verbosity = 2;
2275         o->buffer_output = 1;
2276         o->diff_rename_limit = -1;
2277         o->merge_rename_limit = -1;
2278         o->renormalize = 0;
2279         o->detect_rename = 1;
2280         merge_recursive_config(o);
2281         merge_verbosity = getenv("GIT_MERGE_VERBOSITY");
2282         if (merge_verbosity)
2283                 o->verbosity = strtol(merge_verbosity, NULL, 10);
2284         if (o->verbosity >= 5)
2285                 o->buffer_output = 0;
2286         strbuf_init(&o->obuf, 0);
2287         string_list_init(&o->df_conflict_file_set, 1);
2288 }
2289
2290 int parse_merge_opt(struct merge_options *o, const char *s)
2291 {
2292         const char *arg;
2293
2294         if (!s || !*s)
2295                 return -1;
2296         if (!strcmp(s, "ours"))
2297                 o->recursive_variant = MERGE_RECURSIVE_OURS;
2298         else if (!strcmp(s, "theirs"))
2299                 o->recursive_variant = MERGE_RECURSIVE_THEIRS;
2300         else if (!strcmp(s, "subtree"))
2301                 o->subtree_shift = "";
2302         else if (skip_prefix(s, "subtree=", &arg))
2303                 o->subtree_shift = arg;
2304         else if (!strcmp(s, "patience"))
2305                 o->xdl_opts = DIFF_WITH_ALG(o, PATIENCE_DIFF);
2306         else if (!strcmp(s, "histogram"))
2307                 o->xdl_opts = DIFF_WITH_ALG(o, HISTOGRAM_DIFF);
2308         else if (skip_prefix(s, "diff-algorithm=", &arg)) {
2309                 long value = parse_algorithm_value(arg);
2310                 if (value < 0)
2311                         return -1;
2312                 /* clear out previous settings */
2313                 DIFF_XDL_CLR(o, NEED_MINIMAL);
2314                 o->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
2315                 o->xdl_opts |= value;
2316         }
2317         else if (!strcmp(s, "ignore-space-change"))
2318                 DIFF_XDL_SET(o, IGNORE_WHITESPACE_CHANGE);
2319         else if (!strcmp(s, "ignore-all-space"))
2320                 DIFF_XDL_SET(o, IGNORE_WHITESPACE);
2321         else if (!strcmp(s, "ignore-space-at-eol"))
2322                 DIFF_XDL_SET(o, IGNORE_WHITESPACE_AT_EOL);
2323         else if (!strcmp(s, "ignore-cr-at-eol"))
2324                 DIFF_XDL_SET(o, IGNORE_CR_AT_EOL);
2325         else if (!strcmp(s, "renormalize"))
2326                 o->renormalize = 1;
2327         else if (!strcmp(s, "no-renormalize"))
2328                 o->renormalize = 0;
2329         else if (!strcmp(s, "no-renames"))
2330                 o->detect_rename = 0;
2331         else if (!strcmp(s, "find-renames")) {
2332                 o->detect_rename = 1;
2333                 o->rename_score = 0;
2334         }
2335         else if (skip_prefix(s, "find-renames=", &arg) ||
2336                  skip_prefix(s, "rename-threshold=", &arg)) {
2337                 if ((o->rename_score = parse_rename_score(&arg)) == -1 || *arg != 0)
2338                         return -1;
2339                 o->detect_rename = 1;
2340         }
2341         else
2342                 return -1;
2343         return 0;
2344 }