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