Code

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