merge-recursive --patience
[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 "advice.h"
7 #include "cache.h"
8 #include "cache-tree.h"
9 #include "commit.h"
10 #include "blob.h"
11 #include "builtin.h"
12 #include "tree-walk.h"
13 #include "diff.h"
14 #include "diffcore.h"
15 #include "tag.h"
16 #include "unpack-trees.h"
17 #include "string-list.h"
18 #include "xdiff-interface.h"
19 #include "ll-merge.h"
20 #include "attr.h"
21 #include "merge-recursive.h"
22 #include "dir.h"
23
24 static struct tree *shift_tree_object(struct tree *one, struct tree *two,
25                                       const char *subtree_shift)
26 {
27         unsigned char shifted[20];
28
29         if (!*subtree_shift) {
30                 shift_tree(one->object.sha1, two->object.sha1, shifted, 0);
31         } else {
32                 shift_tree_by(one->object.sha1, two->object.sha1, shifted,
33                               subtree_shift);
34         }
35         if (!hashcmp(two->object.sha1, shifted))
36                 return two;
37         return lookup_tree(shifted);
38 }
39
40 /*
41  * A virtual commit has (const char *)commit->util set to the name.
42  */
43
44 static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
45 {
46         struct commit *commit = xcalloc(1, sizeof(struct commit));
47         commit->tree = tree;
48         commit->util = (void*)comment;
49         /* avoid warnings */
50         commit->object.parsed = 1;
51         return commit;
52 }
53
54 /*
55  * Since we use get_tree_entry(), which does not put the read object into
56  * the object pool, we cannot rely on a == b.
57  */
58 static int sha_eq(const unsigned char *a, const unsigned char *b)
59 {
60         if (!a && !b)
61                 return 2;
62         return a && b && hashcmp(a, b) == 0;
63 }
64
65 /*
66  * Since we want to write the index eventually, we cannot reuse the index
67  * for these (temporary) data.
68  */
69 struct stage_data
70 {
71         struct
72         {
73                 unsigned mode;
74                 unsigned char sha[20];
75         } stages[4];
76         unsigned processed:1;
77 };
78
79 static int show(struct merge_options *o, int v)
80 {
81         return (!o->call_depth && o->verbosity >= v) || o->verbosity >= 5;
82 }
83
84 static void flush_output(struct merge_options *o)
85 {
86         if (o->obuf.len) {
87                 fputs(o->obuf.buf, stdout);
88                 strbuf_reset(&o->obuf);
89         }
90 }
91
92 __attribute__((format (printf, 3, 4)))
93 static void output(struct merge_options *o, int v, const char *fmt, ...)
94 {
95         int len;
96         va_list ap;
97
98         if (!show(o, v))
99                 return;
100
101         strbuf_grow(&o->obuf, o->call_depth * 2 + 2);
102         memset(o->obuf.buf + o->obuf.len, ' ', o->call_depth * 2);
103         strbuf_setlen(&o->obuf, o->obuf.len + o->call_depth * 2);
104
105         va_start(ap, fmt);
106         len = vsnprintf(o->obuf.buf + o->obuf.len, strbuf_avail(&o->obuf), fmt, ap);
107         va_end(ap);
108
109         if (len < 0)
110                 len = 0;
111         if (len >= strbuf_avail(&o->obuf)) {
112                 strbuf_grow(&o->obuf, len + 2);
113                 va_start(ap, fmt);
114                 len = vsnprintf(o->obuf.buf + o->obuf.len, strbuf_avail(&o->obuf), fmt, ap);
115                 va_end(ap);
116                 if (len >= strbuf_avail(&o->obuf)) {
117                         die("this should not happen, your snprintf is broken");
118                 }
119         }
120         strbuf_setlen(&o->obuf, o->obuf.len + len);
121         strbuf_add(&o->obuf, "\n", 1);
122         if (!o->buffer_output)
123                 flush_output(o);
124 }
125
126 static void output_commit_title(struct merge_options *o, struct commit *commit)
127 {
128         int i;
129         flush_output(o);
130         for (i = o->call_depth; i--;)
131                 fputs("  ", stdout);
132         if (commit->util)
133                 printf("virtual %s\n", (char *)commit->util);
134         else {
135                 printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
136                 if (parse_commit(commit) != 0)
137                         printf("(bad commit)\n");
138                 else {
139                         const char *s;
140                         int len;
141                         for (s = commit->buffer; *s; s++)
142                                 if (*s == '\n' && s[1] == '\n') {
143                                         s += 2;
144                                         break;
145                                 }
146                         for (len = 0; s[len] && '\n' != s[len]; len++)
147                                 ; /* do nothing */
148                         printf("%.*s\n", len, s);
149                 }
150         }
151 }
152
153 static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
154                 const char *path, int stage, int refresh, int options)
155 {
156         struct cache_entry *ce;
157         ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
158         if (!ce)
159                 return error("addinfo_cache failed for path '%s'", path);
160         return add_cache_entry(ce, options);
161 }
162
163 static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
164 {
165         parse_tree(tree);
166         init_tree_desc(desc, tree->buffer, tree->size);
167 }
168
169 static int git_merge_trees(int index_only,
170                            struct tree *common,
171                            struct tree *head,
172                            struct tree *merge)
173 {
174         int rc;
175         struct tree_desc t[3];
176         struct unpack_trees_options opts;
177
178         memset(&opts, 0, sizeof(opts));
179         if (index_only)
180                 opts.index_only = 1;
181         else
182                 opts.update = 1;
183         opts.merge = 1;
184         opts.head_idx = 2;
185         opts.fn = threeway_merge;
186         opts.src_index = &the_index;
187         opts.dst_index = &the_index;
188         opts.msgs = get_porcelain_error_msgs();
189
190         init_tree_desc_from_tree(t+0, common);
191         init_tree_desc_from_tree(t+1, head);
192         init_tree_desc_from_tree(t+2, merge);
193
194         rc = unpack_trees(3, t, &opts);
195         cache_tree_free(&active_cache_tree);
196         return rc;
197 }
198
199 struct tree *write_tree_from_memory(struct merge_options *o)
200 {
201         struct tree *result = NULL;
202
203         if (unmerged_cache()) {
204                 int i;
205                 fprintf(stderr, "BUG: There are unmerged index entries:\n");
206                 for (i = 0; i < active_nr; i++) {
207                         struct cache_entry *ce = active_cache[i];
208                         if (ce_stage(ce))
209                                 fprintf(stderr, "BUG: %d %.*s", ce_stage(ce),
210                                         (int)ce_namelen(ce), ce->name);
211                 }
212                 die("Bug in merge-recursive.c");
213         }
214
215         if (!active_cache_tree)
216                 active_cache_tree = cache_tree();
217
218         if (!cache_tree_fully_valid(active_cache_tree) &&
219             cache_tree_update(active_cache_tree,
220                               active_cache, active_nr, 0, 0) < 0)
221                 die("error building trees");
222
223         result = lookup_tree(active_cache_tree->sha1);
224
225         return result;
226 }
227
228 static int save_files_dirs(const unsigned char *sha1,
229                 const char *base, int baselen, const char *path,
230                 unsigned int mode, int stage, void *context)
231 {
232         int len = strlen(path);
233         char *newpath = xmalloc(baselen + len + 1);
234         struct merge_options *o = context;
235
236         memcpy(newpath, base, baselen);
237         memcpy(newpath + baselen, path, len);
238         newpath[baselen + len] = '\0';
239
240         if (S_ISDIR(mode))
241                 string_list_insert(newpath, &o->current_directory_set);
242         else
243                 string_list_insert(newpath, &o->current_file_set);
244         free(newpath);
245
246         return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
247 }
248
249 static int get_files_dirs(struct merge_options *o, struct tree *tree)
250 {
251         int n;
252         if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs, o))
253                 return 0;
254         n = o->current_file_set.nr + o->current_directory_set.nr;
255         return n;
256 }
257
258 /*
259  * Returns an index_entry instance which doesn't have to correspond to
260  * a real cache entry in Git's index.
261  */
262 static struct stage_data *insert_stage_data(const char *path,
263                 struct tree *o, struct tree *a, struct tree *b,
264                 struct string_list *entries)
265 {
266         struct string_list_item *item;
267         struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
268         get_tree_entry(o->object.sha1, path,
269                         e->stages[1].sha, &e->stages[1].mode);
270         get_tree_entry(a->object.sha1, path,
271                         e->stages[2].sha, &e->stages[2].mode);
272         get_tree_entry(b->object.sha1, path,
273                         e->stages[3].sha, &e->stages[3].mode);
274         item = string_list_insert(path, entries);
275         item->util = e;
276         return e;
277 }
278
279 /*
280  * Create a dictionary mapping file names to stage_data objects. The
281  * dictionary contains one entry for every path with a non-zero stage entry.
282  */
283 static struct string_list *get_unmerged(void)
284 {
285         struct string_list *unmerged = xcalloc(1, sizeof(struct string_list));
286         int i;
287
288         unmerged->strdup_strings = 1;
289
290         for (i = 0; i < active_nr; i++) {
291                 struct string_list_item *item;
292                 struct stage_data *e;
293                 struct cache_entry *ce = active_cache[i];
294                 if (!ce_stage(ce))
295                         continue;
296
297                 item = string_list_lookup(ce->name, unmerged);
298                 if (!item) {
299                         item = string_list_insert(ce->name, unmerged);
300                         item->util = xcalloc(1, sizeof(struct stage_data));
301                 }
302                 e = item->util;
303                 e->stages[ce_stage(ce)].mode = ce->ce_mode;
304                 hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
305         }
306
307         return unmerged;
308 }
309
310 struct rename
311 {
312         struct diff_filepair *pair;
313         struct stage_data *src_entry;
314         struct stage_data *dst_entry;
315         unsigned processed:1;
316 };
317
318 /*
319  * Get information of all renames which occurred between 'o_tree' and
320  * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
321  * 'b_tree') to be able to associate the correct cache entries with
322  * the rename information. 'tree' is always equal to either a_tree or b_tree.
323  */
324 static struct string_list *get_renames(struct merge_options *o,
325                                        struct tree *tree,
326                                        struct tree *o_tree,
327                                        struct tree *a_tree,
328                                        struct tree *b_tree,
329                                        struct string_list *entries)
330 {
331         int i;
332         struct string_list *renames;
333         struct diff_options opts;
334
335         renames = xcalloc(1, sizeof(struct string_list));
336         diff_setup(&opts);
337         DIFF_OPT_SET(&opts, RECURSIVE);
338         opts.detect_rename = DIFF_DETECT_RENAME;
339         opts.rename_limit = o->merge_rename_limit >= 0 ? o->merge_rename_limit :
340                             o->diff_rename_limit >= 0 ? o->diff_rename_limit :
341                             500;
342         opts.warn_on_too_large_rename = 1;
343         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
344         if (diff_setup_done(&opts) < 0)
345                 die("diff setup failed");
346         diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
347         diffcore_std(&opts);
348         for (i = 0; i < diff_queued_diff.nr; ++i) {
349                 struct string_list_item *item;
350                 struct rename *re;
351                 struct diff_filepair *pair = diff_queued_diff.queue[i];
352                 if (pair->status != 'R') {
353                         diff_free_filepair(pair);
354                         continue;
355                 }
356                 re = xmalloc(sizeof(*re));
357                 re->processed = 0;
358                 re->pair = pair;
359                 item = string_list_lookup(re->pair->one->path, entries);
360                 if (!item)
361                         re->src_entry = insert_stage_data(re->pair->one->path,
362                                         o_tree, a_tree, b_tree, entries);
363                 else
364                         re->src_entry = item->util;
365
366                 item = string_list_lookup(re->pair->two->path, entries);
367                 if (!item)
368                         re->dst_entry = insert_stage_data(re->pair->two->path,
369                                         o_tree, a_tree, b_tree, entries);
370                 else
371                         re->dst_entry = item->util;
372                 item = string_list_insert(pair->one->path, renames);
373                 item->util = re;
374         }
375         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
376         diff_queued_diff.nr = 0;
377         diff_flush(&opts);
378         return renames;
379 }
380
381 static int update_stages(const char *path, struct diff_filespec *o,
382                          struct diff_filespec *a, struct diff_filespec *b,
383                          int clear)
384 {
385         int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
386         if (clear)
387                 if (remove_file_from_cache(path))
388                         return -1;
389         if (o)
390                 if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
391                         return -1;
392         if (a)
393                 if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
394                         return -1;
395         if (b)
396                 if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
397                         return -1;
398         return 0;
399 }
400
401 static int remove_file(struct merge_options *o, int clean,
402                        const char *path, int no_wd)
403 {
404         int update_cache = o->call_depth || clean;
405         int update_working_directory = !o->call_depth && !no_wd;
406
407         if (update_cache) {
408                 if (remove_file_from_cache(path))
409                         return -1;
410         }
411         if (update_working_directory) {
412                 if (remove_path(path))
413                         return -1;
414         }
415         return 0;
416 }
417
418 static char *unique_path(struct merge_options *o, const char *path, const char *branch)
419 {
420         char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
421         int suffix = 0;
422         struct stat st;
423         char *p = newpath + strlen(path);
424         strcpy(newpath, path);
425         *(p++) = '~';
426         strcpy(p, branch);
427         for (; *p; ++p)
428                 if ('/' == *p)
429                         *p = '_';
430         while (string_list_has_string(&o->current_file_set, newpath) ||
431                string_list_has_string(&o->current_directory_set, newpath) ||
432                lstat(newpath, &st) == 0)
433                 sprintf(p, "_%d", suffix++);
434
435         string_list_insert(newpath, &o->current_file_set);
436         return newpath;
437 }
438
439 static void flush_buffer(int fd, const char *buf, unsigned long size)
440 {
441         while (size > 0) {
442                 long ret = write_in_full(fd, buf, size);
443                 if (ret < 0) {
444                         /* Ignore epipe */
445                         if (errno == EPIPE)
446                                 break;
447                         die_errno("merge-recursive");
448                 } else if (!ret) {
449                         die("merge-recursive: disk full?");
450                 }
451                 size -= ret;
452                 buf += ret;
453         }
454 }
455
456 static int would_lose_untracked(const char *path)
457 {
458         int pos = cache_name_pos(path, strlen(path));
459
460         if (pos < 0)
461                 pos = -1 - pos;
462         while (pos < active_nr &&
463                !strcmp(path, active_cache[pos]->name)) {
464                 /*
465                  * If stage #0, it is definitely tracked.
466                  * If it has stage #2 then it was tracked
467                  * before this merge started.  All other
468                  * cases the path was not tracked.
469                  */
470                 switch (ce_stage(active_cache[pos])) {
471                 case 0:
472                 case 2:
473                         return 0;
474                 }
475                 pos++;
476         }
477         return file_exists(path);
478 }
479
480 static int make_room_for_path(const char *path)
481 {
482         int status;
483         const char *msg = "failed to create path '%s'%s";
484
485         status = safe_create_leading_directories_const(path);
486         if (status) {
487                 if (status == -3) {
488                         /* something else exists */
489                         error(msg, path, ": perhaps a D/F conflict?");
490                         return -1;
491                 }
492                 die(msg, path, "");
493         }
494
495         /*
496          * Do not unlink a file in the work tree if we are not
497          * tracking it.
498          */
499         if (would_lose_untracked(path))
500                 return error("refusing to lose untracked file at '%s'",
501                              path);
502
503         /* Successful unlink is good.. */
504         if (!unlink(path))
505                 return 0;
506         /* .. and so is no existing file */
507         if (errno == ENOENT)
508                 return 0;
509         /* .. but not some other error (who really cares what?) */
510         return error(msg, path, ": perhaps a D/F conflict?");
511 }
512
513 static void update_file_flags(struct merge_options *o,
514                               const unsigned char *sha,
515                               unsigned mode,
516                               const char *path,
517                               int update_cache,
518                               int update_wd)
519 {
520         if (o->call_depth)
521                 update_wd = 0;
522
523         if (update_wd) {
524                 enum object_type type;
525                 void *buf;
526                 unsigned long size;
527
528                 if (S_ISGITLINK(mode))
529                         /*
530                          * We may later decide to recursively descend into
531                          * the submodule directory and update its index
532                          * and/or work tree, but we do not do that now.
533                          */
534                         goto update_index;
535
536                 buf = read_sha1_file(sha, &type, &size);
537                 if (!buf)
538                         die("cannot read object %s '%s'", sha1_to_hex(sha), path);
539                 if (type != OBJ_BLOB)
540                         die("blob expected for %s '%s'", sha1_to_hex(sha), path);
541                 if (S_ISREG(mode)) {
542                         struct strbuf strbuf = STRBUF_INIT;
543                         if (convert_to_working_tree(path, buf, size, &strbuf)) {
544                                 free(buf);
545                                 size = strbuf.len;
546                                 buf = strbuf_detach(&strbuf, NULL);
547                         }
548                 }
549
550                 if (make_room_for_path(path) < 0) {
551                         update_wd = 0;
552                         free(buf);
553                         goto update_index;
554                 }
555                 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
556                         int fd;
557                         if (mode & 0100)
558                                 mode = 0777;
559                         else
560                                 mode = 0666;
561                         fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
562                         if (fd < 0)
563                                 die_errno("failed to open '%s'", path);
564                         flush_buffer(fd, buf, size);
565                         close(fd);
566                 } else if (S_ISLNK(mode)) {
567                         char *lnk = xmemdupz(buf, size);
568                         safe_create_leading_directories_const(path);
569                         unlink(path);
570                         if (symlink(lnk, path))
571                                 die_errno("failed to symlink '%s'", path);
572                         free(lnk);
573                 } else
574                         die("do not know what to do with %06o %s '%s'",
575                             mode, sha1_to_hex(sha), path);
576                 free(buf);
577         }
578  update_index:
579         if (update_cache)
580                 add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
581 }
582
583 static void update_file(struct merge_options *o,
584                         int clean,
585                         const unsigned char *sha,
586                         unsigned mode,
587                         const char *path)
588 {
589         update_file_flags(o, sha, mode, path, o->call_depth || clean, !o->call_depth);
590 }
591
592 /* Low level file merging, update and removal */
593
594 struct merge_file_info
595 {
596         unsigned char sha[20];
597         unsigned mode;
598         unsigned clean:1,
599                  merge:1;
600 };
601
602 static int merge_3way(struct merge_options *o,
603                       mmbuffer_t *result_buf,
604                       struct diff_filespec *one,
605                       struct diff_filespec *a,
606                       struct diff_filespec *b,
607                       const char *branch1,
608                       const char *branch2)
609 {
610         mmfile_t orig, src1, src2;
611         struct ll_merge_options ll_opts = {0};
612         char *base_name, *name1, *name2;
613         int merge_status;
614
615         ll_opts.renormalize = o->renormalize;
616         ll_opts.xdl_opts = o->xdl_opts;
617
618         if (o->call_depth) {
619                 ll_opts.virtual_ancestor = 1;
620                 ll_opts.variant = 0;
621         } else {
622                 switch (o->recursive_variant) {
623                 case MERGE_RECURSIVE_OURS:
624                         ll_opts.variant = XDL_MERGE_FAVOR_OURS;
625                         break;
626                 case MERGE_RECURSIVE_THEIRS:
627                         ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
628                         break;
629                 default:
630                         ll_opts.variant = 0;
631                         break;
632                 }
633         }
634
635         if (strcmp(a->path, b->path) ||
636             (o->ancestor != NULL && strcmp(a->path, one->path) != 0)) {
637                 base_name = o->ancestor == NULL ? NULL :
638                         xstrdup(mkpath("%s:%s", o->ancestor, one->path));
639                 name1 = xstrdup(mkpath("%s:%s", branch1, a->path));
640                 name2 = xstrdup(mkpath("%s:%s", branch2, b->path));
641         } else {
642                 base_name = o->ancestor == NULL ? NULL :
643                         xstrdup(mkpath("%s", o->ancestor));
644                 name1 = xstrdup(mkpath("%s", branch1));
645                 name2 = xstrdup(mkpath("%s", branch2));
646         }
647
648         read_mmblob(&orig, one->sha1);
649         read_mmblob(&src1, a->sha1);
650         read_mmblob(&src2, b->sha1);
651
652         merge_status = ll_merge(result_buf, a->path, &orig, base_name,
653                                 &src1, name1, &src2, name2, &ll_opts);
654
655         free(name1);
656         free(name2);
657         free(orig.ptr);
658         free(src1.ptr);
659         free(src2.ptr);
660         return merge_status;
661 }
662
663 static struct merge_file_info merge_file(struct merge_options *o,
664                                          struct diff_filespec *one,
665                                          struct diff_filespec *a,
666                                          struct diff_filespec *b,
667                                          const char *branch1,
668                                          const char *branch2)
669 {
670         struct merge_file_info result;
671         result.merge = 0;
672         result.clean = 1;
673
674         if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
675                 result.clean = 0;
676                 if (S_ISREG(a->mode)) {
677                         result.mode = a->mode;
678                         hashcpy(result.sha, a->sha1);
679                 } else {
680                         result.mode = b->mode;
681                         hashcpy(result.sha, b->sha1);
682                 }
683         } else {
684                 if (!sha_eq(a->sha1, one->sha1) && !sha_eq(b->sha1, one->sha1))
685                         result.merge = 1;
686
687                 /*
688                  * Merge modes
689                  */
690                 if (a->mode == b->mode || a->mode == one->mode)
691                         result.mode = b->mode;
692                 else {
693                         result.mode = a->mode;
694                         if (b->mode != one->mode) {
695                                 result.clean = 0;
696                                 result.merge = 1;
697                         }
698                 }
699
700                 if (sha_eq(a->sha1, b->sha1) || sha_eq(a->sha1, one->sha1))
701                         hashcpy(result.sha, b->sha1);
702                 else if (sha_eq(b->sha1, one->sha1))
703                         hashcpy(result.sha, a->sha1);
704                 else if (S_ISREG(a->mode)) {
705                         mmbuffer_t result_buf;
706                         int merge_status;
707
708                         merge_status = merge_3way(o, &result_buf, one, a, b,
709                                                   branch1, branch2);
710
711                         if ((merge_status < 0) || !result_buf.ptr)
712                                 die("Failed to execute internal merge");
713
714                         if (write_sha1_file(result_buf.ptr, result_buf.size,
715                                             blob_type, result.sha))
716                                 die("Unable to add %s to database",
717                                     a->path);
718
719                         free(result_buf.ptr);
720                         result.clean = (merge_status == 0);
721                 } else if (S_ISGITLINK(a->mode)) {
722                         result.clean = 0;
723                         hashcpy(result.sha, a->sha1);
724                 } else if (S_ISLNK(a->mode)) {
725                         hashcpy(result.sha, a->sha1);
726
727                         if (!sha_eq(a->sha1, b->sha1))
728                                 result.clean = 0;
729                 } else {
730                         die("unsupported object type in the tree");
731                 }
732         }
733
734         return result;
735 }
736
737 static void conflict_rename_rename(struct merge_options *o,
738                                    struct rename *ren1,
739                                    const char *branch1,
740                                    struct rename *ren2,
741                                    const char *branch2)
742 {
743         char *del[2];
744         int delp = 0;
745         const char *ren1_dst = ren1->pair->two->path;
746         const char *ren2_dst = ren2->pair->two->path;
747         const char *dst_name1 = ren1_dst;
748         const char *dst_name2 = ren2_dst;
749         if (string_list_has_string(&o->current_directory_set, ren1_dst)) {
750                 dst_name1 = del[delp++] = unique_path(o, ren1_dst, branch1);
751                 output(o, 1, "%s is a directory in %s adding as %s instead",
752                        ren1_dst, branch2, dst_name1);
753                 remove_file(o, 0, ren1_dst, 0);
754         }
755         if (string_list_has_string(&o->current_directory_set, ren2_dst)) {
756                 dst_name2 = del[delp++] = unique_path(o, ren2_dst, branch2);
757                 output(o, 1, "%s is a directory in %s adding as %s instead",
758                        ren2_dst, branch1, dst_name2);
759                 remove_file(o, 0, ren2_dst, 0);
760         }
761         if (o->call_depth) {
762                 remove_file_from_cache(dst_name1);
763                 remove_file_from_cache(dst_name2);
764                 /*
765                  * Uncomment to leave the conflicting names in the resulting tree
766                  *
767                  * update_file(o, 0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1);
768                  * update_file(o, 0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2);
769                  */
770         } else {
771                 update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
772                 update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
773         }
774         while (delp--)
775                 free(del[delp]);
776 }
777
778 static void conflict_rename_dir(struct merge_options *o,
779                                 struct rename *ren1,
780                                 const char *branch1)
781 {
782         char *new_path = unique_path(o, ren1->pair->two->path, branch1);
783         output(o, 1, "Renaming %s to %s instead", ren1->pair->one->path, new_path);
784         remove_file(o, 0, ren1->pair->two->path, 0);
785         update_file(o, 0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
786         free(new_path);
787 }
788
789 static void conflict_rename_rename_2(struct merge_options *o,
790                                      struct rename *ren1,
791                                      const char *branch1,
792                                      struct rename *ren2,
793                                      const char *branch2)
794 {
795         char *new_path1 = unique_path(o, ren1->pair->two->path, branch1);
796         char *new_path2 = unique_path(o, ren2->pair->two->path, branch2);
797         output(o, 1, "Renaming %s to %s and %s to %s instead",
798                ren1->pair->one->path, new_path1,
799                ren2->pair->one->path, new_path2);
800         remove_file(o, 0, ren1->pair->two->path, 0);
801         update_file(o, 0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
802         update_file(o, 0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
803         free(new_path2);
804         free(new_path1);
805 }
806
807 static int process_renames(struct merge_options *o,
808                            struct string_list *a_renames,
809                            struct string_list *b_renames)
810 {
811         int clean_merge = 1, i, j;
812         struct string_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
813         const struct rename *sre;
814
815         for (i = 0; i < a_renames->nr; i++) {
816                 sre = a_renames->items[i].util;
817                 string_list_insert(sre->pair->two->path, &a_by_dst)->util
818                         = sre->dst_entry;
819         }
820         for (i = 0; i < b_renames->nr; i++) {
821                 sre = b_renames->items[i].util;
822                 string_list_insert(sre->pair->two->path, &b_by_dst)->util
823                         = sre->dst_entry;
824         }
825
826         for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
827                 char *src;
828                 struct string_list *renames1, *renames2Dst;
829                 struct rename *ren1 = NULL, *ren2 = NULL;
830                 const char *branch1, *branch2;
831                 const char *ren1_src, *ren1_dst;
832
833                 if (i >= a_renames->nr) {
834                         ren2 = b_renames->items[j++].util;
835                 } else if (j >= b_renames->nr) {
836                         ren1 = a_renames->items[i++].util;
837                 } else {
838                         int compare = strcmp(a_renames->items[i].string,
839                                              b_renames->items[j].string);
840                         if (compare <= 0)
841                                 ren1 = a_renames->items[i++].util;
842                         if (compare >= 0)
843                                 ren2 = b_renames->items[j++].util;
844                 }
845
846                 /* TODO: refactor, so that 1/2 are not needed */
847                 if (ren1) {
848                         renames1 = a_renames;
849                         renames2Dst = &b_by_dst;
850                         branch1 = o->branch1;
851                         branch2 = o->branch2;
852                 } else {
853                         struct rename *tmp;
854                         renames1 = b_renames;
855                         renames2Dst = &a_by_dst;
856                         branch1 = o->branch2;
857                         branch2 = o->branch1;
858                         tmp = ren2;
859                         ren2 = ren1;
860                         ren1 = tmp;
861                 }
862                 src = ren1->pair->one->path;
863
864                 ren1->dst_entry->processed = 1;
865                 ren1->src_entry->processed = 1;
866
867                 if (ren1->processed)
868                         continue;
869                 ren1->processed = 1;
870
871                 ren1_src = ren1->pair->one->path;
872                 ren1_dst = ren1->pair->two->path;
873
874                 if (ren2) {
875                         const char *ren2_src = ren2->pair->one->path;
876                         const char *ren2_dst = ren2->pair->two->path;
877                         /* Renamed in 1 and renamed in 2 */
878                         if (strcmp(ren1_src, ren2_src) != 0)
879                                 die("ren1.src != ren2.src");
880                         ren2->dst_entry->processed = 1;
881                         ren2->processed = 1;
882                         if (strcmp(ren1_dst, ren2_dst) != 0) {
883                                 clean_merge = 0;
884                                 output(o, 1, "CONFLICT (rename/rename): "
885                                        "Rename \"%s\"->\"%s\" in branch \"%s\" "
886                                        "rename \"%s\"->\"%s\" in \"%s\"%s",
887                                        src, ren1_dst, branch1,
888                                        src, ren2_dst, branch2,
889                                        o->call_depth ? " (left unresolved)": "");
890                                 if (o->call_depth) {
891                                         remove_file_from_cache(src);
892                                         update_file(o, 0, ren1->pair->one->sha1,
893                                                     ren1->pair->one->mode, src);
894                                 }
895                                 conflict_rename_rename(o, ren1, branch1, ren2, branch2);
896                         } else {
897                                 struct merge_file_info mfi;
898                                 remove_file(o, 1, ren1_src, 1);
899                                 mfi = merge_file(o,
900                                                  ren1->pair->one,
901                                                  ren1->pair->two,
902                                                  ren2->pair->two,
903                                                  branch1,
904                                                  branch2);
905                                 if (mfi.merge || !mfi.clean)
906                                         output(o, 1, "Renaming %s->%s", src, ren1_dst);
907
908                                 if (mfi.merge)
909                                         output(o, 2, "Auto-merging %s", ren1_dst);
910
911                                 if (!mfi.clean) {
912                                         output(o, 1, "CONFLICT (content): merge conflict in %s",
913                                                ren1_dst);
914                                         clean_merge = 0;
915
916                                         if (!o->call_depth)
917                                                 update_stages(ren1_dst,
918                                                               ren1->pair->one,
919                                                               ren1->pair->two,
920                                                               ren2->pair->two,
921                                                               1 /* clear */);
922                                 }
923                                 update_file(o, mfi.clean, mfi.sha, mfi.mode, ren1_dst);
924                         }
925                 } else {
926                         /* Renamed in 1, maybe changed in 2 */
927                         struct string_list_item *item;
928                         /* we only use sha1 and mode of these */
929                         struct diff_filespec src_other, dst_other;
930                         int try_merge, stage = a_renames == renames1 ? 3: 2;
931
932                         remove_file(o, 1, ren1_src, o->call_depth || stage == 3);
933
934                         hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
935                         src_other.mode = ren1->src_entry->stages[stage].mode;
936                         hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
937                         dst_other.mode = ren1->dst_entry->stages[stage].mode;
938
939                         try_merge = 0;
940
941                         if (string_list_has_string(&o->current_directory_set, ren1_dst)) {
942                                 clean_merge = 0;
943                                 output(o, 1, "CONFLICT (rename/directory): Rename %s->%s in %s "
944                                        " directory %s added in %s",
945                                        ren1_src, ren1_dst, branch1,
946                                        ren1_dst, branch2);
947                                 conflict_rename_dir(o, ren1, branch1);
948                         } else if (sha_eq(src_other.sha1, null_sha1)) {
949                                 clean_merge = 0;
950                                 output(o, 1, "CONFLICT (rename/delete): Rename %s->%s in %s "
951                                        "and deleted in %s",
952                                        ren1_src, ren1_dst, branch1,
953                                        branch2);
954                                 update_file(o, 0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
955                                 if (!o->call_depth)
956                                         update_stages(ren1_dst, NULL,
957                                                         branch1 == o->branch1 ?
958                                                         ren1->pair->two : NULL,
959                                                         branch1 == o->branch1 ?
960                                                         NULL : ren1->pair->two, 1);
961                         } else if (!sha_eq(dst_other.sha1, null_sha1)) {
962                                 const char *new_path;
963                                 clean_merge = 0;
964                                 try_merge = 1;
965                                 output(o, 1, "CONFLICT (rename/add): Rename %s->%s in %s. "
966                                        "%s added in %s",
967                                        ren1_src, ren1_dst, branch1,
968                                        ren1_dst, branch2);
969                                 if (o->call_depth) {
970                                         struct merge_file_info mfi;
971                                         struct diff_filespec one, a, b;
972
973                                         one.path = a.path = b.path =
974                                                 (char *)ren1_dst;
975                                         hashcpy(one.sha1, null_sha1);
976                                         one.mode = 0;
977                                         hashcpy(a.sha1, ren1->pair->two->sha1);
978                                         a.mode = ren1->pair->two->mode;
979                                         hashcpy(b.sha1, dst_other.sha1);
980                                         b.mode = dst_other.mode;
981                                         mfi = merge_file(o, &one, &a, &b,
982                                                          branch1,
983                                                          branch2);
984                                         output(o, 1, "Adding merged %s", ren1_dst);
985                                         update_file(o, 0,
986                                                     mfi.sha,
987                                                     mfi.mode,
988                                                     ren1_dst);
989                                 } else {
990                                         new_path = unique_path(o, ren1_dst, branch2);
991                                         output(o, 1, "Adding as %s instead", new_path);
992                                         update_file(o, 0, dst_other.sha1, dst_other.mode, new_path);
993                                 }
994                         } else if ((item = string_list_lookup(ren1_dst, renames2Dst))) {
995                                 ren2 = item->util;
996                                 clean_merge = 0;
997                                 ren2->processed = 1;
998                                 output(o, 1, "CONFLICT (rename/rename): "
999                                        "Rename %s->%s in %s. "
1000                                        "Rename %s->%s in %s",
1001                                        ren1_src, ren1_dst, branch1,
1002                                        ren2->pair->one->path, ren2->pair->two->path, branch2);
1003                                 conflict_rename_rename_2(o, ren1, branch1, ren2, branch2);
1004                         } else
1005                                 try_merge = 1;
1006
1007                         if (try_merge) {
1008                                 struct diff_filespec *one, *a, *b;
1009                                 struct merge_file_info mfi;
1010                                 src_other.path = (char *)ren1_src;
1011
1012                                 one = ren1->pair->one;
1013                                 if (a_renames == renames1) {
1014                                         a = ren1->pair->two;
1015                                         b = &src_other;
1016                                 } else {
1017                                         b = ren1->pair->two;
1018                                         a = &src_other;
1019                                 }
1020                                 mfi = merge_file(o, one, a, b,
1021                                                 o->branch1, o->branch2);
1022
1023                                 if (mfi.clean &&
1024                                     sha_eq(mfi.sha, ren1->pair->two->sha1) &&
1025                                     mfi.mode == ren1->pair->two->mode)
1026                                         /*
1027                                          * This messaged is part of
1028                                          * t6022 test. If you change
1029                                          * it update the test too.
1030                                          */
1031                                         output(o, 3, "Skipped %s (merged same as existing)", ren1_dst);
1032                                 else {
1033                                         if (mfi.merge || !mfi.clean)
1034                                                 output(o, 1, "Renaming %s => %s", ren1_src, ren1_dst);
1035                                         if (mfi.merge)
1036                                                 output(o, 2, "Auto-merging %s", ren1_dst);
1037                                         if (!mfi.clean) {
1038                                                 output(o, 1, "CONFLICT (rename/modify): Merge conflict in %s",
1039                                                        ren1_dst);
1040                                                 clean_merge = 0;
1041
1042                                                 if (!o->call_depth)
1043                                                         update_stages(ren1_dst,
1044                                                                       one, a, b, 1);
1045                                         }
1046                                         update_file(o, mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1047                                 }
1048                         }
1049                 }
1050         }
1051         string_list_clear(&a_by_dst, 0);
1052         string_list_clear(&b_by_dst, 0);
1053
1054         return clean_merge;
1055 }
1056
1057 static unsigned char *stage_sha(const unsigned char *sha, unsigned mode)
1058 {
1059         return (is_null_sha1(sha) || mode == 0) ? NULL: (unsigned char *)sha;
1060 }
1061
1062 static int read_sha1_strbuf(const unsigned char *sha1, struct strbuf *dst)
1063 {
1064         void *buf;
1065         enum object_type type;
1066         unsigned long size;
1067         buf = read_sha1_file(sha1, &type, &size);
1068         if (!buf)
1069                 return error("cannot read object %s", sha1_to_hex(sha1));
1070         if (type != OBJ_BLOB) {
1071                 free(buf);
1072                 return error("object %s is not a blob", sha1_to_hex(sha1));
1073         }
1074         strbuf_attach(dst, buf, size, size + 1);
1075         return 0;
1076 }
1077
1078 static int blob_unchanged(const unsigned char *o_sha,
1079                           const unsigned char *a_sha,
1080                           int renormalize, const char *path)
1081 {
1082         struct strbuf o = STRBUF_INIT;
1083         struct strbuf a = STRBUF_INIT;
1084         int ret = 0; /* assume changed for safety */
1085
1086         if (sha_eq(o_sha, a_sha))
1087                 return 1;
1088         if (!renormalize)
1089                 return 0;
1090
1091         assert(o_sha && a_sha);
1092         if (read_sha1_strbuf(o_sha, &o) || read_sha1_strbuf(a_sha, &a))
1093                 goto error_return;
1094         /*
1095          * Note: binary | is used so that both renormalizations are
1096          * performed.  Comparison can be skipped if both files are
1097          * unchanged since their sha1s have already been compared.
1098          */
1099         if (renormalize_buffer(path, o.buf, o.len, &o) |
1100             renormalize_buffer(path, a.buf, o.len, &a))
1101                 ret = (o.len == a.len && !memcmp(o.buf, a.buf, o.len));
1102
1103 error_return:
1104         strbuf_release(&o);
1105         strbuf_release(&a);
1106         return ret;
1107 }
1108
1109 /* Per entry merge function */
1110 static int process_entry(struct merge_options *o,
1111                          const char *path, struct stage_data *entry)
1112 {
1113         /*
1114         printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
1115         print_index_entry("\tpath: ", entry);
1116         */
1117         int clean_merge = 1;
1118         int normalize = o->renormalize;
1119         unsigned o_mode = entry->stages[1].mode;
1120         unsigned a_mode = entry->stages[2].mode;
1121         unsigned b_mode = entry->stages[3].mode;
1122         unsigned char *o_sha = stage_sha(entry->stages[1].sha, o_mode);
1123         unsigned char *a_sha = stage_sha(entry->stages[2].sha, a_mode);
1124         unsigned char *b_sha = stage_sha(entry->stages[3].sha, b_mode);
1125
1126         if (o_sha && (!a_sha || !b_sha)) {
1127                 /* Case A: Deleted in one */
1128                 if ((!a_sha && !b_sha) ||
1129                     (!b_sha && blob_unchanged(o_sha, a_sha, normalize, path)) ||
1130                     (!a_sha && blob_unchanged(o_sha, b_sha, normalize, path))) {
1131                         /* Deleted in both or deleted in one and
1132                          * unchanged in the other */
1133                         if (a_sha)
1134                                 output(o, 2, "Removing %s", path);
1135                         /* do not touch working file if it did not exist */
1136                         remove_file(o, 1, path, !a_sha);
1137                 } else {
1138                         /* Deleted in one and changed in the other */
1139                         clean_merge = 0;
1140                         if (!a_sha) {
1141                                 output(o, 1, "CONFLICT (delete/modify): %s deleted in %s "
1142                                        "and modified in %s. Version %s of %s left in tree.",
1143                                        path, o->branch1,
1144                                        o->branch2, o->branch2, path);
1145                                 update_file(o, 0, b_sha, b_mode, path);
1146                         } else {
1147                                 output(o, 1, "CONFLICT (delete/modify): %s deleted in %s "
1148                                        "and modified in %s. Version %s of %s left in tree.",
1149                                        path, o->branch2,
1150                                        o->branch1, o->branch1, path);
1151                                 update_file(o, 0, a_sha, a_mode, path);
1152                         }
1153                 }
1154
1155         } else if ((!o_sha && a_sha && !b_sha) ||
1156                    (!o_sha && !a_sha && b_sha)) {
1157                 /* Case B: Added in one. */
1158                 const char *add_branch;
1159                 const char *other_branch;
1160                 unsigned mode;
1161                 const unsigned char *sha;
1162                 const char *conf;
1163
1164                 if (a_sha) {
1165                         add_branch = o->branch1;
1166                         other_branch = o->branch2;
1167                         mode = a_mode;
1168                         sha = a_sha;
1169                         conf = "file/directory";
1170                 } else {
1171                         add_branch = o->branch2;
1172                         other_branch = o->branch1;
1173                         mode = b_mode;
1174                         sha = b_sha;
1175                         conf = "directory/file";
1176                 }
1177                 if (string_list_has_string(&o->current_directory_set, path)) {
1178                         const char *new_path = unique_path(o, path, add_branch);
1179                         clean_merge = 0;
1180                         output(o, 1, "CONFLICT (%s): There is a directory with name %s in %s. "
1181                                "Adding %s as %s",
1182                                conf, path, other_branch, path, new_path);
1183                         remove_file(o, 0, path, 0);
1184                         update_file(o, 0, sha, mode, new_path);
1185                 } else {
1186                         output(o, 2, "Adding %s", path);
1187                         update_file(o, 1, sha, mode, path);
1188                 }
1189         } else if (a_sha && b_sha) {
1190                 /* Case C: Added in both (check for same permissions) and */
1191                 /* case D: Modified in both, but differently. */
1192                 const char *reason = "content";
1193                 struct merge_file_info mfi;
1194                 struct diff_filespec one, a, b;
1195
1196                 if (!o_sha) {
1197                         reason = "add/add";
1198                         o_sha = (unsigned char *)null_sha1;
1199                 }
1200                 output(o, 2, "Auto-merging %s", path);
1201                 one.path = a.path = b.path = (char *)path;
1202                 hashcpy(one.sha1, o_sha);
1203                 one.mode = o_mode;
1204                 hashcpy(a.sha1, a_sha);
1205                 a.mode = a_mode;
1206                 hashcpy(b.sha1, b_sha);
1207                 b.mode = b_mode;
1208
1209                 mfi = merge_file(o, &one, &a, &b,
1210                                  o->branch1, o->branch2);
1211
1212                 clean_merge = mfi.clean;
1213                 if (!mfi.clean) {
1214                         if (S_ISGITLINK(mfi.mode))
1215                                 reason = "submodule";
1216                         output(o, 1, "CONFLICT (%s): Merge conflict in %s",
1217                                         reason, path);
1218                 }
1219                 update_file(o, mfi.clean, mfi.sha, mfi.mode, path);
1220         } else if (!o_sha && !a_sha && !b_sha) {
1221                 /*
1222                  * this entry was deleted altogether. a_mode == 0 means
1223                  * we had that path and want to actively remove it.
1224                  */
1225                 remove_file(o, 1, path, !a_mode);
1226         } else
1227                 die("Fatal merge failure, shouldn't happen.");
1228
1229         return clean_merge;
1230 }
1231
1232 struct unpack_trees_error_msgs get_porcelain_error_msgs(void)
1233 {
1234         struct unpack_trees_error_msgs msgs = {
1235                 /* would_overwrite */
1236                 "Your local changes to '%s' would be overwritten by merge.  Aborting.",
1237                 /* not_uptodate_file */
1238                 "Your local changes to '%s' would be overwritten by merge.  Aborting.",
1239                 /* not_uptodate_dir */
1240                 "Updating '%s' would lose untracked files in it.  Aborting.",
1241                 /* would_lose_untracked */
1242                 "Untracked working tree file '%s' would be %s by merge.  Aborting",
1243                 /* bind_overlap -- will not happen here */
1244                 NULL,
1245         };
1246         if (advice_commit_before_merge) {
1247                 msgs.would_overwrite = msgs.not_uptodate_file =
1248                         "Your local changes to '%s' would be overwritten by merge.  Aborting.\n"
1249                         "Please, commit your changes or stash them before you can merge.";
1250         }
1251         return msgs;
1252 }
1253
1254 int merge_trees(struct merge_options *o,
1255                 struct tree *head,
1256                 struct tree *merge,
1257                 struct tree *common,
1258                 struct tree **result)
1259 {
1260         int code, clean;
1261
1262         if (o->subtree_shift) {
1263                 merge = shift_tree_object(head, merge, o->subtree_shift);
1264                 common = shift_tree_object(head, common, o->subtree_shift);
1265         }
1266
1267         if (sha_eq(common->object.sha1, merge->object.sha1)) {
1268                 output(o, 0, "Already uptodate!");
1269                 *result = head;
1270                 return 1;
1271         }
1272
1273         code = git_merge_trees(o->call_depth, common, head, merge);
1274
1275         if (code != 0) {
1276                 if (show(o, 4) || o->call_depth)
1277                         die("merging of trees %s and %s failed",
1278                             sha1_to_hex(head->object.sha1),
1279                             sha1_to_hex(merge->object.sha1));
1280                 else
1281                         exit(128);
1282         }
1283
1284         if (unmerged_cache()) {
1285                 struct string_list *entries, *re_head, *re_merge;
1286                 int i;
1287                 string_list_clear(&o->current_file_set, 1);
1288                 string_list_clear(&o->current_directory_set, 1);
1289                 get_files_dirs(o, head);
1290                 get_files_dirs(o, merge);
1291
1292                 entries = get_unmerged();
1293                 re_head  = get_renames(o, head, common, head, merge, entries);
1294                 re_merge = get_renames(o, merge, common, head, merge, entries);
1295                 clean = process_renames(o, re_head, re_merge);
1296                 for (i = 0; i < entries->nr; i++) {
1297                         const char *path = entries->items[i].string;
1298                         struct stage_data *e = entries->items[i].util;
1299                         if (!e->processed
1300                                 && !process_entry(o, path, e))
1301                                 clean = 0;
1302                 }
1303
1304                 string_list_clear(re_merge, 0);
1305                 string_list_clear(re_head, 0);
1306                 string_list_clear(entries, 1);
1307
1308         }
1309         else
1310                 clean = 1;
1311
1312         if (o->call_depth)
1313                 *result = write_tree_from_memory(o);
1314
1315         return clean;
1316 }
1317
1318 static struct commit_list *reverse_commit_list(struct commit_list *list)
1319 {
1320         struct commit_list *next = NULL, *current, *backup;
1321         for (current = list; current; current = backup) {
1322                 backup = current->next;
1323                 current->next = next;
1324                 next = current;
1325         }
1326         return next;
1327 }
1328
1329 /*
1330  * Merge the commits h1 and h2, return the resulting virtual
1331  * commit object and a flag indicating the cleanness of the merge.
1332  */
1333 int merge_recursive(struct merge_options *o,
1334                     struct commit *h1,
1335                     struct commit *h2,
1336                     struct commit_list *ca,
1337                     struct commit **result)
1338 {
1339         struct commit_list *iter;
1340         struct commit *merged_common_ancestors;
1341         struct tree *mrtree = mrtree;
1342         int clean;
1343
1344         if (show(o, 4)) {
1345                 output(o, 4, "Merging:");
1346                 output_commit_title(o, h1);
1347                 output_commit_title(o, h2);
1348         }
1349
1350         if (!ca) {
1351                 ca = get_merge_bases(h1, h2, 1);
1352                 ca = reverse_commit_list(ca);
1353         }
1354
1355         if (show(o, 5)) {
1356                 output(o, 5, "found %u common ancestor(s):", commit_list_count(ca));
1357                 for (iter = ca; iter; iter = iter->next)
1358                         output_commit_title(o, iter->item);
1359         }
1360
1361         merged_common_ancestors = pop_commit(&ca);
1362         if (merged_common_ancestors == NULL) {
1363                 /* if there is no common ancestor, make an empty tree */
1364                 struct tree *tree = xcalloc(1, sizeof(struct tree));
1365
1366                 tree->object.parsed = 1;
1367                 tree->object.type = OBJ_TREE;
1368                 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
1369                 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1370         }
1371
1372         for (iter = ca; iter; iter = iter->next) {
1373                 const char *saved_b1, *saved_b2;
1374                 o->call_depth++;
1375                 /*
1376                  * When the merge fails, the result contains files
1377                  * with conflict markers. The cleanness flag is
1378                  * ignored, it was never actually used, as result of
1379                  * merge_trees has always overwritten it: the committed
1380                  * "conflicts" were already resolved.
1381                  */
1382                 discard_cache();
1383                 saved_b1 = o->branch1;
1384                 saved_b2 = o->branch2;
1385                 o->branch1 = "Temporary merge branch 1";
1386                 o->branch2 = "Temporary merge branch 2";
1387                 merge_recursive(o, merged_common_ancestors, iter->item,
1388                                 NULL, &merged_common_ancestors);
1389                 o->branch1 = saved_b1;
1390                 o->branch2 = saved_b2;
1391                 o->call_depth--;
1392
1393                 if (!merged_common_ancestors)
1394                         die("merge returned no commit");
1395         }
1396
1397         discard_cache();
1398         if (!o->call_depth)
1399                 read_cache();
1400
1401         o->ancestor = "merged common ancestors";
1402         clean = merge_trees(o, h1->tree, h2->tree, merged_common_ancestors->tree,
1403                             &mrtree);
1404
1405         if (o->call_depth) {
1406                 *result = make_virtual_commit(mrtree, "merged tree");
1407                 commit_list_insert(h1, &(*result)->parents);
1408                 commit_list_insert(h2, &(*result)->parents->next);
1409         }
1410         flush_output(o);
1411         return clean;
1412 }
1413
1414 static struct commit *get_ref(const unsigned char *sha1, const char *name)
1415 {
1416         struct object *object;
1417
1418         object = deref_tag(parse_object(sha1), name, strlen(name));
1419         if (!object)
1420                 return NULL;
1421         if (object->type == OBJ_TREE)
1422                 return make_virtual_commit((struct tree*)object, name);
1423         if (object->type != OBJ_COMMIT)
1424                 return NULL;
1425         if (parse_commit((struct commit *)object))
1426                 return NULL;
1427         return (struct commit *)object;
1428 }
1429
1430 int merge_recursive_generic(struct merge_options *o,
1431                             const unsigned char *head,
1432                             const unsigned char *merge,
1433                             int num_base_list,
1434                             const unsigned char **base_list,
1435                             struct commit **result)
1436 {
1437         int clean, index_fd;
1438         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
1439         struct commit *head_commit = get_ref(head, o->branch1);
1440         struct commit *next_commit = get_ref(merge, o->branch2);
1441         struct commit_list *ca = NULL;
1442
1443         if (base_list) {
1444                 int i;
1445                 for (i = 0; i < num_base_list; ++i) {
1446                         struct commit *base;
1447                         if (!(base = get_ref(base_list[i], sha1_to_hex(base_list[i]))))
1448                                 return error("Could not parse object '%s'",
1449                                         sha1_to_hex(base_list[i]));
1450                         commit_list_insert(base, &ca);
1451                 }
1452         }
1453
1454         index_fd = hold_locked_index(lock, 1);
1455         clean = merge_recursive(o, head_commit, next_commit, ca,
1456                         result);
1457         if (active_cache_changed &&
1458                         (write_cache(index_fd, active_cache, active_nr) ||
1459                          commit_locked_index(lock)))
1460                 return error("Unable to write index.");
1461
1462         return clean ? 0 : 1;
1463 }
1464
1465 static int merge_recursive_config(const char *var, const char *value, void *cb)
1466 {
1467         struct merge_options *o = cb;
1468         if (!strcasecmp(var, "merge.verbosity")) {
1469                 o->verbosity = git_config_int(var, value);
1470                 return 0;
1471         }
1472         if (!strcasecmp(var, "diff.renamelimit")) {
1473                 o->diff_rename_limit = git_config_int(var, value);
1474                 return 0;
1475         }
1476         if (!strcasecmp(var, "merge.renamelimit")) {
1477                 o->merge_rename_limit = git_config_int(var, value);
1478                 return 0;
1479         }
1480         return git_xmerge_config(var, value, cb);
1481 }
1482
1483 void init_merge_options(struct merge_options *o)
1484 {
1485         memset(o, 0, sizeof(struct merge_options));
1486         o->verbosity = 2;
1487         o->buffer_output = 1;
1488         o->diff_rename_limit = -1;
1489         o->merge_rename_limit = -1;
1490         o->renormalize = 0;
1491         git_config(merge_recursive_config, o);
1492         if (getenv("GIT_MERGE_VERBOSITY"))
1493                 o->verbosity =
1494                         strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
1495         if (o->verbosity >= 5)
1496                 o->buffer_output = 0;
1497         strbuf_init(&o->obuf, 0);
1498         memset(&o->current_file_set, 0, sizeof(struct string_list));
1499         o->current_file_set.strdup_strings = 1;
1500         memset(&o->current_directory_set, 0, sizeof(struct string_list));
1501         o->current_directory_set.strdup_strings = 1;
1502 }
1503
1504 int parse_merge_opt(struct merge_options *o, const char *s)
1505 {
1506         if (!s || !*s)
1507                 return -1;
1508         if (!strcmp(s, "ours"))
1509                 o->recursive_variant = MERGE_RECURSIVE_OURS;
1510         else if (!strcmp(s, "theirs"))
1511                 o->recursive_variant = MERGE_RECURSIVE_THEIRS;
1512         else if (!strcmp(s, "subtree"))
1513                 o->subtree_shift = "";
1514         else if (!prefixcmp(s, "subtree="))
1515                 o->subtree_shift = s + strlen("subtree=");
1516         else if (!strcmp(s, "patience"))
1517                 o->xdl_opts |= XDF_PATIENCE_DIFF;
1518         else if (!strcmp(s, "renormalize"))
1519                 o->renormalize = 1;
1520         else if (!strcmp(s, "no-renormalize"))
1521                 o->renormalize = 0;
1522         else
1523                 return -1;
1524         return 0;
1525 }