2 * Recursive Merge algorithm stolen from git-merge-recursive.py by
4 * The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006
7 #include "cache-tree.h"
10 #include "tree-walk.h"
13 #include "run-command.h"
15 #include "unpack-trees.h"
16 #include "path-list.h"
17 #include "xdiff-interface.h"
18 #include "interpolate.h"
21 static int subtree_merge;
23 static struct tree *shift_tree_object(struct tree *one, struct tree *two)
25 unsigned char shifted[20];
28 * NEEDSWORK: this limits the recursion depth to hardcoded
29 * value '2' to avoid excessive overhead.
31 shift_tree(one->object.sha1, two->object.sha1, shifted, 2);
32 if (!hashcmp(two->object.sha1, shifted))
34 return lookup_tree(shifted);
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.
43 static unsigned commit_list_count(const struct commit_list *l)
46 for (; l; l = l->next )
51 static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
53 struct commit *commit = xcalloc(1, sizeof(struct commit));
54 static unsigned virtual_id = 1;
56 commit->util = (void*)comment;
57 *(int*)commit->object.sha1 = virtual_id++;
59 commit->object.parsed = 1;
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.
67 static int sha_eq(const unsigned char *a, const unsigned char *b)
71 return a && b && hashcmp(a, b) == 0;
75 * Since we want to write the index eventually, we cannot reuse the index
76 * for these (temporary) data.
83 unsigned char sha[20];
90 struct output_buffer *next;
94 static struct path_list current_file_set = {NULL, 0, 0, 1};
95 static struct path_list current_directory_set = {NULL, 0, 0, 1};
97 static int call_depth = 0;
98 static int verbosity = 2;
99 static int buffer_output = 1;
100 static struct output_buffer *output_list, *output_end;
102 static int show (int v)
104 return (!call_depth && verbosity >= v) || verbosity >= 5;
107 static void output(int v, const char *fmt, ...)
111 if (buffer_output && show(v)) {
112 struct output_buffer *b = xmalloc(sizeof(*b));
113 nfvasprintf(&b->str, fmt, args);
116 output_end->next = b;
120 } else if (show(v)) {
122 for (i = call_depth; i--;)
124 vfprintf(stdout, fmt, args);
130 static void flush_output(void)
132 struct output_buffer *b, *n;
133 for (b = output_list; b; b = n) {
135 for (i = call_depth; i--;)
137 fputs(b->str, stdout);
147 static void output_commit_title(struct commit *commit)
151 for (i = call_depth; i--;)
154 printf("virtual %s\n", (char *)commit->util);
156 printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
157 if (parse_commit(commit) != 0)
158 printf("(bad commit)\n");
162 for (s = commit->buffer; *s; s++)
163 if (*s == '\n' && s[1] == '\n') {
167 for (len = 0; s[len] && '\n' != s[len]; len++)
169 printf("%.*s\n", len, s);
174 static struct cache_entry *make_cache_entry(unsigned int mode,
175 const unsigned char *sha1, const char *path, int stage, int refresh)
178 struct cache_entry *ce;
180 if (!verify_path(path))
184 size = cache_entry_size(len);
185 ce = xcalloc(1, size);
187 hashcpy(ce->sha1, sha1);
188 memcpy(ce->name, path, len);
189 ce->ce_flags = create_ce_flags(len, stage);
190 ce->ce_mode = create_ce_mode(mode);
193 return refresh_cache_entry(ce, 0);
198 static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
199 const char *path, int stage, int refresh, int options)
201 struct cache_entry *ce;
202 ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
204 return error("addinfo_cache failed for path '%s'", path);
205 return add_cache_entry(ce, options);
209 * This is a global variable which is used in a number of places but
210 * only written to in the 'merge' function.
212 * index_only == 1 => Don't leave any non-stage 0 entries in the cache and
213 * don't update the working directory.
214 * 0 => Leave unmerged entries in the cache and update
215 * the working directory.
217 static int index_only = 0;
219 static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
222 init_tree_desc(desc, tree->buffer, tree->size);
225 static int git_merge_trees(int index_only,
231 struct tree_desc t[3];
232 struct unpack_trees_options opts;
234 memset(&opts, 0, sizeof(opts));
241 opts.fn = threeway_merge;
243 init_tree_desc_from_tree(t+0, common);
244 init_tree_desc_from_tree(t+1, head);
245 init_tree_desc_from_tree(t+2, merge);
247 rc = unpack_trees(3, t, &opts);
248 cache_tree_free(&active_cache_tree);
252 static int unmerged_index(void)
255 for (i = 0; i < active_nr; i++) {
256 struct cache_entry *ce = active_cache[i];
263 static struct tree *git_write_tree(void)
265 struct tree *result = NULL;
267 if (unmerged_index()) {
269 output(0, "There are unmerged index entries:");
270 for (i = 0; i < active_nr; i++) {
271 struct cache_entry *ce = active_cache[i];
273 output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name);
278 if (!active_cache_tree)
279 active_cache_tree = cache_tree();
281 if (!cache_tree_fully_valid(active_cache_tree) &&
282 cache_tree_update(active_cache_tree,
283 active_cache, active_nr, 0, 0) < 0)
284 die("error building trees");
286 result = lookup_tree(active_cache_tree->sha1);
291 static int save_files_dirs(const unsigned char *sha1,
292 const char *base, int baselen, const char *path,
293 unsigned int mode, int stage)
295 int len = strlen(path);
296 char *newpath = xmalloc(baselen + len + 1);
297 memcpy(newpath, base, baselen);
298 memcpy(newpath + baselen, path, len);
299 newpath[baselen + len] = '\0';
302 path_list_insert(newpath, ¤t_directory_set);
304 path_list_insert(newpath, ¤t_file_set);
307 return READ_TREE_RECURSIVE;
310 static int get_files_dirs(struct tree *tree)
313 if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0)
315 n = current_file_set.nr + current_directory_set.nr;
320 * Returns a index_entry instance which doesn't have to correspond to
321 * a real cache entry in Git's index.
323 static struct stage_data *insert_stage_data(const char *path,
324 struct tree *o, struct tree *a, struct tree *b,
325 struct path_list *entries)
327 struct path_list_item *item;
328 struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
329 get_tree_entry(o->object.sha1, path,
330 e->stages[1].sha, &e->stages[1].mode);
331 get_tree_entry(a->object.sha1, path,
332 e->stages[2].sha, &e->stages[2].mode);
333 get_tree_entry(b->object.sha1, path,
334 e->stages[3].sha, &e->stages[3].mode);
335 item = path_list_insert(path, entries);
341 * Create a dictionary mapping file names to stage_data objects. The
342 * dictionary contains one entry for every path with a non-zero stage entry.
344 static struct path_list *get_unmerged(void)
346 struct path_list *unmerged = xcalloc(1, sizeof(struct path_list));
349 unmerged->strdup_paths = 1;
351 for (i = 0; i < active_nr; i++) {
352 struct path_list_item *item;
353 struct stage_data *e;
354 struct cache_entry *ce = active_cache[i];
358 item = path_list_lookup(ce->name, unmerged);
360 item = path_list_insert(ce->name, unmerged);
361 item->util = xcalloc(1, sizeof(struct stage_data));
364 e->stages[ce_stage(ce)].mode = ntohl(ce->ce_mode);
365 hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
373 struct diff_filepair *pair;
374 struct stage_data *src_entry;
375 struct stage_data *dst_entry;
376 unsigned processed:1;
380 * Get information of all renames which occurred between 'o_tree' and
381 * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
382 * 'b_tree') to be able to associate the correct cache entries with
383 * the rename information. 'tree' is always equal to either a_tree or b_tree.
385 static struct path_list *get_renames(struct tree *tree,
389 struct path_list *entries)
392 struct path_list *renames;
393 struct diff_options opts;
395 renames = xcalloc(1, sizeof(struct path_list));
398 opts.detect_rename = DIFF_DETECT_RENAME;
399 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
400 if (diff_setup_done(&opts) < 0)
401 die("diff setup failed");
402 diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
404 for (i = 0; i < diff_queued_diff.nr; ++i) {
405 struct path_list_item *item;
407 struct diff_filepair *pair = diff_queued_diff.queue[i];
408 if (pair->status != 'R') {
409 diff_free_filepair(pair);
412 re = xmalloc(sizeof(*re));
415 item = path_list_lookup(re->pair->one->path, entries);
417 re->src_entry = insert_stage_data(re->pair->one->path,
418 o_tree, a_tree, b_tree, entries);
420 re->src_entry = item->util;
422 item = path_list_lookup(re->pair->two->path, entries);
424 re->dst_entry = insert_stage_data(re->pair->two->path,
425 o_tree, a_tree, b_tree, entries);
427 re->dst_entry = item->util;
428 item = path_list_insert(pair->one->path, renames);
431 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
432 diff_queued_diff.nr = 0;
437 static int update_stages(const char *path, struct diff_filespec *o,
438 struct diff_filespec *a, struct diff_filespec *b,
441 int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
443 if (remove_file_from_cache(path))
446 if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
449 if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
452 if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
457 static int remove_path(const char *name)
466 dirs = xmalloc(len+1);
467 memcpy(dirs, name, len);
469 while ((slash = strrchr(name, '/'))) {
472 if (rmdir(name) != 0)
479 static int remove_file(int clean, const char *path, int no_wd)
481 int update_cache = index_only || clean;
482 int update_working_directory = !index_only && !no_wd;
485 if (remove_file_from_cache(path))
488 if (update_working_directory) {
490 if (errno != ENOENT || errno != EISDIR)
497 static char *unique_path(const char *path, const char *branch)
499 char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
502 char *p = newpath + strlen(path);
503 strcpy(newpath, path);
509 while (path_list_has_path(¤t_file_set, newpath) ||
510 path_list_has_path(¤t_directory_set, newpath) ||
511 lstat(newpath, &st) == 0)
512 sprintf(p, "_%d", suffix++);
514 path_list_insert(newpath, ¤t_file_set);
518 static int mkdir_p(const char *path, unsigned long mode)
520 /* path points to cache entries, so xstrdup before messing with it */
521 char *buf = xstrdup(path);
522 int result = safe_create_leading_directories(buf);
527 static void flush_buffer(int fd, const char *buf, unsigned long size)
530 long ret = write_in_full(fd, buf, size);
535 die("merge-recursive: %s", strerror(errno));
537 die("merge-recursive: disk full?");
544 static int make_room_for_path(const char *path)
547 const char *msg = "failed to create path '%s'%s";
549 status = mkdir_p(path, 0777);
552 /* something else exists */
553 error(msg, path, ": perhaps a D/F conflict?");
559 /* Successful unlink is good.. */
562 /* .. and so is no existing file */
565 /* .. but not some other error (who really cares what?) */
566 return error(msg, path, ": perhaps a D/F conflict?");
569 static void update_file_flags(const unsigned char *sha,
579 enum object_type type;
583 buf = read_sha1_file(sha, &type, &size);
585 die("cannot read object %s '%s'", sha1_to_hex(sha), path);
586 if (type != OBJ_BLOB)
587 die("blob expected for %s '%s'", sha1_to_hex(sha), path);
589 if (make_room_for_path(path) < 0) {
593 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
599 fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
601 die("failed to open %s: %s", path, strerror(errno));
602 flush_buffer(fd, buf, size);
604 } else if (S_ISLNK(mode)) {
605 char *lnk = xmalloc(size + 1);
606 memcpy(lnk, buf, size);
613 die("do not know what to do with %06o %s '%s'",
614 mode, sha1_to_hex(sha), path);
618 add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
621 static void update_file(int clean,
622 const unsigned char *sha,
626 update_file_flags(sha, mode, path, index_only || clean, !index_only);
629 /* Low level file merging, update and removal */
631 struct merge_file_info
633 unsigned char sha[20];
639 static void fill_mm(const unsigned char *sha1, mmfile_t *mm)
642 enum object_type type;
644 if (!hashcmp(sha1, null_sha1)) {
645 mm->ptr = xstrdup("");
650 mm->ptr = read_sha1_file(sha1, &type, &size);
651 if (!mm->ptr || type != OBJ_BLOB)
652 die("unable to read blob object %s", sha1_to_hex(sha1));
657 * Customizable low-level merge drivers support.
660 struct ll_merge_driver;
661 typedef int (*ll_merge_fn)(const struct ll_merge_driver *,
664 mmfile_t *src1, const char *name1,
665 mmfile_t *src2, const char *name2,
668 struct ll_merge_driver {
670 const char *description;
672 const char *recursive;
673 struct ll_merge_driver *next;
678 * Built-in low-levels
680 static int ll_xdl_merge(const struct ll_merge_driver *drv_unused,
681 const char *path_unused,
683 mmfile_t *src1, const char *name1,
684 mmfile_t *src2, const char *name2,
689 if (buffer_is_binary(orig->ptr, orig->size) ||
690 buffer_is_binary(src1->ptr, src1->size) ||
691 buffer_is_binary(src2->ptr, src2->size))
692 return error("Cannot merge binary files: %s vs. %s\n",
695 memset(&xpp, 0, sizeof(xpp));
696 return xdl_merge(orig,
699 &xpp, XDL_MERGE_ZEALOUS,
703 static int ll_union_merge(const struct ll_merge_driver *drv_unused,
704 const char *path_unused,
706 mmfile_t *src1, const char *name1,
707 mmfile_t *src2, const char *name2,
712 const int marker_size = 7;
714 int status = ll_xdl_merge(drv_unused, path_unused,
715 orig, src1, NULL, src2, NULL, result);
719 src = dst = result->ptr;
722 if ((marker_size < size) &&
723 (*src == '<' || *src == '=' || *src == '>')) {
726 for (i = 0; i < marker_size; i++)
729 if (src[marker_size] != '\n')
731 src += marker_size + 1;
732 size -= marker_size + 1;
740 } while (ch != '\n' && size);
742 result->size = dst - result->ptr;
746 static int ll_binary_merge(const struct ll_merge_driver *drv_unused,
747 const char *path_unused,
749 mmfile_t *src1, const char *name1,
750 mmfile_t *src2, const char *name2,
754 * The tentative merge result is "ours" for the final round,
755 * or common ancestor for an internal merge. Still return
756 * "conflicted merge" status.
758 mmfile_t *stolen = index_only ? orig : src1;
760 result->ptr = stolen->ptr;
761 result->size = stolen->size;
766 #define LL_BINARY_MERGE 0
767 #define LL_TEXT_MERGE 1
768 #define LL_UNION_MERGE 2
769 static struct ll_merge_driver ll_merge_drv[] = {
770 { "binary", "built-in binary merge", ll_binary_merge },
771 { "text", "built-in 3-way text merge", ll_xdl_merge },
772 { "union", "built-in union merge", ll_union_merge },
775 static void create_temp(mmfile_t *src, char *path)
779 strcpy(path, ".merge_file_XXXXXX");
782 die("unable to create temp-file");
783 if (write_in_full(fd, src->ptr, src->size) != src->size)
784 die("unable to write temp-file");
789 * User defined low-level merge driver support.
791 static int ll_ext_merge(const struct ll_merge_driver *fn,
794 mmfile_t *src1, const char *name1,
795 mmfile_t *src2, const char *name2,
800 struct interp table[] = {
805 struct child_process child;
806 const char *args[20];
810 if (fn->cmdline == NULL)
811 die("custom merge driver %s lacks command line.", fn->name);
815 create_temp(orig, temp[0]);
816 create_temp(src1, temp[1]);
817 create_temp(src2, temp[2]);
819 interp_set_entry(table, 0, temp[0]);
820 interp_set_entry(table, 1, temp[1]);
821 interp_set_entry(table, 2, temp[2]);
823 output(1, "merging %s using %s", path,
824 fn->description ? fn->description : fn->name);
826 interpolate(cmdbuf, sizeof(cmdbuf), fn->cmdline, table, 3);
828 memset(&child, 0, sizeof(child));
835 status = run_command(&child);
836 if (status < -ERR_RUN_COMMAND_FORK)
837 ; /* failure in run-command */
840 fd = open(temp[1], O_RDONLY);
845 result->size = st.st_size;
846 result->ptr = xmalloc(result->size + 1);
847 if (read_in_full(fd, result->ptr, result->size) != result->size) {
855 for (i = 0; i < 3; i++)
861 * merge.default and merge.driver configuration items
863 static struct ll_merge_driver *ll_user_merge, **ll_user_merge_tail;
864 static const char *default_ll_merge;
866 static int read_merge_config(const char *var, const char *value)
868 struct ll_merge_driver *fn;
869 const char *ep, *name;
872 if (!strcmp(var, "merge.default")) {
874 default_ll_merge = strdup(value);
879 * We are not interested in anything but "merge.<name>.variable";
880 * especially, we do not want to look at variables such as
881 * "merge.summary", "merge.tool", and "merge.verbosity".
883 if (prefixcmp(var, "merge.") || (ep = strrchr(var, '.')) == var + 5)
887 * Find existing one as we might be processing merge.<name>.var2
888 * after seeing merge.<name>.var1.
892 for (fn = ll_user_merge; fn; fn = fn->next)
893 if (!strncmp(fn->name, name, namelen) && !fn->name[namelen])
897 fn = xcalloc(1, sizeof(struct ll_merge_driver));
898 namebuf = xmalloc(namelen + 1);
899 memcpy(namebuf, name, namelen);
900 namebuf[namelen] = 0;
902 fn->fn = ll_ext_merge;
904 *ll_user_merge_tail = fn;
905 ll_user_merge_tail = &(fn->next);
910 if (!strcmp("name", ep)) {
912 return error("%s: lacks value", var);
913 fn->description = strdup(value);
917 if (!strcmp("driver", ep)) {
919 return error("%s: lacks value", var);
921 * merge.<name>.driver specifies the command line:
925 * The command-line will be interpolated with the following
926 * tokens and is given to the shell:
928 * %O - temporary file name for the merge base.
929 * %A - temporary file name for our version.
930 * %B - temporary file name for the other branches' version.
932 * The external merge driver should write the results in the
933 * file named by %A, and signal that it has done with zero exit
936 fn->cmdline = strdup(value);
940 if (!strcmp("recursive", ep)) {
942 return error("%s: lacks value", var);
943 fn->recursive = strdup(value);
950 static void initialize_ll_merge(void)
952 if (ll_user_merge_tail)
954 ll_user_merge_tail = &ll_user_merge;
955 git_config(read_merge_config);
958 static const struct ll_merge_driver *find_ll_merge_driver(const char *merge_attr)
960 struct ll_merge_driver *fn;
964 initialize_ll_merge();
966 if (ATTR_TRUE(merge_attr))
967 return &ll_merge_drv[LL_TEXT_MERGE];
968 else if (ATTR_FALSE(merge_attr))
969 return &ll_merge_drv[LL_BINARY_MERGE];
970 else if (ATTR_UNSET(merge_attr)) {
971 if (!default_ll_merge)
972 return &ll_merge_drv[LL_TEXT_MERGE];
974 name = default_ll_merge;
979 for (fn = ll_user_merge; fn; fn = fn->next)
980 if (!strcmp(fn->name, name))
983 for (i = 0; i < ARRAY_SIZE(ll_merge_drv); i++)
984 if (!strcmp(ll_merge_drv[i].name, name))
985 return &ll_merge_drv[i];
987 /* default to the 3-way */
988 return &ll_merge_drv[LL_TEXT_MERGE];
991 static const char *git_path_check_merge(const char *path)
993 static struct git_attr_check attr_merge_check;
995 if (!attr_merge_check.attr)
996 attr_merge_check.attr = git_attr("merge", 5);
998 if (git_checkattr(path, 1, &attr_merge_check))
1000 return attr_merge_check.value;
1003 static int ll_merge(mmbuffer_t *result_buf,
1004 struct diff_filespec *o,
1005 struct diff_filespec *a,
1006 struct diff_filespec *b,
1007 const char *branch1,
1008 const char *branch2)
1010 mmfile_t orig, src1, src2;
1011 char *name1, *name2;
1013 const char *ll_driver_name;
1014 const struct ll_merge_driver *driver;
1016 name1 = xstrdup(mkpath("%s:%s", branch1, a->path));
1017 name2 = xstrdup(mkpath("%s:%s", branch2, b->path));
1019 fill_mm(o->sha1, &orig);
1020 fill_mm(a->sha1, &src1);
1021 fill_mm(b->sha1, &src2);
1023 ll_driver_name = git_path_check_merge(a->path);
1024 driver = find_ll_merge_driver(ll_driver_name);
1026 if (index_only && driver->recursive)
1027 driver = find_ll_merge_driver(driver->recursive);
1028 merge_status = driver->fn(driver, a->path,
1029 &orig, &src1, name1, &src2, name2,
1037 return merge_status;
1040 static struct merge_file_info merge_file(struct diff_filespec *o,
1041 struct diff_filespec *a, struct diff_filespec *b,
1042 const char *branch1, const char *branch2)
1044 struct merge_file_info result;
1048 if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
1050 if (S_ISREG(a->mode)) {
1051 result.mode = a->mode;
1052 hashcpy(result.sha, a->sha1);
1054 result.mode = b->mode;
1055 hashcpy(result.sha, b->sha1);
1058 if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1))
1061 result.mode = a->mode == o->mode ? b->mode: a->mode;
1063 if (sha_eq(a->sha1, o->sha1))
1064 hashcpy(result.sha, b->sha1);
1065 else if (sha_eq(b->sha1, o->sha1))
1066 hashcpy(result.sha, a->sha1);
1067 else if (S_ISREG(a->mode)) {
1068 mmbuffer_t result_buf;
1071 merge_status = ll_merge(&result_buf, o, a, b,
1074 if ((merge_status < 0) || !result_buf.ptr)
1075 die("Failed to execute internal merge");
1077 if (write_sha1_file(result_buf.ptr, result_buf.size,
1078 blob_type, result.sha))
1079 die("Unable to add %s to database",
1082 free(result_buf.ptr);
1083 result.clean = (merge_status == 0);
1085 if (!(S_ISLNK(a->mode) || S_ISLNK(b->mode)))
1086 die("cannot merge modes?");
1088 hashcpy(result.sha, a->sha1);
1090 if (!sha_eq(a->sha1, b->sha1))
1098 static void conflict_rename_rename(struct rename *ren1,
1099 const char *branch1,
1100 struct rename *ren2,
1101 const char *branch2)
1105 const char *ren1_dst = ren1->pair->two->path;
1106 const char *ren2_dst = ren2->pair->two->path;
1107 const char *dst_name1 = ren1_dst;
1108 const char *dst_name2 = ren2_dst;
1109 if (path_list_has_path(¤t_directory_set, ren1_dst)) {
1110 dst_name1 = del[delp++] = unique_path(ren1_dst, branch1);
1111 output(1, "%s is a directory in %s added as %s instead",
1112 ren1_dst, branch2, dst_name1);
1113 remove_file(0, ren1_dst, 0);
1115 if (path_list_has_path(¤t_directory_set, ren2_dst)) {
1116 dst_name2 = del[delp++] = unique_path(ren2_dst, branch2);
1117 output(1, "%s is a directory in %s added as %s instead",
1118 ren2_dst, branch1, dst_name2);
1119 remove_file(0, ren2_dst, 0);
1122 remove_file_from_cache(dst_name1);
1123 remove_file_from_cache(dst_name2);
1125 * Uncomment to leave the conflicting names in the resulting tree
1127 * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1);
1128 * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2);
1131 update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
1132 update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
1138 static void conflict_rename_dir(struct rename *ren1,
1139 const char *branch1)
1141 char *new_path = unique_path(ren1->pair->two->path, branch1);
1142 output(1, "Renamed %s to %s instead", ren1->pair->one->path, new_path);
1143 remove_file(0, ren1->pair->two->path, 0);
1144 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
1148 static void conflict_rename_rename_2(struct rename *ren1,
1149 const char *branch1,
1150 struct rename *ren2,
1151 const char *branch2)
1153 char *new_path1 = unique_path(ren1->pair->two->path, branch1);
1154 char *new_path2 = unique_path(ren2->pair->two->path, branch2);
1155 output(1, "Renamed %s to %s and %s to %s instead",
1156 ren1->pair->one->path, new_path1,
1157 ren2->pair->one->path, new_path2);
1158 remove_file(0, ren1->pair->two->path, 0);
1159 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
1160 update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
1165 static int process_renames(struct path_list *a_renames,
1166 struct path_list *b_renames,
1167 const char *a_branch,
1168 const char *b_branch)
1170 int clean_merge = 1, i, j;
1171 struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
1172 const struct rename *sre;
1174 for (i = 0; i < a_renames->nr; i++) {
1175 sre = a_renames->items[i].util;
1176 path_list_insert(sre->pair->two->path, &a_by_dst)->util
1179 for (i = 0; i < b_renames->nr; i++) {
1180 sre = b_renames->items[i].util;
1181 path_list_insert(sre->pair->two->path, &b_by_dst)->util
1185 for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
1188 struct path_list *renames1, *renames2, *renames2Dst;
1189 struct rename *ren1 = NULL, *ren2 = NULL;
1190 const char *branch1, *branch2;
1191 const char *ren1_src, *ren1_dst;
1193 if (i >= a_renames->nr) {
1195 ren2 = b_renames->items[j++].util;
1196 } else if (j >= b_renames->nr) {
1198 ren1 = a_renames->items[i++].util;
1200 compare = strcmp(a_renames->items[i].path,
1201 b_renames->items[j].path);
1203 ren1 = a_renames->items[i++].util;
1205 ren2 = b_renames->items[j++].util;
1208 /* TODO: refactor, so that 1/2 are not needed */
1210 renames1 = a_renames;
1211 renames2 = b_renames;
1212 renames2Dst = &b_by_dst;
1217 renames1 = b_renames;
1218 renames2 = a_renames;
1219 renames2Dst = &a_by_dst;
1226 src = ren1->pair->one->path;
1228 ren1->dst_entry->processed = 1;
1229 ren1->src_entry->processed = 1;
1231 if (ren1->processed)
1233 ren1->processed = 1;
1235 ren1_src = ren1->pair->one->path;
1236 ren1_dst = ren1->pair->two->path;
1239 const char *ren2_src = ren2->pair->one->path;
1240 const char *ren2_dst = ren2->pair->two->path;
1241 /* Renamed in 1 and renamed in 2 */
1242 if (strcmp(ren1_src, ren2_src) != 0)
1243 die("ren1.src != ren2.src");
1244 ren2->dst_entry->processed = 1;
1245 ren2->processed = 1;
1246 if (strcmp(ren1_dst, ren2_dst) != 0) {
1248 output(1, "CONFLICT (rename/rename): "
1249 "Rename \"%s\"->\"%s\" in branch \"%s\" "
1250 "rename \"%s\"->\"%s\" in \"%s\"%s",
1251 src, ren1_dst, branch1,
1252 src, ren2_dst, branch2,
1253 index_only ? " (left unresolved)": "");
1255 remove_file_from_cache(src);
1256 update_file(0, ren1->pair->one->sha1,
1257 ren1->pair->one->mode, src);
1259 conflict_rename_rename(ren1, branch1, ren2, branch2);
1261 struct merge_file_info mfi;
1262 remove_file(1, ren1_src, 1);
1263 mfi = merge_file(ren1->pair->one,
1268 if (mfi.merge || !mfi.clean)
1269 output(1, "Renamed %s->%s", src, ren1_dst);
1272 output(2, "Auto-merged %s", ren1_dst);
1275 output(1, "CONFLICT (content): merge conflict in %s",
1280 update_stages(ren1_dst,
1286 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1289 /* Renamed in 1, maybe changed in 2 */
1290 struct path_list_item *item;
1291 /* we only use sha1 and mode of these */
1292 struct diff_filespec src_other, dst_other;
1293 int try_merge, stage = a_renames == renames1 ? 3: 2;
1295 remove_file(1, ren1_src, index_only || stage == 3);
1297 hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
1298 src_other.mode = ren1->src_entry->stages[stage].mode;
1299 hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
1300 dst_other.mode = ren1->dst_entry->stages[stage].mode;
1304 if (path_list_has_path(¤t_directory_set, ren1_dst)) {
1306 output(1, "CONFLICT (rename/directory): Renamed %s->%s in %s "
1307 " directory %s added in %s",
1308 ren1_src, ren1_dst, branch1,
1310 conflict_rename_dir(ren1, branch1);
1311 } else if (sha_eq(src_other.sha1, null_sha1)) {
1313 output(1, "CONFLICT (rename/delete): Renamed %s->%s in %s "
1314 "and deleted in %s",
1315 ren1_src, ren1_dst, branch1,
1317 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
1318 } else if (!sha_eq(dst_other.sha1, null_sha1)) {
1319 const char *new_path;
1322 output(1, "CONFLICT (rename/add): Renamed %s->%s in %s. "
1324 ren1_src, ren1_dst, branch1,
1326 new_path = unique_path(ren1_dst, branch2);
1327 output(1, "Added as %s instead", new_path);
1328 update_file(0, dst_other.sha1, dst_other.mode, new_path);
1329 } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) {
1332 ren2->processed = 1;
1333 output(1, "CONFLICT (rename/rename): Renamed %s->%s in %s. "
1334 "Renamed %s->%s in %s",
1335 ren1_src, ren1_dst, branch1,
1336 ren2->pair->one->path, ren2->pair->two->path, branch2);
1337 conflict_rename_rename_2(ren1, branch1, ren2, branch2);
1342 struct diff_filespec *o, *a, *b;
1343 struct merge_file_info mfi;
1344 src_other.path = (char *)ren1_src;
1346 o = ren1->pair->one;
1347 if (a_renames == renames1) {
1348 a = ren1->pair->two;
1351 b = ren1->pair->two;
1354 mfi = merge_file(o, a, b,
1355 a_branch, b_branch);
1358 sha_eq(mfi.sha, ren1->pair->two->sha1) &&
1359 mfi.mode == ren1->pair->two->mode)
1361 * This messaged is part of
1362 * t6022 test. If you change
1363 * it update the test too.
1365 output(3, "Skipped %s (merged same as existing)", ren1_dst);
1367 if (mfi.merge || !mfi.clean)
1368 output(1, "Renamed %s => %s", ren1_src, ren1_dst);
1370 output(2, "Auto-merged %s", ren1_dst);
1372 output(1, "CONFLICT (rename/modify): Merge conflict in %s",
1377 update_stages(ren1_dst,
1380 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1385 path_list_clear(&a_by_dst, 0);
1386 path_list_clear(&b_by_dst, 0);
1391 static unsigned char *stage_sha(const unsigned char *sha, unsigned mode)
1393 return (is_null_sha1(sha) || mode == 0) ? NULL: (unsigned char *)sha;
1396 /* Per entry merge function */
1397 static int process_entry(const char *path, struct stage_data *entry,
1398 const char *branch1,
1399 const char *branch2)
1402 printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
1403 print_index_entry("\tpath: ", entry);
1405 int clean_merge = 1;
1406 unsigned o_mode = entry->stages[1].mode;
1407 unsigned a_mode = entry->stages[2].mode;
1408 unsigned b_mode = entry->stages[3].mode;
1409 unsigned char *o_sha = stage_sha(entry->stages[1].sha, o_mode);
1410 unsigned char *a_sha = stage_sha(entry->stages[2].sha, a_mode);
1411 unsigned char *b_sha = stage_sha(entry->stages[3].sha, b_mode);
1413 if (o_sha && (!a_sha || !b_sha)) {
1414 /* Case A: Deleted in one */
1415 if ((!a_sha && !b_sha) ||
1416 (sha_eq(a_sha, o_sha) && !b_sha) ||
1417 (!a_sha && sha_eq(b_sha, o_sha))) {
1418 /* Deleted in both or deleted in one and
1419 * unchanged in the other */
1421 output(2, "Removed %s", path);
1422 /* do not touch working file if it did not exist */
1423 remove_file(1, path, !a_sha);
1425 /* Deleted in one and changed in the other */
1428 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1429 "and modified in %s. Version %s of %s left in tree.",
1431 branch2, branch2, path);
1432 update_file(0, b_sha, b_mode, path);
1434 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1435 "and modified in %s. Version %s of %s left in tree.",
1437 branch1, branch1, path);
1438 update_file(0, a_sha, a_mode, path);
1442 } else if ((!o_sha && a_sha && !b_sha) ||
1443 (!o_sha && !a_sha && b_sha)) {
1444 /* Case B: Added in one. */
1445 const char *add_branch;
1446 const char *other_branch;
1448 const unsigned char *sha;
1452 add_branch = branch1;
1453 other_branch = branch2;
1456 conf = "file/directory";
1458 add_branch = branch2;
1459 other_branch = branch1;
1462 conf = "directory/file";
1464 if (path_list_has_path(¤t_directory_set, path)) {
1465 const char *new_path = unique_path(path, add_branch);
1467 output(1, "CONFLICT (%s): There is a directory with name %s in %s. "
1469 conf, path, other_branch, path, new_path);
1470 remove_file(0, path, 0);
1471 update_file(0, sha, mode, new_path);
1473 output(2, "Added %s", path);
1474 update_file(1, sha, mode, path);
1476 } else if (a_sha && b_sha) {
1477 /* Case C: Added in both (check for same permissions) and */
1478 /* case D: Modified in both, but differently. */
1479 const char *reason = "content";
1480 struct merge_file_info mfi;
1481 struct diff_filespec o, a, b;
1485 o_sha = (unsigned char *)null_sha1;
1487 output(2, "Auto-merged %s", path);
1488 o.path = a.path = b.path = (char *)path;
1489 hashcpy(o.sha1, o_sha);
1491 hashcpy(a.sha1, a_sha);
1493 hashcpy(b.sha1, b_sha);
1496 mfi = merge_file(&o, &a, &b,
1500 update_file(1, mfi.sha, mfi.mode, path);
1503 output(1, "CONFLICT (%s): Merge conflict in %s",
1507 update_file(0, mfi.sha, mfi.mode, path);
1509 update_file_flags(mfi.sha, mfi.mode, path,
1510 0 /* update_cache */, 1 /* update_working_directory */);
1512 } else if (!o_sha && !a_sha && !b_sha) {
1514 * this entry was deleted altogether. a_mode == 0 means
1515 * we had that path and want to actively remove it.
1517 remove_file(1, path, !a_mode);
1519 die("Fatal merge failure, shouldn't happen.");
1524 static int merge_trees(struct tree *head,
1526 struct tree *common,
1527 const char *branch1,
1528 const char *branch2,
1529 struct tree **result)
1533 if (subtree_merge) {
1534 merge = shift_tree_object(head, merge);
1535 common = shift_tree_object(head, common);
1538 if (sha_eq(common->object.sha1, merge->object.sha1)) {
1539 output(0, "Already uptodate!");
1544 code = git_merge_trees(index_only, common, head, merge);
1547 die("merging of trees %s and %s failed",
1548 sha1_to_hex(head->object.sha1),
1549 sha1_to_hex(merge->object.sha1));
1551 if (unmerged_index()) {
1552 struct path_list *entries, *re_head, *re_merge;
1554 path_list_clear(¤t_file_set, 1);
1555 path_list_clear(¤t_directory_set, 1);
1556 get_files_dirs(head);
1557 get_files_dirs(merge);
1559 entries = get_unmerged();
1560 re_head = get_renames(head, common, head, merge, entries);
1561 re_merge = get_renames(merge, common, head, merge, entries);
1562 clean = process_renames(re_head, re_merge,
1564 for (i = 0; i < entries->nr; i++) {
1565 const char *path = entries->items[i].path;
1566 struct stage_data *e = entries->items[i].util;
1568 && !process_entry(path, e, branch1, branch2))
1572 path_list_clear(re_merge, 0);
1573 path_list_clear(re_head, 0);
1574 path_list_clear(entries, 1);
1581 *result = git_write_tree();
1586 static struct commit_list *reverse_commit_list(struct commit_list *list)
1588 struct commit_list *next = NULL, *current, *backup;
1589 for (current = list; current; current = backup) {
1590 backup = current->next;
1591 current->next = next;
1598 * Merge the commits h1 and h2, return the resulting virtual
1599 * commit object and a flag indicating the cleanness of the merge.
1601 static int merge(struct commit *h1,
1603 const char *branch1,
1604 const char *branch2,
1605 struct commit_list *ca,
1606 struct commit **result)
1608 struct commit_list *iter;
1609 struct commit *merged_common_ancestors;
1610 struct tree *mrtree;
1614 output(4, "Merging:");
1615 output_commit_title(h1);
1616 output_commit_title(h2);
1620 ca = get_merge_bases(h1, h2, 1);
1621 ca = reverse_commit_list(ca);
1625 output(5, "found %u common ancestor(s):", commit_list_count(ca));
1626 for (iter = ca; iter; iter = iter->next)
1627 output_commit_title(iter->item);
1630 merged_common_ancestors = pop_commit(&ca);
1631 if (merged_common_ancestors == NULL) {
1632 /* if there is no common ancestor, make an empty tree */
1633 struct tree *tree = xcalloc(1, sizeof(struct tree));
1635 tree->object.parsed = 1;
1636 tree->object.type = OBJ_TREE;
1637 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
1638 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1641 for (iter = ca; iter; iter = iter->next) {
1644 * When the merge fails, the result contains files
1645 * with conflict markers. The cleanness flag is
1646 * ignored, it was never actually used, as result of
1647 * merge_trees has always overwritten it: the committed
1648 * "conflicts" were already resolved.
1651 merge(merged_common_ancestors, iter->item,
1652 "Temporary merge branch 1",
1653 "Temporary merge branch 2",
1655 &merged_common_ancestors);
1658 if (!merged_common_ancestors)
1659 die("merge returned no commit");
1669 clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree,
1670 branch1, branch2, &mrtree);
1673 *result = make_virtual_commit(mrtree, "merged tree");
1674 commit_list_insert(h1, &(*result)->parents);
1675 commit_list_insert(h2, &(*result)->parents->next);
1681 static const char *better_branch_name(const char *branch)
1683 static char githead_env[8 + 40 + 1];
1686 if (strlen(branch) != 40)
1688 sprintf(githead_env, "GITHEAD_%s", branch);
1689 name = getenv(githead_env);
1690 return name ? name : branch;
1693 static struct commit *get_ref(const char *ref)
1695 unsigned char sha1[20];
1696 struct object *object;
1698 if (get_sha1(ref, sha1))
1699 die("Could not resolve ref '%s'", ref);
1700 object = deref_tag(parse_object(sha1), ref, strlen(ref));
1701 if (object->type == OBJ_TREE)
1702 return make_virtual_commit((struct tree*)object,
1703 better_branch_name(ref));
1704 if (object->type != OBJ_COMMIT)
1706 if (parse_commit((struct commit *)object))
1707 die("Could not parse commit '%s'", sha1_to_hex(object->sha1));
1708 return (struct commit *)object;
1711 static int merge_config(const char *var, const char *value)
1713 if (!strcasecmp(var, "merge.verbosity")) {
1714 verbosity = git_config_int(var, value);
1717 return git_default_config(var, value);
1720 int main(int argc, char *argv[])
1722 static const char *bases[20];
1723 static unsigned bases_count = 0;
1725 const char *branch1, *branch2;
1726 struct commit *result, *h1, *h2;
1727 struct commit_list *ca = NULL;
1728 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
1732 int namelen = strlen(argv[0]);
1734 !strcmp(argv[0] + namelen - 8, "-subtree"))
1738 git_config(merge_config);
1739 if (getenv("GIT_MERGE_VERBOSITY"))
1740 verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
1743 die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]);
1745 for (i = 1; i < argc; ++i) {
1746 if (!strcmp(argv[i], "--"))
1748 if (bases_count < sizeof(bases)/sizeof(*bases))
1749 bases[bases_count++] = argv[i];
1751 if (argc - i != 3) /* "--" "<head>" "<remote>" */
1752 die("Not handling anything other than two heads merge.");
1756 branch1 = argv[++i];
1757 branch2 = argv[++i];
1759 h1 = get_ref(branch1);
1760 h2 = get_ref(branch2);
1762 branch1 = better_branch_name(branch1);
1763 branch2 = better_branch_name(branch2);
1766 printf("Merging %s with %s\n", branch1, branch2);
1768 index_fd = hold_locked_index(lock, 1);
1770 for (i = 0; i < bases_count; i++) {
1771 struct commit *ancestor = get_ref(bases[i]);
1772 ca = commit_list_insert(ancestor, &ca);
1774 clean = merge(h1, h2, branch1, branch2, ca, &result);
1776 if (active_cache_changed &&
1777 (write_cache(index_fd, active_cache, active_nr) ||
1778 close(index_fd) || commit_locked_index(lock)))
1779 die ("unable to write %s", get_index_file());
1781 return clean ? 0: 1;