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