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