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