Merge branch 'maint'
[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 "cache-tree.h"
8 #include "commit.h"
9 #include "blob.h"
10 #include "tree-walk.h"
11 #include "diff.h"
12 #include "diffcore.h"
13 #include "run-command.h"
14 #include "tag.h"
15 #include "unpack-trees.h"
16 #include "path-list.h"
17 #include "xdiff-interface.h"
18 #include "interpolate.h"
19 #include "attr.h"
20
21 static int subtree_merge;
22
23 static struct tree *shift_tree_object(struct tree *one, struct tree *two)
24 {
25         unsigned char shifted[20];
26
27         /*
28          * NEEDSWORK: this limits the recursion depth to hardcoded
29          * value '2' to avoid excessive overhead.
30          */
31         shift_tree(one->object.sha1, two->object.sha1, shifted, 2);
32         if (!hashcmp(two->object.sha1, shifted))
33                 return two;
34         return lookup_tree(shifted);
35 }
36
37 /*
38  * A virtual commit has
39  * - (const char *)commit->util set to the name, and
40  * - *(int *)commit->object.sha1 set to the virtual id.
41  */
42
43 static unsigned commit_list_count(const struct commit_list *l)
44 {
45         unsigned c = 0;
46         for (; l; l = l->next )
47                 c++;
48         return c;
49 }
50
51 static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
52 {
53         struct commit *commit = xcalloc(1, sizeof(struct commit));
54         static unsigned virtual_id = 1;
55         commit->tree = tree;
56         commit->util = (void*)comment;
57         *(int*)commit->object.sha1 = virtual_id++;
58         /* avoid warnings */
59         commit->object.parsed = 1;
60         return commit;
61 }
62
63 /*
64  * Since we use get_tree_entry(), which does not put the read object into
65  * the object pool, we cannot rely on a == b.
66  */
67 static int sha_eq(const unsigned char *a, const unsigned char *b)
68 {
69         if (!a && !b)
70                 return 2;
71         return a && b && hashcmp(a, b) == 0;
72 }
73
74 /*
75  * Since we want to write the index eventually, we cannot reuse the index
76  * for these (temporary) data.
77  */
78 struct stage_data
79 {
80         struct
81         {
82                 unsigned mode;
83                 unsigned char sha[20];
84         } stages[4];
85         unsigned processed:1;
86 };
87
88 static struct path_list current_file_set = {NULL, 0, 0, 1};
89 static struct path_list current_directory_set = {NULL, 0, 0, 1};
90
91 static int call_depth = 0;
92 static int verbosity = 2;
93 static int rename_limit = -1;
94 static int buffer_output = 1;
95 static struct strbuf obuf = STRBUF_INIT;
96
97 static int show(int v)
98 {
99         return (!call_depth && verbosity >= v) || verbosity >= 5;
100 }
101
102 static void flush_output(void)
103 {
104         if (obuf.len) {
105                 fputs(obuf.buf, stdout);
106                 strbuf_reset(&obuf);
107         }
108 }
109
110 static void output(int v, const char *fmt, ...)
111 {
112         int len;
113         va_list ap;
114
115         if (!show(v))
116                 return;
117
118         strbuf_grow(&obuf, call_depth * 2 + 2);
119         memset(obuf.buf + obuf.len, ' ', call_depth * 2);
120         strbuf_setlen(&obuf, obuf.len + call_depth * 2);
121
122         va_start(ap, fmt);
123         len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap);
124         va_end(ap);
125
126         if (len < 0)
127                 len = 0;
128         if (len >= strbuf_avail(&obuf)) {
129                 strbuf_grow(&obuf, len + 2);
130                 va_start(ap, fmt);
131                 len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap);
132                 va_end(ap);
133                 if (len >= strbuf_avail(&obuf)) {
134                         die("this should not happen, your snprintf is broken");
135                 }
136         }
137         strbuf_setlen(&obuf, obuf.len + len);
138         strbuf_add(&obuf, "\n", 1);
139         if (!buffer_output)
140                 flush_output();
141 }
142
143 static void output_commit_title(struct commit *commit)
144 {
145         int i;
146         flush_output();
147         for (i = call_depth; i--;)
148                 fputs("  ", stdout);
149         if (commit->util)
150                 printf("virtual %s\n", (char *)commit->util);
151         else {
152                 printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
153                 if (parse_commit(commit) != 0)
154                         printf("(bad commit)\n");
155                 else {
156                         const char *s;
157                         int len;
158                         for (s = commit->buffer; *s; s++)
159                                 if (*s == '\n' && s[1] == '\n') {
160                                         s += 2;
161                                         break;
162                                 }
163                         for (len = 0; s[len] && '\n' != s[len]; len++)
164                                 ; /* do nothing */
165                         printf("%.*s\n", len, s);
166                 }
167         }
168 }
169
170 static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
171                 const char *path, int stage, int refresh, int options)
172 {
173         struct cache_entry *ce;
174         ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
175         if (!ce)
176                 return error("addinfo_cache failed for path '%s'", path);
177         return add_cache_entry(ce, options);
178 }
179
180 /*
181  * This is a global variable which is used in a number of places but
182  * only written to in the 'merge' function.
183  *
184  * index_only == 1    => Don't leave any non-stage 0 entries in the cache and
185  *                       don't update the working directory.
186  *               0    => Leave unmerged entries in the cache and update
187  *                       the working directory.
188  */
189 static int index_only = 0;
190
191 static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
192 {
193         parse_tree(tree);
194         init_tree_desc(desc, tree->buffer, tree->size);
195 }
196
197 static int git_merge_trees(int index_only,
198                            struct tree *common,
199                            struct tree *head,
200                            struct tree *merge)
201 {
202         int rc;
203         struct tree_desc t[3];
204         struct unpack_trees_options opts;
205
206         memset(&opts, 0, sizeof(opts));
207         if (index_only)
208                 opts.index_only = 1;
209         else
210                 opts.update = 1;
211         opts.merge = 1;
212         opts.head_idx = 2;
213         opts.fn = threeway_merge;
214
215         init_tree_desc_from_tree(t+0, common);
216         init_tree_desc_from_tree(t+1, head);
217         init_tree_desc_from_tree(t+2, merge);
218
219         rc = unpack_trees(3, t, &opts);
220         cache_tree_free(&active_cache_tree);
221         return rc;
222 }
223
224 static int unmerged_index(void)
225 {
226         int i;
227         for (i = 0; i < active_nr; i++) {
228                 struct cache_entry *ce = active_cache[i];
229                 if (ce_stage(ce))
230                         return 1;
231         }
232         return 0;
233 }
234
235 static struct tree *git_write_tree(void)
236 {
237         struct tree *result = NULL;
238
239         if (unmerged_index()) {
240                 int i;
241                 output(0, "There are unmerged index entries:");
242                 for (i = 0; i < active_nr; i++) {
243                         struct cache_entry *ce = active_cache[i];
244                         if (ce_stage(ce))
245                                 output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name);
246                 }
247                 return NULL;
248         }
249
250         if (!active_cache_tree)
251                 active_cache_tree = cache_tree();
252
253         if (!cache_tree_fully_valid(active_cache_tree) &&
254             cache_tree_update(active_cache_tree,
255                               active_cache, active_nr, 0, 0) < 0)
256                 die("error building trees");
257
258         result = lookup_tree(active_cache_tree->sha1);
259
260         return result;
261 }
262
263 static int save_files_dirs(const unsigned char *sha1,
264                 const char *base, int baselen, const char *path,
265                 unsigned int mode, int stage)
266 {
267         int len = strlen(path);
268         char *newpath = xmalloc(baselen + len + 1);
269         memcpy(newpath, base, baselen);
270         memcpy(newpath + baselen, path, len);
271         newpath[baselen + len] = '\0';
272
273         if (S_ISDIR(mode))
274                 path_list_insert(newpath, &current_directory_set);
275         else
276                 path_list_insert(newpath, &current_file_set);
277         free(newpath);
278
279         return READ_TREE_RECURSIVE;
280 }
281
282 static int get_files_dirs(struct tree *tree)
283 {
284         int n;
285         if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0)
286                 return 0;
287         n = current_file_set.nr + current_directory_set.nr;
288         return n;
289 }
290
291 /*
292  * Returns a index_entry instance which doesn't have to correspond to
293  * a real cache entry in Git's index.
294  */
295 static struct stage_data *insert_stage_data(const char *path,
296                 struct tree *o, struct tree *a, struct tree *b,
297                 struct path_list *entries)
298 {
299         struct path_list_item *item;
300         struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
301         get_tree_entry(o->object.sha1, path,
302                         e->stages[1].sha, &e->stages[1].mode);
303         get_tree_entry(a->object.sha1, path,
304                         e->stages[2].sha, &e->stages[2].mode);
305         get_tree_entry(b->object.sha1, path,
306                         e->stages[3].sha, &e->stages[3].mode);
307         item = path_list_insert(path, entries);
308         item->util = e;
309         return e;
310 }
311
312 /*
313  * Create a dictionary mapping file names to stage_data objects. The
314  * dictionary contains one entry for every path with a non-zero stage entry.
315  */
316 static struct path_list *get_unmerged(void)
317 {
318         struct path_list *unmerged = xcalloc(1, sizeof(struct path_list));
319         int i;
320
321         unmerged->strdup_paths = 1;
322
323         for (i = 0; i < active_nr; i++) {
324                 struct path_list_item *item;
325                 struct stage_data *e;
326                 struct cache_entry *ce = active_cache[i];
327                 if (!ce_stage(ce))
328                         continue;
329
330                 item = path_list_lookup(ce->name, unmerged);
331                 if (!item) {
332                         item = path_list_insert(ce->name, unmerged);
333                         item->util = xcalloc(1, sizeof(struct stage_data));
334                 }
335                 e = item->util;
336                 e->stages[ce_stage(ce)].mode = ntohl(ce->ce_mode);
337                 hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
338         }
339
340         return unmerged;
341 }
342
343 struct rename
344 {
345         struct diff_filepair *pair;
346         struct stage_data *src_entry;
347         struct stage_data *dst_entry;
348         unsigned processed:1;
349 };
350
351 /*
352  * Get information of all renames which occurred between 'o_tree' and
353  * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
354  * 'b_tree') to be able to associate the correct cache entries with
355  * the rename information. 'tree' is always equal to either a_tree or b_tree.
356  */
357 static struct path_list *get_renames(struct tree *tree,
358                                         struct tree *o_tree,
359                                         struct tree *a_tree,
360                                         struct tree *b_tree,
361                                         struct path_list *entries)
362 {
363         int i;
364         struct path_list *renames;
365         struct diff_options opts;
366
367         renames = xcalloc(1, sizeof(struct path_list));
368         diff_setup(&opts);
369         DIFF_OPT_SET(&opts, RECURSIVE);
370         opts.detect_rename = DIFF_DETECT_RENAME;
371         opts.rename_limit = rename_limit;
372         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
373         if (diff_setup_done(&opts) < 0)
374                 die("diff setup failed");
375         diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
376         diffcore_std(&opts);
377         for (i = 0; i < diff_queued_diff.nr; ++i) {
378                 struct path_list_item *item;
379                 struct rename *re;
380                 struct diff_filepair *pair = diff_queued_diff.queue[i];
381                 if (pair->status != 'R') {
382                         diff_free_filepair(pair);
383                         continue;
384                 }
385                 re = xmalloc(sizeof(*re));
386                 re->processed = 0;
387                 re->pair = pair;
388                 item = path_list_lookup(re->pair->one->path, entries);
389                 if (!item)
390                         re->src_entry = insert_stage_data(re->pair->one->path,
391                                         o_tree, a_tree, b_tree, entries);
392                 else
393                         re->src_entry = item->util;
394
395                 item = path_list_lookup(re->pair->two->path, entries);
396                 if (!item)
397                         re->dst_entry = insert_stage_data(re->pair->two->path,
398                                         o_tree, a_tree, b_tree, entries);
399                 else
400                         re->dst_entry = item->util;
401                 item = path_list_insert(pair->one->path, renames);
402                 item->util = re;
403         }
404         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
405         diff_queued_diff.nr = 0;
406         diff_flush(&opts);
407         return renames;
408 }
409
410 static int update_stages(const char *path, struct diff_filespec *o,
411                          struct diff_filespec *a, struct diff_filespec *b,
412                          int clear)
413 {
414         int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
415         if (clear)
416                 if (remove_file_from_cache(path))
417                         return -1;
418         if (o)
419                 if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
420                         return -1;
421         if (a)
422                 if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
423                         return -1;
424         if (b)
425                 if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
426                         return -1;
427         return 0;
428 }
429
430 static int remove_path(const char *name)
431 {
432         int ret;
433         char *slash, *dirs;
434
435         ret = unlink(name);
436         if (ret)
437                 return ret;
438         dirs = xstrdup(name);
439         while ((slash = strrchr(name, '/'))) {
440                 *slash = '\0';
441                 if (rmdir(name) != 0)
442                         break;
443         }
444         free(dirs);
445         return ret;
446 }
447
448 static int remove_file(int clean, const char *path, int no_wd)
449 {
450         int update_cache = index_only || clean;
451         int update_working_directory = !index_only && !no_wd;
452
453         if (update_cache) {
454                 if (remove_file_from_cache(path))
455                         return -1;
456         }
457         if (update_working_directory) {
458                 unlink(path);
459                 if (errno != ENOENT || errno != EISDIR)
460                         return -1;
461                 remove_path(path);
462         }
463         return 0;
464 }
465
466 static char *unique_path(const char *path, const char *branch)
467 {
468         char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
469         int suffix = 0;
470         struct stat st;
471         char *p = newpath + strlen(path);
472         strcpy(newpath, path);
473         *(p++) = '~';
474         strcpy(p, branch);
475         for (; *p; ++p)
476                 if ('/' == *p)
477                         *p = '_';
478         while (path_list_has_path(&current_file_set, newpath) ||
479                path_list_has_path(&current_directory_set, newpath) ||
480                lstat(newpath, &st) == 0)
481                 sprintf(p, "_%d", suffix++);
482
483         path_list_insert(newpath, &current_file_set);
484         return newpath;
485 }
486
487 static int mkdir_p(const char *path, unsigned long mode)
488 {
489         /* path points to cache entries, so xstrdup before messing with it */
490         char *buf = xstrdup(path);
491         int result = safe_create_leading_directories(buf);
492         free(buf);
493         return result;
494 }
495
496 static void flush_buffer(int fd, const char *buf, unsigned long size)
497 {
498         while (size > 0) {
499                 long ret = write_in_full(fd, buf, size);
500                 if (ret < 0) {
501                         /* Ignore epipe */
502                         if (errno == EPIPE)
503                                 break;
504                         die("merge-recursive: %s", strerror(errno));
505                 } else if (!ret) {
506                         die("merge-recursive: disk full?");
507                 }
508                 size -= ret;
509                 buf += ret;
510         }
511 }
512
513 static int make_room_for_path(const char *path)
514 {
515         int status;
516         const char *msg = "failed to create path '%s'%s";
517
518         status = mkdir_p(path, 0777);
519         if (status) {
520                 if (status == -3) {
521                         /* something else exists */
522                         error(msg, path, ": perhaps a D/F conflict?");
523                         return -1;
524                 }
525                 die(msg, path, "");
526         }
527
528         /* Successful unlink is good.. */
529         if (!unlink(path))
530                 return 0;
531         /* .. and so is no existing file */
532         if (errno == ENOENT)
533                 return 0;
534         /* .. but not some other error (who really cares what?) */
535         return error(msg, path, ": perhaps a D/F conflict?");
536 }
537
538 static void update_file_flags(const unsigned char *sha,
539                               unsigned mode,
540                               const char *path,
541                               int update_cache,
542                               int update_wd)
543 {
544         if (index_only)
545                 update_wd = 0;
546
547         if (update_wd) {
548                 enum object_type type;
549                 void *buf;
550                 unsigned long size;
551
552                 buf = read_sha1_file(sha, &type, &size);
553                 if (!buf)
554                         die("cannot read object %s '%s'", sha1_to_hex(sha), path);
555                 if (type != OBJ_BLOB)
556                         die("blob expected for %s '%s'", sha1_to_hex(sha), path);
557
558                 if (make_room_for_path(path) < 0) {
559                         update_wd = 0;
560                         goto update_index;
561                 }
562                 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
563                         int fd;
564                         if (mode & 0100)
565                                 mode = 0777;
566                         else
567                                 mode = 0666;
568                         fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
569                         if (fd < 0)
570                                 die("failed to open %s: %s", path, strerror(errno));
571                         flush_buffer(fd, buf, size);
572                         close(fd);
573                 } else if (S_ISLNK(mode)) {
574                         char *lnk = xmemdupz(buf, size);
575                         mkdir_p(path, 0777);
576                         unlink(path);
577                         symlink(lnk, path);
578                         free(lnk);
579                 } else
580                         die("do not know what to do with %06o %s '%s'",
581                             mode, sha1_to_hex(sha), path);
582         }
583  update_index:
584         if (update_cache)
585                 add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
586 }
587
588 static void update_file(int clean,
589                         const unsigned char *sha,
590                         unsigned mode,
591                         const char *path)
592 {
593         update_file_flags(sha, mode, path, index_only || clean, !index_only);
594 }
595
596 /* Low level file merging, update and removal */
597
598 struct merge_file_info
599 {
600         unsigned char sha[20];
601         unsigned mode;
602         unsigned clean:1,
603                  merge:1;
604 };
605
606 static void fill_mm(const unsigned char *sha1, mmfile_t *mm)
607 {
608         unsigned long size;
609         enum object_type type;
610
611         if (!hashcmp(sha1, null_sha1)) {
612                 mm->ptr = xstrdup("");
613                 mm->size = 0;
614                 return;
615         }
616
617         mm->ptr = read_sha1_file(sha1, &type, &size);
618         if (!mm->ptr || type != OBJ_BLOB)
619                 die("unable to read blob object %s", sha1_to_hex(sha1));
620         mm->size = size;
621 }
622
623 /*
624  * Customizable low-level merge drivers support.
625  */
626
627 struct ll_merge_driver;
628 typedef int (*ll_merge_fn)(const struct ll_merge_driver *,
629                            const char *path,
630                            mmfile_t *orig,
631                            mmfile_t *src1, const char *name1,
632                            mmfile_t *src2, const char *name2,
633                            mmbuffer_t *result);
634
635 struct ll_merge_driver {
636         const char *name;
637         const char *description;
638         ll_merge_fn fn;
639         const char *recursive;
640         struct ll_merge_driver *next;
641         char *cmdline;
642 };
643
644 /*
645  * Built-in low-levels
646  */
647 static int ll_binary_merge(const struct ll_merge_driver *drv_unused,
648                            const char *path_unused,
649                            mmfile_t *orig,
650                            mmfile_t *src1, const char *name1,
651                            mmfile_t *src2, const char *name2,
652                            mmbuffer_t *result)
653 {
654         /*
655          * The tentative merge result is "ours" for the final round,
656          * or common ancestor for an internal merge.  Still return
657          * "conflicted merge" status.
658          */
659         mmfile_t *stolen = index_only ? orig : src1;
660
661         result->ptr = stolen->ptr;
662         result->size = stolen->size;
663         stolen->ptr = NULL;
664         return 1;
665 }
666
667 static int ll_xdl_merge(const struct ll_merge_driver *drv_unused,
668                         const char *path_unused,
669                         mmfile_t *orig,
670                         mmfile_t *src1, const char *name1,
671                         mmfile_t *src2, const char *name2,
672                         mmbuffer_t *result)
673 {
674         xpparam_t xpp;
675
676         if (buffer_is_binary(orig->ptr, orig->size) ||
677             buffer_is_binary(src1->ptr, src1->size) ||
678             buffer_is_binary(src2->ptr, src2->size)) {
679                 warning("Cannot merge binary files: %s vs. %s\n",
680                         name1, name2);
681                 return ll_binary_merge(drv_unused, path_unused,
682                                        orig, src1, name1,
683                                        src2, name2,
684                                        result);
685         }
686
687         memset(&xpp, 0, sizeof(xpp));
688         return xdl_merge(orig,
689                          src1, name1,
690                          src2, name2,
691                          &xpp, XDL_MERGE_ZEALOUS,
692                          result);
693 }
694
695 static int ll_union_merge(const struct ll_merge_driver *drv_unused,
696                           const char *path_unused,
697                           mmfile_t *orig,
698                           mmfile_t *src1, const char *name1,
699                           mmfile_t *src2, const char *name2,
700                           mmbuffer_t *result)
701 {
702         char *src, *dst;
703         long size;
704         const int marker_size = 7;
705
706         int status = ll_xdl_merge(drv_unused, path_unused,
707                                   orig, src1, NULL, src2, NULL, result);
708         if (status <= 0)
709                 return status;
710         size = result->size;
711         src = dst = result->ptr;
712         while (size) {
713                 char ch;
714                 if ((marker_size < size) &&
715                     (*src == '<' || *src == '=' || *src == '>')) {
716                         int i;
717                         ch = *src;
718                         for (i = 0; i < marker_size; i++)
719                                 if (src[i] != ch)
720                                         goto not_a_marker;
721                         if (src[marker_size] != '\n')
722                                 goto not_a_marker;
723                         src += marker_size + 1;
724                         size -= marker_size + 1;
725                         continue;
726                 }
727         not_a_marker:
728                 do {
729                         ch = *src++;
730                         *dst++ = ch;
731                         size--;
732                 } while (ch != '\n' && size);
733         }
734         result->size = dst - result->ptr;
735         return 0;
736 }
737
738 #define LL_BINARY_MERGE 0
739 #define LL_TEXT_MERGE 1
740 #define LL_UNION_MERGE 2
741 static struct ll_merge_driver ll_merge_drv[] = {
742         { "binary", "built-in binary merge", ll_binary_merge },
743         { "text", "built-in 3-way text merge", ll_xdl_merge },
744         { "union", "built-in union merge", ll_union_merge },
745 };
746
747 static void create_temp(mmfile_t *src, char *path)
748 {
749         int fd;
750
751         strcpy(path, ".merge_file_XXXXXX");
752         fd = xmkstemp(path);
753         if (write_in_full(fd, src->ptr, src->size) != src->size)
754                 die("unable to write temp-file");
755         close(fd);
756 }
757
758 /*
759  * User defined low-level merge driver support.
760  */
761 static int ll_ext_merge(const struct ll_merge_driver *fn,
762                         const char *path,
763                         mmfile_t *orig,
764                         mmfile_t *src1, const char *name1,
765                         mmfile_t *src2, const char *name2,
766                         mmbuffer_t *result)
767 {
768         char temp[3][50];
769         char cmdbuf[2048];
770         struct interp table[] = {
771                 { "%O" },
772                 { "%A" },
773                 { "%B" },
774         };
775         struct child_process child;
776         const char *args[20];
777         int status, fd, i;
778         struct stat st;
779
780         if (fn->cmdline == NULL)
781                 die("custom merge driver %s lacks command line.", fn->name);
782
783         result->ptr = NULL;
784         result->size = 0;
785         create_temp(orig, temp[0]);
786         create_temp(src1, temp[1]);
787         create_temp(src2, temp[2]);
788
789         interp_set_entry(table, 0, temp[0]);
790         interp_set_entry(table, 1, temp[1]);
791         interp_set_entry(table, 2, temp[2]);
792
793         output(1, "merging %s using %s", path,
794                fn->description ? fn->description : fn->name);
795
796         interpolate(cmdbuf, sizeof(cmdbuf), fn->cmdline, table, 3);
797
798         memset(&child, 0, sizeof(child));
799         child.argv = args;
800         args[0] = "sh";
801         args[1] = "-c";
802         args[2] = cmdbuf;
803         args[3] = NULL;
804
805         status = run_command(&child);
806         if (status < -ERR_RUN_COMMAND_FORK)
807                 ; /* failure in run-command */
808         else
809                 status = -status;
810         fd = open(temp[1], O_RDONLY);
811         if (fd < 0)
812                 goto bad;
813         if (fstat(fd, &st))
814                 goto close_bad;
815         result->size = st.st_size;
816         result->ptr = xmalloc(result->size + 1);
817         if (read_in_full(fd, result->ptr, result->size) != result->size) {
818                 free(result->ptr);
819                 result->ptr = NULL;
820                 result->size = 0;
821         }
822  close_bad:
823         close(fd);
824  bad:
825         for (i = 0; i < 3; i++)
826                 unlink(temp[i]);
827         return status;
828 }
829
830 /*
831  * merge.default and merge.driver configuration items
832  */
833 static struct ll_merge_driver *ll_user_merge, **ll_user_merge_tail;
834 static const char *default_ll_merge;
835
836 static int read_merge_config(const char *var, const char *value)
837 {
838         struct ll_merge_driver *fn;
839         const char *ep, *name;
840         int namelen;
841
842         if (!strcmp(var, "merge.default")) {
843                 if (value)
844                         default_ll_merge = strdup(value);
845                 return 0;
846         }
847
848         /*
849          * We are not interested in anything but "merge.<name>.variable";
850          * especially, we do not want to look at variables such as
851          * "merge.summary", "merge.tool", and "merge.verbosity".
852          */
853         if (prefixcmp(var, "merge.") || (ep = strrchr(var, '.')) == var + 5)
854                 return 0;
855
856         /*
857          * Find existing one as we might be processing merge.<name>.var2
858          * after seeing merge.<name>.var1.
859          */
860         name = var + 6;
861         namelen = ep - name;
862         for (fn = ll_user_merge; fn; fn = fn->next)
863                 if (!strncmp(fn->name, name, namelen) && !fn->name[namelen])
864                         break;
865         if (!fn) {
866                 fn = xcalloc(1, sizeof(struct ll_merge_driver));
867                 fn->name = xmemdupz(name, namelen);
868                 fn->fn = ll_ext_merge;
869                 *ll_user_merge_tail = fn;
870                 ll_user_merge_tail = &(fn->next);
871         }
872
873         ep++;
874
875         if (!strcmp("name", ep)) {
876                 if (!value)
877                         return error("%s: lacks value", var);
878                 fn->description = strdup(value);
879                 return 0;
880         }
881
882         if (!strcmp("driver", ep)) {
883                 if (!value)
884                         return error("%s: lacks value", var);
885                 /*
886                  * merge.<name>.driver specifies the command line:
887                  *
888                  *      command-line
889                  *
890                  * The command-line will be interpolated with the following
891                  * tokens and is given to the shell:
892                  *
893                  *    %O - temporary file name for the merge base.
894                  *    %A - temporary file name for our version.
895                  *    %B - temporary file name for the other branches' version.
896                  *
897                  * The external merge driver should write the results in the
898                  * file named by %A, and signal that it has done with zero exit
899                  * status.
900                  */
901                 fn->cmdline = strdup(value);
902                 return 0;
903         }
904
905         if (!strcmp("recursive", ep)) {
906                 if (!value)
907                         return error("%s: lacks value", var);
908                 fn->recursive = strdup(value);
909                 return 0;
910         }
911
912         return 0;
913 }
914
915 static void initialize_ll_merge(void)
916 {
917         if (ll_user_merge_tail)
918                 return;
919         ll_user_merge_tail = &ll_user_merge;
920         git_config(read_merge_config);
921 }
922
923 static const struct ll_merge_driver *find_ll_merge_driver(const char *merge_attr)
924 {
925         struct ll_merge_driver *fn;
926         const char *name;
927         int i;
928
929         initialize_ll_merge();
930
931         if (ATTR_TRUE(merge_attr))
932                 return &ll_merge_drv[LL_TEXT_MERGE];
933         else if (ATTR_FALSE(merge_attr))
934                 return &ll_merge_drv[LL_BINARY_MERGE];
935         else if (ATTR_UNSET(merge_attr)) {
936                 if (!default_ll_merge)
937                         return &ll_merge_drv[LL_TEXT_MERGE];
938                 else
939                         name = default_ll_merge;
940         }
941         else
942                 name = merge_attr;
943
944         for (fn = ll_user_merge; fn; fn = fn->next)
945                 if (!strcmp(fn->name, name))
946                         return fn;
947
948         for (i = 0; i < ARRAY_SIZE(ll_merge_drv); i++)
949                 if (!strcmp(ll_merge_drv[i].name, name))
950                         return &ll_merge_drv[i];
951
952         /* default to the 3-way */
953         return &ll_merge_drv[LL_TEXT_MERGE];
954 }
955
956 static const char *git_path_check_merge(const char *path)
957 {
958         static struct git_attr_check attr_merge_check;
959
960         if (!attr_merge_check.attr)
961                 attr_merge_check.attr = git_attr("merge", 5);
962
963         if (git_checkattr(path, 1, &attr_merge_check))
964                 return NULL;
965         return attr_merge_check.value;
966 }
967
968 static int ll_merge(mmbuffer_t *result_buf,
969                     struct diff_filespec *o,
970                     struct diff_filespec *a,
971                     struct diff_filespec *b,
972                     const char *branch1,
973                     const char *branch2)
974 {
975         mmfile_t orig, src1, src2;
976         char *name1, *name2;
977         int merge_status;
978         const char *ll_driver_name;
979         const struct ll_merge_driver *driver;
980
981         name1 = xstrdup(mkpath("%s:%s", branch1, a->path));
982         name2 = xstrdup(mkpath("%s:%s", branch2, b->path));
983
984         fill_mm(o->sha1, &orig);
985         fill_mm(a->sha1, &src1);
986         fill_mm(b->sha1, &src2);
987
988         ll_driver_name = git_path_check_merge(a->path);
989         driver = find_ll_merge_driver(ll_driver_name);
990
991         if (index_only && driver->recursive)
992                 driver = find_ll_merge_driver(driver->recursive);
993         merge_status = driver->fn(driver, a->path,
994                                   &orig, &src1, name1, &src2, name2,
995                                   result_buf);
996
997         free(name1);
998         free(name2);
999         free(orig.ptr);
1000         free(src1.ptr);
1001         free(src2.ptr);
1002         return merge_status;
1003 }
1004
1005 static struct merge_file_info merge_file(struct diff_filespec *o,
1006                 struct diff_filespec *a, struct diff_filespec *b,
1007                 const char *branch1, const char *branch2)
1008 {
1009         struct merge_file_info result;
1010         result.merge = 0;
1011         result.clean = 1;
1012
1013         if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
1014                 result.clean = 0;
1015                 if (S_ISREG(a->mode)) {
1016                         result.mode = a->mode;
1017                         hashcpy(result.sha, a->sha1);
1018                 } else {
1019                         result.mode = b->mode;
1020                         hashcpy(result.sha, b->sha1);
1021                 }
1022         } else {
1023                 if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1))
1024                         result.merge = 1;
1025
1026                 result.mode = a->mode == o->mode ? b->mode: a->mode;
1027
1028                 if (sha_eq(a->sha1, o->sha1))
1029                         hashcpy(result.sha, b->sha1);
1030                 else if (sha_eq(b->sha1, o->sha1))
1031                         hashcpy(result.sha, a->sha1);
1032                 else if (S_ISREG(a->mode)) {
1033                         mmbuffer_t result_buf;
1034                         int merge_status;
1035
1036                         merge_status = ll_merge(&result_buf, o, a, b,
1037                                                 branch1, branch2);
1038
1039                         if ((merge_status < 0) || !result_buf.ptr)
1040                                 die("Failed to execute internal merge");
1041
1042                         if (write_sha1_file(result_buf.ptr, result_buf.size,
1043                                             blob_type, result.sha))
1044                                 die("Unable to add %s to database",
1045                                     a->path);
1046
1047                         free(result_buf.ptr);
1048                         result.clean = (merge_status == 0);
1049                 } else {
1050                         if (!(S_ISLNK(a->mode) || S_ISLNK(b->mode)))
1051                                 die("cannot merge modes?");
1052
1053                         hashcpy(result.sha, a->sha1);
1054
1055                         if (!sha_eq(a->sha1, b->sha1))
1056                                 result.clean = 0;
1057                 }
1058         }
1059
1060         return result;
1061 }
1062
1063 static void conflict_rename_rename(struct rename *ren1,
1064                                    const char *branch1,
1065                                    struct rename *ren2,
1066                                    const char *branch2)
1067 {
1068         char *del[2];
1069         int delp = 0;
1070         const char *ren1_dst = ren1->pair->two->path;
1071         const char *ren2_dst = ren2->pair->two->path;
1072         const char *dst_name1 = ren1_dst;
1073         const char *dst_name2 = ren2_dst;
1074         if (path_list_has_path(&current_directory_set, ren1_dst)) {
1075                 dst_name1 = del[delp++] = unique_path(ren1_dst, branch1);
1076                 output(1, "%s is a directory in %s added as %s instead",
1077                        ren1_dst, branch2, dst_name1);
1078                 remove_file(0, ren1_dst, 0);
1079         }
1080         if (path_list_has_path(&current_directory_set, ren2_dst)) {
1081                 dst_name2 = del[delp++] = unique_path(ren2_dst, branch2);
1082                 output(1, "%s is a directory in %s added as %s instead",
1083                        ren2_dst, branch1, dst_name2);
1084                 remove_file(0, ren2_dst, 0);
1085         }
1086         if (index_only) {
1087                 remove_file_from_cache(dst_name1);
1088                 remove_file_from_cache(dst_name2);
1089                 /*
1090                  * Uncomment to leave the conflicting names in the resulting tree
1091                  *
1092                  * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1);
1093                  * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2);
1094                  */
1095         } else {
1096                 update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
1097                 update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
1098         }
1099         while (delp--)
1100                 free(del[delp]);
1101 }
1102
1103 static void conflict_rename_dir(struct rename *ren1,
1104                                 const char *branch1)
1105 {
1106         char *new_path = unique_path(ren1->pair->two->path, branch1);
1107         output(1, "Renamed %s to %s instead", ren1->pair->one->path, new_path);
1108         remove_file(0, ren1->pair->two->path, 0);
1109         update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
1110         free(new_path);
1111 }
1112
1113 static void conflict_rename_rename_2(struct rename *ren1,
1114                                      const char *branch1,
1115                                      struct rename *ren2,
1116                                      const char *branch2)
1117 {
1118         char *new_path1 = unique_path(ren1->pair->two->path, branch1);
1119         char *new_path2 = unique_path(ren2->pair->two->path, branch2);
1120         output(1, "Renamed %s to %s and %s to %s instead",
1121                ren1->pair->one->path, new_path1,
1122                ren2->pair->one->path, new_path2);
1123         remove_file(0, ren1->pair->two->path, 0);
1124         update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
1125         update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
1126         free(new_path2);
1127         free(new_path1);
1128 }
1129
1130 static int process_renames(struct path_list *a_renames,
1131                            struct path_list *b_renames,
1132                            const char *a_branch,
1133                            const char *b_branch)
1134 {
1135         int clean_merge = 1, i, j;
1136         struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
1137         const struct rename *sre;
1138
1139         for (i = 0; i < a_renames->nr; i++) {
1140                 sre = a_renames->items[i].util;
1141                 path_list_insert(sre->pair->two->path, &a_by_dst)->util
1142                         = sre->dst_entry;
1143         }
1144         for (i = 0; i < b_renames->nr; i++) {
1145                 sre = b_renames->items[i].util;
1146                 path_list_insert(sre->pair->two->path, &b_by_dst)->util
1147                         = sre->dst_entry;
1148         }
1149
1150         for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
1151                 int compare;
1152                 char *src;
1153                 struct path_list *renames1, *renames2, *renames2Dst;
1154                 struct rename *ren1 = NULL, *ren2 = NULL;
1155                 const char *branch1, *branch2;
1156                 const char *ren1_src, *ren1_dst;
1157
1158                 if (i >= a_renames->nr) {
1159                         compare = 1;
1160                         ren2 = b_renames->items[j++].util;
1161                 } else if (j >= b_renames->nr) {
1162                         compare = -1;
1163                         ren1 = a_renames->items[i++].util;
1164                 } else {
1165                         compare = strcmp(a_renames->items[i].path,
1166                                         b_renames->items[j].path);
1167                         if (compare <= 0)
1168                                 ren1 = a_renames->items[i++].util;
1169                         if (compare >= 0)
1170                                 ren2 = b_renames->items[j++].util;
1171                 }
1172
1173                 /* TODO: refactor, so that 1/2 are not needed */
1174                 if (ren1) {
1175                         renames1 = a_renames;
1176                         renames2 = b_renames;
1177                         renames2Dst = &b_by_dst;
1178                         branch1 = a_branch;
1179                         branch2 = b_branch;
1180                 } else {
1181                         struct rename *tmp;
1182                         renames1 = b_renames;
1183                         renames2 = a_renames;
1184                         renames2Dst = &a_by_dst;
1185                         branch1 = b_branch;
1186                         branch2 = a_branch;
1187                         tmp = ren2;
1188                         ren2 = ren1;
1189                         ren1 = tmp;
1190                 }
1191                 src = ren1->pair->one->path;
1192
1193                 ren1->dst_entry->processed = 1;
1194                 ren1->src_entry->processed = 1;
1195
1196                 if (ren1->processed)
1197                         continue;
1198                 ren1->processed = 1;
1199
1200                 ren1_src = ren1->pair->one->path;
1201                 ren1_dst = ren1->pair->two->path;
1202
1203                 if (ren2) {
1204                         const char *ren2_src = ren2->pair->one->path;
1205                         const char *ren2_dst = ren2->pair->two->path;
1206                         /* Renamed in 1 and renamed in 2 */
1207                         if (strcmp(ren1_src, ren2_src) != 0)
1208                                 die("ren1.src != ren2.src");
1209                         ren2->dst_entry->processed = 1;
1210                         ren2->processed = 1;
1211                         if (strcmp(ren1_dst, ren2_dst) != 0) {
1212                                 clean_merge = 0;
1213                                 output(1, "CONFLICT (rename/rename): "
1214                                        "Rename \"%s\"->\"%s\" in branch \"%s\" "
1215                                        "rename \"%s\"->\"%s\" in \"%s\"%s",
1216                                        src, ren1_dst, branch1,
1217                                        src, ren2_dst, branch2,
1218                                        index_only ? " (left unresolved)": "");
1219                                 if (index_only) {
1220                                         remove_file_from_cache(src);
1221                                         update_file(0, ren1->pair->one->sha1,
1222                                                     ren1->pair->one->mode, src);
1223                                 }
1224                                 conflict_rename_rename(ren1, branch1, ren2, branch2);
1225                         } else {
1226                                 struct merge_file_info mfi;
1227                                 remove_file(1, ren1_src, 1);
1228                                 mfi = merge_file(ren1->pair->one,
1229                                                  ren1->pair->two,
1230                                                  ren2->pair->two,
1231                                                  branch1,
1232                                                  branch2);
1233                                 if (mfi.merge || !mfi.clean)
1234                                         output(1, "Renamed %s->%s", src, ren1_dst);
1235
1236                                 if (mfi.merge)
1237                                         output(2, "Auto-merged %s", ren1_dst);
1238
1239                                 if (!mfi.clean) {
1240                                         output(1, "CONFLICT (content): merge conflict in %s",
1241                                                ren1_dst);
1242                                         clean_merge = 0;
1243
1244                                         if (!index_only)
1245                                                 update_stages(ren1_dst,
1246                                                               ren1->pair->one,
1247                                                               ren1->pair->two,
1248                                                               ren2->pair->two,
1249                                                               1 /* clear */);
1250                                 }
1251                                 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1252                         }
1253                 } else {
1254                         /* Renamed in 1, maybe changed in 2 */
1255                         struct path_list_item *item;
1256                         /* we only use sha1 and mode of these */
1257                         struct diff_filespec src_other, dst_other;
1258                         int try_merge, stage = a_renames == renames1 ? 3: 2;
1259
1260                         remove_file(1, ren1_src, index_only || stage == 3);
1261
1262                         hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
1263                         src_other.mode = ren1->src_entry->stages[stage].mode;
1264                         hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
1265                         dst_other.mode = ren1->dst_entry->stages[stage].mode;
1266
1267                         try_merge = 0;
1268
1269                         if (path_list_has_path(&current_directory_set, ren1_dst)) {
1270                                 clean_merge = 0;
1271                                 output(1, "CONFLICT (rename/directory): Renamed %s->%s in %s "
1272                                        " directory %s added in %s",
1273                                        ren1_src, ren1_dst, branch1,
1274                                        ren1_dst, branch2);
1275                                 conflict_rename_dir(ren1, branch1);
1276                         } else if (sha_eq(src_other.sha1, null_sha1)) {
1277                                 clean_merge = 0;
1278                                 output(1, "CONFLICT (rename/delete): Renamed %s->%s in %s "
1279                                        "and deleted in %s",
1280                                        ren1_src, ren1_dst, branch1,
1281                                        branch2);
1282                                 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
1283                         } else if (!sha_eq(dst_other.sha1, null_sha1)) {
1284                                 const char *new_path;
1285                                 clean_merge = 0;
1286                                 try_merge = 1;
1287                                 output(1, "CONFLICT (rename/add): Renamed %s->%s in %s. "
1288                                        "%s added in %s",
1289                                        ren1_src, ren1_dst, branch1,
1290                                        ren1_dst, branch2);
1291                                 new_path = unique_path(ren1_dst, branch2);
1292                                 output(1, "Added as %s instead", new_path);
1293                                 update_file(0, dst_other.sha1, dst_other.mode, new_path);
1294                         } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) {
1295                                 ren2 = item->util;
1296                                 clean_merge = 0;
1297                                 ren2->processed = 1;
1298                                 output(1, "CONFLICT (rename/rename): Renamed %s->%s in %s. "
1299                                        "Renamed %s->%s in %s",
1300                                        ren1_src, ren1_dst, branch1,
1301                                        ren2->pair->one->path, ren2->pair->two->path, branch2);
1302                                 conflict_rename_rename_2(ren1, branch1, ren2, branch2);
1303                         } else
1304                                 try_merge = 1;
1305
1306                         if (try_merge) {
1307                                 struct diff_filespec *o, *a, *b;
1308                                 struct merge_file_info mfi;
1309                                 src_other.path = (char *)ren1_src;
1310
1311                                 o = ren1->pair->one;
1312                                 if (a_renames == renames1) {
1313                                         a = ren1->pair->two;
1314                                         b = &src_other;
1315                                 } else {
1316                                         b = ren1->pair->two;
1317                                         a = &src_other;
1318                                 }
1319                                 mfi = merge_file(o, a, b,
1320                                                 a_branch, b_branch);
1321
1322                                 if (mfi.clean &&
1323                                     sha_eq(mfi.sha, ren1->pair->two->sha1) &&
1324                                     mfi.mode == ren1->pair->two->mode)
1325                                         /*
1326                                          * This messaged is part of
1327                                          * t6022 test. If you change
1328                                          * it update the test too.
1329                                          */
1330                                         output(3, "Skipped %s (merged same as existing)", ren1_dst);
1331                                 else {
1332                                         if (mfi.merge || !mfi.clean)
1333                                                 output(1, "Renamed %s => %s", ren1_src, ren1_dst);
1334                                         if (mfi.merge)
1335                                                 output(2, "Auto-merged %s", ren1_dst);
1336                                         if (!mfi.clean) {
1337                                                 output(1, "CONFLICT (rename/modify): Merge conflict in %s",
1338                                                        ren1_dst);
1339                                                 clean_merge = 0;
1340
1341                                                 if (!index_only)
1342                                                         update_stages(ren1_dst,
1343                                                                       o, a, b, 1);
1344                                         }
1345                                         update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1346                                 }
1347                         }
1348                 }
1349         }
1350         path_list_clear(&a_by_dst, 0);
1351         path_list_clear(&b_by_dst, 0);
1352
1353         return clean_merge;
1354 }
1355
1356 static unsigned char *stage_sha(const unsigned char *sha, unsigned mode)
1357 {
1358         return (is_null_sha1(sha) || mode == 0) ? NULL: (unsigned char *)sha;
1359 }
1360
1361 /* Per entry merge function */
1362 static int process_entry(const char *path, struct stage_data *entry,
1363                          const char *branch1,
1364                          const char *branch2)
1365 {
1366         /*
1367         printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
1368         print_index_entry("\tpath: ", entry);
1369         */
1370         int clean_merge = 1;
1371         unsigned o_mode = entry->stages[1].mode;
1372         unsigned a_mode = entry->stages[2].mode;
1373         unsigned b_mode = entry->stages[3].mode;
1374         unsigned char *o_sha = stage_sha(entry->stages[1].sha, o_mode);
1375         unsigned char *a_sha = stage_sha(entry->stages[2].sha, a_mode);
1376         unsigned char *b_sha = stage_sha(entry->stages[3].sha, b_mode);
1377
1378         if (o_sha && (!a_sha || !b_sha)) {
1379                 /* Case A: Deleted in one */
1380                 if ((!a_sha && !b_sha) ||
1381                     (sha_eq(a_sha, o_sha) && !b_sha) ||
1382                     (!a_sha && sha_eq(b_sha, o_sha))) {
1383                         /* Deleted in both or deleted in one and
1384                          * unchanged in the other */
1385                         if (a_sha)
1386                                 output(2, "Removed %s", path);
1387                         /* do not touch working file if it did not exist */
1388                         remove_file(1, path, !a_sha);
1389                 } else {
1390                         /* Deleted in one and changed in the other */
1391                         clean_merge = 0;
1392                         if (!a_sha) {
1393                                 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1394                                        "and modified in %s. Version %s of %s left in tree.",
1395                                        path, branch1,
1396                                        branch2, branch2, path);
1397                                 update_file(0, b_sha, b_mode, path);
1398                         } else {
1399                                 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1400                                        "and modified in %s. Version %s of %s left in tree.",
1401                                        path, branch2,
1402                                        branch1, branch1, path);
1403                                 update_file(0, a_sha, a_mode, path);
1404                         }
1405                 }
1406
1407         } else if ((!o_sha && a_sha && !b_sha) ||
1408                    (!o_sha && !a_sha && b_sha)) {
1409                 /* Case B: Added in one. */
1410                 const char *add_branch;
1411                 const char *other_branch;
1412                 unsigned mode;
1413                 const unsigned char *sha;
1414                 const char *conf;
1415
1416                 if (a_sha) {
1417                         add_branch = branch1;
1418                         other_branch = branch2;
1419                         mode = a_mode;
1420                         sha = a_sha;
1421                         conf = "file/directory";
1422                 } else {
1423                         add_branch = branch2;
1424                         other_branch = branch1;
1425                         mode = b_mode;
1426                         sha = b_sha;
1427                         conf = "directory/file";
1428                 }
1429                 if (path_list_has_path(&current_directory_set, path)) {
1430                         const char *new_path = unique_path(path, add_branch);
1431                         clean_merge = 0;
1432                         output(1, "CONFLICT (%s): There is a directory with name %s in %s. "
1433                                "Added %s as %s",
1434                                conf, path, other_branch, path, new_path);
1435                         remove_file(0, path, 0);
1436                         update_file(0, sha, mode, new_path);
1437                 } else {
1438                         output(2, "Added %s", path);
1439                         update_file(1, sha, mode, path);
1440                 }
1441         } else if (a_sha && b_sha) {
1442                 /* Case C: Added in both (check for same permissions) and */
1443                 /* case D: Modified in both, but differently. */
1444                 const char *reason = "content";
1445                 struct merge_file_info mfi;
1446                 struct diff_filespec o, a, b;
1447
1448                 if (!o_sha) {
1449                         reason = "add/add";
1450                         o_sha = (unsigned char *)null_sha1;
1451                 }
1452                 output(2, "Auto-merged %s", path);
1453                 o.path = a.path = b.path = (char *)path;
1454                 hashcpy(o.sha1, o_sha);
1455                 o.mode = o_mode;
1456                 hashcpy(a.sha1, a_sha);
1457                 a.mode = a_mode;
1458                 hashcpy(b.sha1, b_sha);
1459                 b.mode = b_mode;
1460
1461                 mfi = merge_file(&o, &a, &b,
1462                                  branch1, branch2);
1463
1464                 if (mfi.clean)
1465                         update_file(1, mfi.sha, mfi.mode, path);
1466                 else {
1467                         clean_merge = 0;
1468                         output(1, "CONFLICT (%s): Merge conflict in %s",
1469                                         reason, path);
1470
1471                         if (index_only)
1472                                 update_file(0, mfi.sha, mfi.mode, path);
1473                         else
1474                                 update_file_flags(mfi.sha, mfi.mode, path,
1475                                               0 /* update_cache */, 1 /* update_working_directory */);
1476                 }
1477         } else if (!o_sha && !a_sha && !b_sha) {
1478                 /*
1479                  * this entry was deleted altogether. a_mode == 0 means
1480                  * we had that path and want to actively remove it.
1481                  */
1482                 remove_file(1, path, !a_mode);
1483         } else
1484                 die("Fatal merge failure, shouldn't happen.");
1485
1486         return clean_merge;
1487 }
1488
1489 static int merge_trees(struct tree *head,
1490                        struct tree *merge,
1491                        struct tree *common,
1492                        const char *branch1,
1493                        const char *branch2,
1494                        struct tree **result)
1495 {
1496         int code, clean;
1497
1498         if (subtree_merge) {
1499                 merge = shift_tree_object(head, merge);
1500                 common = shift_tree_object(head, common);
1501         }
1502
1503         if (sha_eq(common->object.sha1, merge->object.sha1)) {
1504                 output(0, "Already uptodate!");
1505                 *result = head;
1506                 return 1;
1507         }
1508
1509         code = git_merge_trees(index_only, common, head, merge);
1510
1511         if (code != 0)
1512                 die("merging of trees %s and %s failed",
1513                     sha1_to_hex(head->object.sha1),
1514                     sha1_to_hex(merge->object.sha1));
1515
1516         if (unmerged_index()) {
1517                 struct path_list *entries, *re_head, *re_merge;
1518                 int i;
1519                 path_list_clear(&current_file_set, 1);
1520                 path_list_clear(&current_directory_set, 1);
1521                 get_files_dirs(head);
1522                 get_files_dirs(merge);
1523
1524                 entries = get_unmerged();
1525                 re_head  = get_renames(head, common, head, merge, entries);
1526                 re_merge = get_renames(merge, common, head, merge, entries);
1527                 clean = process_renames(re_head, re_merge,
1528                                 branch1, branch2);
1529                 for (i = 0; i < entries->nr; i++) {
1530                         const char *path = entries->items[i].path;
1531                         struct stage_data *e = entries->items[i].util;
1532                         if (!e->processed
1533                                 && !process_entry(path, e, branch1, branch2))
1534                                 clean = 0;
1535                 }
1536
1537                 path_list_clear(re_merge, 0);
1538                 path_list_clear(re_head, 0);
1539                 path_list_clear(entries, 1);
1540
1541         }
1542         else
1543                 clean = 1;
1544
1545         if (index_only)
1546                 *result = git_write_tree();
1547
1548         return clean;
1549 }
1550
1551 static struct commit_list *reverse_commit_list(struct commit_list *list)
1552 {
1553         struct commit_list *next = NULL, *current, *backup;
1554         for (current = list; current; current = backup) {
1555                 backup = current->next;
1556                 current->next = next;
1557                 next = current;
1558         }
1559         return next;
1560 }
1561
1562 /*
1563  * Merge the commits h1 and h2, return the resulting virtual
1564  * commit object and a flag indicating the cleanness of the merge.
1565  */
1566 static int merge(struct commit *h1,
1567                  struct commit *h2,
1568                  const char *branch1,
1569                  const char *branch2,
1570                  struct commit_list *ca,
1571                  struct commit **result)
1572 {
1573         struct commit_list *iter;
1574         struct commit *merged_common_ancestors;
1575         struct tree *mrtree = mrtree;
1576         int clean;
1577
1578         if (show(4)) {
1579                 output(4, "Merging:");
1580                 output_commit_title(h1);
1581                 output_commit_title(h2);
1582         }
1583
1584         if (!ca) {
1585                 ca = get_merge_bases(h1, h2, 1);
1586                 ca = reverse_commit_list(ca);
1587         }
1588
1589         if (show(5)) {
1590                 output(5, "found %u common ancestor(s):", commit_list_count(ca));
1591                 for (iter = ca; iter; iter = iter->next)
1592                         output_commit_title(iter->item);
1593         }
1594
1595         merged_common_ancestors = pop_commit(&ca);
1596         if (merged_common_ancestors == NULL) {
1597                 /* if there is no common ancestor, make an empty tree */
1598                 struct tree *tree = xcalloc(1, sizeof(struct tree));
1599
1600                 tree->object.parsed = 1;
1601                 tree->object.type = OBJ_TREE;
1602                 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
1603                 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1604         }
1605
1606         for (iter = ca; iter; iter = iter->next) {
1607                 call_depth++;
1608                 /*
1609                  * When the merge fails, the result contains files
1610                  * with conflict markers. The cleanness flag is
1611                  * ignored, it was never actually used, as result of
1612                  * merge_trees has always overwritten it: the committed
1613                  * "conflicts" were already resolved.
1614                  */
1615                 discard_cache();
1616                 merge(merged_common_ancestors, iter->item,
1617                       "Temporary merge branch 1",
1618                       "Temporary merge branch 2",
1619                       NULL,
1620                       &merged_common_ancestors);
1621                 call_depth--;
1622
1623                 if (!merged_common_ancestors)
1624                         die("merge returned no commit");
1625         }
1626
1627         discard_cache();
1628         if (!call_depth) {
1629                 read_cache();
1630                 index_only = 0;
1631         } else
1632                 index_only = 1;
1633
1634         clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree,
1635                             branch1, branch2, &mrtree);
1636
1637         if (index_only) {
1638                 *result = make_virtual_commit(mrtree, "merged tree");
1639                 commit_list_insert(h1, &(*result)->parents);
1640                 commit_list_insert(h2, &(*result)->parents->next);
1641         }
1642         flush_output();
1643         return clean;
1644 }
1645
1646 static const char *better_branch_name(const char *branch)
1647 {
1648         static char githead_env[8 + 40 + 1];
1649         char *name;
1650
1651         if (strlen(branch) != 40)
1652                 return branch;
1653         sprintf(githead_env, "GITHEAD_%s", branch);
1654         name = getenv(githead_env);
1655         return name ? name : branch;
1656 }
1657
1658 static struct commit *get_ref(const char *ref)
1659 {
1660         unsigned char sha1[20];
1661         struct object *object;
1662
1663         if (get_sha1(ref, sha1))
1664                 die("Could not resolve ref '%s'", ref);
1665         object = deref_tag(parse_object(sha1), ref, strlen(ref));
1666         if (object->type == OBJ_TREE)
1667                 return make_virtual_commit((struct tree*)object,
1668                         better_branch_name(ref));
1669         if (object->type != OBJ_COMMIT)
1670                 return NULL;
1671         if (parse_commit((struct commit *)object))
1672                 die("Could not parse commit '%s'", sha1_to_hex(object->sha1));
1673         return (struct commit *)object;
1674 }
1675
1676 static int merge_config(const char *var, const char *value)
1677 {
1678         if (!strcasecmp(var, "merge.verbosity")) {
1679                 verbosity = git_config_int(var, value);
1680                 return 0;
1681         }
1682         if (!strcasecmp(var, "diff.renamelimit")) {
1683                 rename_limit = git_config_int(var, value);
1684                 return 0;
1685         }
1686         return git_default_config(var, value);
1687 }
1688
1689 int main(int argc, char *argv[])
1690 {
1691         static const char *bases[20];
1692         static unsigned bases_count = 0;
1693         int i, clean;
1694         const char *branch1, *branch2;
1695         struct commit *result, *h1, *h2;
1696         struct commit_list *ca = NULL;
1697         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
1698         int index_fd;
1699
1700         if (argv[0]) {
1701                 int namelen = strlen(argv[0]);
1702                 if (8 < namelen &&
1703                     !strcmp(argv[0] + namelen - 8, "-subtree"))
1704                         subtree_merge = 1;
1705         }
1706
1707         git_config(merge_config);
1708         if (getenv("GIT_MERGE_VERBOSITY"))
1709                 verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
1710
1711         if (argc < 4)
1712                 die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]);
1713
1714         for (i = 1; i < argc; ++i) {
1715                 if (!strcmp(argv[i], "--"))
1716                         break;
1717                 if (bases_count < sizeof(bases)/sizeof(*bases))
1718                         bases[bases_count++] = argv[i];
1719         }
1720         if (argc - i != 3) /* "--" "<head>" "<remote>" */
1721                 die("Not handling anything other than two heads merge.");
1722         if (verbosity >= 5)
1723                 buffer_output = 0;
1724
1725         branch1 = argv[++i];
1726         branch2 = argv[++i];
1727
1728         h1 = get_ref(branch1);
1729         h2 = get_ref(branch2);
1730
1731         branch1 = better_branch_name(branch1);
1732         branch2 = better_branch_name(branch2);
1733
1734         if (show(3))
1735                 printf("Merging %s with %s\n", branch1, branch2);
1736
1737         index_fd = hold_locked_index(lock, 1);
1738
1739         for (i = 0; i < bases_count; i++) {
1740                 struct commit *ancestor = get_ref(bases[i]);
1741                 ca = commit_list_insert(ancestor, &ca);
1742         }
1743         clean = merge(h1, h2, branch1, branch2, ca, &result);
1744
1745         if (active_cache_changed &&
1746             (write_cache(index_fd, active_cache, active_nr) ||
1747              close(index_fd) || commit_locked_index(lock)))
1748                         die ("unable to write %s", get_index_file());
1749
1750         return clean ? 0: 1;
1751 }