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 rename_limit = -1;
100 static int buffer_output = 1;
101 static struct output_buffer *output_list, *output_end;
103 static int show (int v)
105 return (!call_depth && verbosity >= v) || verbosity >= 5;
108 static void output(int v, const char *fmt, ...)
112 if (buffer_output && show(v)) {
113 struct output_buffer *b = xmalloc(sizeof(*b));
114 nfvasprintf(&b->str, fmt, args);
117 output_end->next = b;
121 } else if (show(v)) {
123 for (i = call_depth; i--;)
125 vfprintf(stdout, fmt, args);
131 static void flush_output(void)
133 struct output_buffer *b, *n;
134 for (b = output_list; b; b = n) {
136 for (i = call_depth; i--;)
138 fputs(b->str, stdout);
148 static void output_commit_title(struct commit *commit)
152 for (i = call_depth; i--;)
155 printf("virtual %s\n", (char *)commit->util);
157 printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
158 if (parse_commit(commit) != 0)
159 printf("(bad commit)\n");
163 for (s = commit->buffer; *s; s++)
164 if (*s == '\n' && s[1] == '\n') {
168 for (len = 0; s[len] && '\n' != s[len]; len++)
170 printf("%.*s\n", len, s);
175 static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
176 const char *path, int stage, int refresh, int options)
178 struct cache_entry *ce;
179 ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
181 return error("addinfo_cache failed for path '%s'", path);
182 return add_cache_entry(ce, options);
186 * This is a global variable which is used in a number of places but
187 * only written to in the 'merge' function.
189 * index_only == 1 => Don't leave any non-stage 0 entries in the cache and
190 * don't update the working directory.
191 * 0 => Leave unmerged entries in the cache and update
192 * the working directory.
194 static int index_only = 0;
196 static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
199 init_tree_desc(desc, tree->buffer, tree->size);
202 static int git_merge_trees(int index_only,
208 struct tree_desc t[3];
209 struct unpack_trees_options opts;
211 memset(&opts, 0, sizeof(opts));
218 opts.fn = threeway_merge;
220 init_tree_desc_from_tree(t+0, common);
221 init_tree_desc_from_tree(t+1, head);
222 init_tree_desc_from_tree(t+2, merge);
224 rc = unpack_trees(3, t, &opts);
225 cache_tree_free(&active_cache_tree);
229 static int unmerged_index(void)
232 for (i = 0; i < active_nr; i++) {
233 struct cache_entry *ce = active_cache[i];
240 static struct tree *git_write_tree(void)
242 struct tree *result = NULL;
244 if (unmerged_index()) {
246 output(0, "There are unmerged index entries:");
247 for (i = 0; i < active_nr; i++) {
248 struct cache_entry *ce = active_cache[i];
250 output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name);
255 if (!active_cache_tree)
256 active_cache_tree = cache_tree();
258 if (!cache_tree_fully_valid(active_cache_tree) &&
259 cache_tree_update(active_cache_tree,
260 active_cache, active_nr, 0, 0) < 0)
261 die("error building trees");
263 result = lookup_tree(active_cache_tree->sha1);
268 static int save_files_dirs(const unsigned char *sha1,
269 const char *base, int baselen, const char *path,
270 unsigned int mode, int stage)
272 int len = strlen(path);
273 char *newpath = xmalloc(baselen + len + 1);
274 memcpy(newpath, base, baselen);
275 memcpy(newpath + baselen, path, len);
276 newpath[baselen + len] = '\0';
279 path_list_insert(newpath, ¤t_directory_set);
281 path_list_insert(newpath, ¤t_file_set);
284 return READ_TREE_RECURSIVE;
287 static int get_files_dirs(struct tree *tree)
290 if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0)
292 n = current_file_set.nr + current_directory_set.nr;
297 * Returns a index_entry instance which doesn't have to correspond to
298 * a real cache entry in Git's index.
300 static struct stage_data *insert_stage_data(const char *path,
301 struct tree *o, struct tree *a, struct tree *b,
302 struct path_list *entries)
304 struct path_list_item *item;
305 struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
306 get_tree_entry(o->object.sha1, path,
307 e->stages[1].sha, &e->stages[1].mode);
308 get_tree_entry(a->object.sha1, path,
309 e->stages[2].sha, &e->stages[2].mode);
310 get_tree_entry(b->object.sha1, path,
311 e->stages[3].sha, &e->stages[3].mode);
312 item = path_list_insert(path, entries);
318 * Create a dictionary mapping file names to stage_data objects. The
319 * dictionary contains one entry for every path with a non-zero stage entry.
321 static struct path_list *get_unmerged(void)
323 struct path_list *unmerged = xcalloc(1, sizeof(struct path_list));
326 unmerged->strdup_paths = 1;
328 for (i = 0; i < active_nr; i++) {
329 struct path_list_item *item;
330 struct stage_data *e;
331 struct cache_entry *ce = active_cache[i];
335 item = path_list_lookup(ce->name, unmerged);
337 item = path_list_insert(ce->name, unmerged);
338 item->util = xcalloc(1, sizeof(struct stage_data));
341 e->stages[ce_stage(ce)].mode = ntohl(ce->ce_mode);
342 hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
350 struct diff_filepair *pair;
351 struct stage_data *src_entry;
352 struct stage_data *dst_entry;
353 unsigned processed:1;
357 * Get information of all renames which occurred between 'o_tree' and
358 * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
359 * 'b_tree') to be able to associate the correct cache entries with
360 * the rename information. 'tree' is always equal to either a_tree or b_tree.
362 static struct path_list *get_renames(struct tree *tree,
366 struct path_list *entries)
369 struct path_list *renames;
370 struct diff_options opts;
372 renames = xcalloc(1, sizeof(struct path_list));
375 opts.detect_rename = DIFF_DETECT_RENAME;
376 opts.rename_limit = rename_limit;
377 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
378 if (diff_setup_done(&opts) < 0)
379 die("diff setup failed");
380 diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
382 for (i = 0; i < diff_queued_diff.nr; ++i) {
383 struct path_list_item *item;
385 struct diff_filepair *pair = diff_queued_diff.queue[i];
386 if (pair->status != 'R') {
387 diff_free_filepair(pair);
390 re = xmalloc(sizeof(*re));
393 item = path_list_lookup(re->pair->one->path, entries);
395 re->src_entry = insert_stage_data(re->pair->one->path,
396 o_tree, a_tree, b_tree, entries);
398 re->src_entry = item->util;
400 item = path_list_lookup(re->pair->two->path, entries);
402 re->dst_entry = insert_stage_data(re->pair->two->path,
403 o_tree, a_tree, b_tree, entries);
405 re->dst_entry = item->util;
406 item = path_list_insert(pair->one->path, renames);
409 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
410 diff_queued_diff.nr = 0;
415 static int update_stages(const char *path, struct diff_filespec *o,
416 struct diff_filespec *a, struct diff_filespec *b,
419 int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
421 if (remove_file_from_cache(path))
424 if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
427 if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
430 if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
435 static int remove_path(const char *name)
444 dirs = xmalloc(len+1);
445 memcpy(dirs, name, len);
447 while ((slash = strrchr(name, '/'))) {
450 if (rmdir(name) != 0)
457 static int remove_file(int clean, const char *path, int no_wd)
459 int update_cache = index_only || clean;
460 int update_working_directory = !index_only && !no_wd;
463 if (remove_file_from_cache(path))
466 if (update_working_directory) {
468 if (errno != ENOENT || errno != EISDIR)
475 static char *unique_path(const char *path, const char *branch)
477 char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
480 char *p = newpath + strlen(path);
481 strcpy(newpath, path);
487 while (path_list_has_path(¤t_file_set, newpath) ||
488 path_list_has_path(¤t_directory_set, newpath) ||
489 lstat(newpath, &st) == 0)
490 sprintf(p, "_%d", suffix++);
492 path_list_insert(newpath, ¤t_file_set);
496 static int mkdir_p(const char *path, unsigned long mode)
498 /* path points to cache entries, so xstrdup before messing with it */
499 char *buf = xstrdup(path);
500 int result = safe_create_leading_directories(buf);
505 static void flush_buffer(int fd, const char *buf, unsigned long size)
508 long ret = write_in_full(fd, buf, size);
513 die("merge-recursive: %s", strerror(errno));
515 die("merge-recursive: disk full?");
522 static int make_room_for_path(const char *path)
525 const char *msg = "failed to create path '%s'%s";
527 status = mkdir_p(path, 0777);
530 /* something else exists */
531 error(msg, path, ": perhaps a D/F conflict?");
537 /* Successful unlink is good.. */
540 /* .. and so is no existing file */
543 /* .. but not some other error (who really cares what?) */
544 return error(msg, path, ": perhaps a D/F conflict?");
547 static void update_file_flags(const unsigned char *sha,
557 enum object_type type;
561 buf = read_sha1_file(sha, &type, &size);
563 die("cannot read object %s '%s'", sha1_to_hex(sha), path);
564 if (type != OBJ_BLOB)
565 die("blob expected for %s '%s'", sha1_to_hex(sha), path);
567 if (make_room_for_path(path) < 0) {
571 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
577 fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
579 die("failed to open %s: %s", path, strerror(errno));
580 flush_buffer(fd, buf, size);
582 } else if (S_ISLNK(mode)) {
583 char *lnk = xmalloc(size + 1);
584 memcpy(lnk, buf, size);
591 die("do not know what to do with %06o %s '%s'",
592 mode, sha1_to_hex(sha), path);
596 add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
599 static void update_file(int clean,
600 const unsigned char *sha,
604 update_file_flags(sha, mode, path, index_only || clean, !index_only);
607 /* Low level file merging, update and removal */
609 struct merge_file_info
611 unsigned char sha[20];
617 static void fill_mm(const unsigned char *sha1, mmfile_t *mm)
620 enum object_type type;
622 if (!hashcmp(sha1, null_sha1)) {
623 mm->ptr = xstrdup("");
628 mm->ptr = read_sha1_file(sha1, &type, &size);
629 if (!mm->ptr || type != OBJ_BLOB)
630 die("unable to read blob object %s", sha1_to_hex(sha1));
635 * Customizable low-level merge drivers support.
638 struct ll_merge_driver;
639 typedef int (*ll_merge_fn)(const struct ll_merge_driver *,
642 mmfile_t *src1, const char *name1,
643 mmfile_t *src2, const char *name2,
646 struct ll_merge_driver {
648 const char *description;
650 const char *recursive;
651 struct ll_merge_driver *next;
656 * Built-in low-levels
658 static int ll_binary_merge(const struct ll_merge_driver *drv_unused,
659 const char *path_unused,
661 mmfile_t *src1, const char *name1,
662 mmfile_t *src2, const char *name2,
666 * The tentative merge result is "ours" for the final round,
667 * or common ancestor for an internal merge. Still return
668 * "conflicted merge" status.
670 mmfile_t *stolen = index_only ? orig : src1;
672 result->ptr = stolen->ptr;
673 result->size = stolen->size;
678 static int ll_xdl_merge(const struct ll_merge_driver *drv_unused,
679 const char *path_unused,
681 mmfile_t *src1, const char *name1,
682 mmfile_t *src2, const char *name2,
687 if (buffer_is_binary(orig->ptr, orig->size) ||
688 buffer_is_binary(src1->ptr, src1->size) ||
689 buffer_is_binary(src2->ptr, src2->size)) {
690 warning("Cannot merge binary files: %s vs. %s\n",
692 return ll_binary_merge(drv_unused, path_unused,
698 memset(&xpp, 0, sizeof(xpp));
699 return xdl_merge(orig,
702 &xpp, XDL_MERGE_ZEALOUS,
706 static int ll_union_merge(const struct ll_merge_driver *drv_unused,
707 const char *path_unused,
709 mmfile_t *src1, const char *name1,
710 mmfile_t *src2, const char *name2,
715 const int marker_size = 7;
717 int status = ll_xdl_merge(drv_unused, path_unused,
718 orig, src1, NULL, src2, NULL, result);
722 src = dst = result->ptr;
725 if ((marker_size < size) &&
726 (*src == '<' || *src == '=' || *src == '>')) {
729 for (i = 0; i < marker_size; i++)
732 if (src[marker_size] != '\n')
734 src += marker_size + 1;
735 size -= marker_size + 1;
743 } while (ch != '\n' && size);
745 result->size = dst - result->ptr;
749 #define LL_BINARY_MERGE 0
750 #define LL_TEXT_MERGE 1
751 #define LL_UNION_MERGE 2
752 static struct ll_merge_driver ll_merge_drv[] = {
753 { "binary", "built-in binary merge", ll_binary_merge },
754 { "text", "built-in 3-way text merge", ll_xdl_merge },
755 { "union", "built-in union merge", ll_union_merge },
758 static void create_temp(mmfile_t *src, char *path)
762 strcpy(path, ".merge_file_XXXXXX");
764 if (write_in_full(fd, src->ptr, src->size) != src->size)
765 die("unable to write temp-file");
770 * User defined low-level merge driver support.
772 static int ll_ext_merge(const struct ll_merge_driver *fn,
775 mmfile_t *src1, const char *name1,
776 mmfile_t *src2, const char *name2,
781 struct interp table[] = {
786 struct child_process child;
787 const char *args[20];
791 if (fn->cmdline == NULL)
792 die("custom merge driver %s lacks command line.", fn->name);
796 create_temp(orig, temp[0]);
797 create_temp(src1, temp[1]);
798 create_temp(src2, temp[2]);
800 interp_set_entry(table, 0, temp[0]);
801 interp_set_entry(table, 1, temp[1]);
802 interp_set_entry(table, 2, temp[2]);
804 output(1, "merging %s using %s", path,
805 fn->description ? fn->description : fn->name);
807 interpolate(cmdbuf, sizeof(cmdbuf), fn->cmdline, table, 3);
809 memset(&child, 0, sizeof(child));
816 status = run_command(&child);
817 if (status < -ERR_RUN_COMMAND_FORK)
818 ; /* failure in run-command */
821 fd = open(temp[1], O_RDONLY);
826 result->size = st.st_size;
827 result->ptr = xmalloc(result->size + 1);
828 if (read_in_full(fd, result->ptr, result->size) != result->size) {
836 for (i = 0; i < 3; i++)
842 * merge.default and merge.driver configuration items
844 static struct ll_merge_driver *ll_user_merge, **ll_user_merge_tail;
845 static const char *default_ll_merge;
847 static int read_merge_config(const char *var, const char *value)
849 struct ll_merge_driver *fn;
850 const char *ep, *name;
853 if (!strcmp(var, "merge.default")) {
855 default_ll_merge = strdup(value);
860 * We are not interested in anything but "merge.<name>.variable";
861 * especially, we do not want to look at variables such as
862 * "merge.summary", "merge.tool", and "merge.verbosity".
864 if (prefixcmp(var, "merge.") || (ep = strrchr(var, '.')) == var + 5)
868 * Find existing one as we might be processing merge.<name>.var2
869 * after seeing merge.<name>.var1.
873 for (fn = ll_user_merge; fn; fn = fn->next)
874 if (!strncmp(fn->name, name, namelen) && !fn->name[namelen])
878 fn = xcalloc(1, sizeof(struct ll_merge_driver));
879 namebuf = xmalloc(namelen + 1);
880 memcpy(namebuf, name, namelen);
881 namebuf[namelen] = 0;
883 fn->fn = ll_ext_merge;
885 *ll_user_merge_tail = fn;
886 ll_user_merge_tail = &(fn->next);
891 if (!strcmp("name", ep)) {
893 return error("%s: lacks value", var);
894 fn->description = strdup(value);
898 if (!strcmp("driver", ep)) {
900 return error("%s: lacks value", var);
902 * merge.<name>.driver specifies the command line:
906 * The command-line will be interpolated with the following
907 * tokens and is given to the shell:
909 * %O - temporary file name for the merge base.
910 * %A - temporary file name for our version.
911 * %B - temporary file name for the other branches' version.
913 * The external merge driver should write the results in the
914 * file named by %A, and signal that it has done with zero exit
917 fn->cmdline = strdup(value);
921 if (!strcmp("recursive", ep)) {
923 return error("%s: lacks value", var);
924 fn->recursive = strdup(value);
931 static void initialize_ll_merge(void)
933 if (ll_user_merge_tail)
935 ll_user_merge_tail = &ll_user_merge;
936 git_config(read_merge_config);
939 static const struct ll_merge_driver *find_ll_merge_driver(const char *merge_attr)
941 struct ll_merge_driver *fn;
945 initialize_ll_merge();
947 if (ATTR_TRUE(merge_attr))
948 return &ll_merge_drv[LL_TEXT_MERGE];
949 else if (ATTR_FALSE(merge_attr))
950 return &ll_merge_drv[LL_BINARY_MERGE];
951 else if (ATTR_UNSET(merge_attr)) {
952 if (!default_ll_merge)
953 return &ll_merge_drv[LL_TEXT_MERGE];
955 name = default_ll_merge;
960 for (fn = ll_user_merge; fn; fn = fn->next)
961 if (!strcmp(fn->name, name))
964 for (i = 0; i < ARRAY_SIZE(ll_merge_drv); i++)
965 if (!strcmp(ll_merge_drv[i].name, name))
966 return &ll_merge_drv[i];
968 /* default to the 3-way */
969 return &ll_merge_drv[LL_TEXT_MERGE];
972 static const char *git_path_check_merge(const char *path)
974 static struct git_attr_check attr_merge_check;
976 if (!attr_merge_check.attr)
977 attr_merge_check.attr = git_attr("merge", 5);
979 if (git_checkattr(path, 1, &attr_merge_check))
981 return attr_merge_check.value;
984 static int ll_merge(mmbuffer_t *result_buf,
985 struct diff_filespec *o,
986 struct diff_filespec *a,
987 struct diff_filespec *b,
991 mmfile_t orig, src1, src2;
994 const char *ll_driver_name;
995 const struct ll_merge_driver *driver;
997 name1 = xstrdup(mkpath("%s:%s", branch1, a->path));
998 name2 = xstrdup(mkpath("%s:%s", branch2, b->path));
1000 fill_mm(o->sha1, &orig);
1001 fill_mm(a->sha1, &src1);
1002 fill_mm(b->sha1, &src2);
1004 ll_driver_name = git_path_check_merge(a->path);
1005 driver = find_ll_merge_driver(ll_driver_name);
1007 if (index_only && driver->recursive)
1008 driver = find_ll_merge_driver(driver->recursive);
1009 merge_status = driver->fn(driver, a->path,
1010 &orig, &src1, name1, &src2, name2,
1018 return merge_status;
1021 static struct merge_file_info merge_file(struct diff_filespec *o,
1022 struct diff_filespec *a, struct diff_filespec *b,
1023 const char *branch1, const char *branch2)
1025 struct merge_file_info result;
1029 if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
1031 if (S_ISREG(a->mode)) {
1032 result.mode = a->mode;
1033 hashcpy(result.sha, a->sha1);
1035 result.mode = b->mode;
1036 hashcpy(result.sha, b->sha1);
1039 if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1))
1042 result.mode = a->mode == o->mode ? b->mode: a->mode;
1044 if (sha_eq(a->sha1, o->sha1))
1045 hashcpy(result.sha, b->sha1);
1046 else if (sha_eq(b->sha1, o->sha1))
1047 hashcpy(result.sha, a->sha1);
1048 else if (S_ISREG(a->mode)) {
1049 mmbuffer_t result_buf;
1052 merge_status = ll_merge(&result_buf, o, a, b,
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",
1063 free(result_buf.ptr);
1064 result.clean = (merge_status == 0);
1066 if (!(S_ISLNK(a->mode) || S_ISLNK(b->mode)))
1067 die("cannot merge modes?");
1069 hashcpy(result.sha, a->sha1);
1071 if (!sha_eq(a->sha1, b->sha1))
1079 static void conflict_rename_rename(struct rename *ren1,
1080 const char *branch1,
1081 struct rename *ren2,
1082 const char *branch2)
1086 const char *ren1_dst = ren1->pair->two->path;
1087 const char *ren2_dst = ren2->pair->two->path;
1088 const char *dst_name1 = ren1_dst;
1089 const char *dst_name2 = ren2_dst;
1090 if (path_list_has_path(¤t_directory_set, ren1_dst)) {
1091 dst_name1 = del[delp++] = unique_path(ren1_dst, branch1);
1092 output(1, "%s is a directory in %s added as %s instead",
1093 ren1_dst, branch2, dst_name1);
1094 remove_file(0, ren1_dst, 0);
1096 if (path_list_has_path(¤t_directory_set, ren2_dst)) {
1097 dst_name2 = del[delp++] = unique_path(ren2_dst, branch2);
1098 output(1, "%s is a directory in %s added as %s instead",
1099 ren2_dst, branch1, dst_name2);
1100 remove_file(0, ren2_dst, 0);
1103 remove_file_from_cache(dst_name1);
1104 remove_file_from_cache(dst_name2);
1106 * Uncomment to leave the conflicting names in the resulting tree
1108 * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1);
1109 * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2);
1112 update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
1113 update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
1119 static void conflict_rename_dir(struct rename *ren1,
1120 const char *branch1)
1122 char *new_path = unique_path(ren1->pair->two->path, branch1);
1123 output(1, "Renamed %s to %s instead", ren1->pair->one->path, new_path);
1124 remove_file(0, ren1->pair->two->path, 0);
1125 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
1129 static void conflict_rename_rename_2(struct rename *ren1,
1130 const char *branch1,
1131 struct rename *ren2,
1132 const char *branch2)
1134 char *new_path1 = unique_path(ren1->pair->two->path, branch1);
1135 char *new_path2 = unique_path(ren2->pair->two->path, branch2);
1136 output(1, "Renamed %s to %s and %s to %s instead",
1137 ren1->pair->one->path, new_path1,
1138 ren2->pair->one->path, new_path2);
1139 remove_file(0, ren1->pair->two->path, 0);
1140 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
1141 update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
1146 static int process_renames(struct path_list *a_renames,
1147 struct path_list *b_renames,
1148 const char *a_branch,
1149 const char *b_branch)
1151 int clean_merge = 1, i, j;
1152 struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
1153 const struct rename *sre;
1155 for (i = 0; i < a_renames->nr; i++) {
1156 sre = a_renames->items[i].util;
1157 path_list_insert(sre->pair->two->path, &a_by_dst)->util
1160 for (i = 0; i < b_renames->nr; i++) {
1161 sre = b_renames->items[i].util;
1162 path_list_insert(sre->pair->two->path, &b_by_dst)->util
1166 for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
1169 struct path_list *renames1, *renames2, *renames2Dst;
1170 struct rename *ren1 = NULL, *ren2 = NULL;
1171 const char *branch1, *branch2;
1172 const char *ren1_src, *ren1_dst;
1174 if (i >= a_renames->nr) {
1176 ren2 = b_renames->items[j++].util;
1177 } else if (j >= b_renames->nr) {
1179 ren1 = a_renames->items[i++].util;
1181 compare = strcmp(a_renames->items[i].path,
1182 b_renames->items[j].path);
1184 ren1 = a_renames->items[i++].util;
1186 ren2 = b_renames->items[j++].util;
1189 /* TODO: refactor, so that 1/2 are not needed */
1191 renames1 = a_renames;
1192 renames2 = b_renames;
1193 renames2Dst = &b_by_dst;
1198 renames1 = b_renames;
1199 renames2 = a_renames;
1200 renames2Dst = &a_by_dst;
1207 src = ren1->pair->one->path;
1209 ren1->dst_entry->processed = 1;
1210 ren1->src_entry->processed = 1;
1212 if (ren1->processed)
1214 ren1->processed = 1;
1216 ren1_src = ren1->pair->one->path;
1217 ren1_dst = ren1->pair->two->path;
1220 const char *ren2_src = ren2->pair->one->path;
1221 const char *ren2_dst = ren2->pair->two->path;
1222 /* Renamed in 1 and renamed in 2 */
1223 if (strcmp(ren1_src, ren2_src) != 0)
1224 die("ren1.src != ren2.src");
1225 ren2->dst_entry->processed = 1;
1226 ren2->processed = 1;
1227 if (strcmp(ren1_dst, ren2_dst) != 0) {
1229 output(1, "CONFLICT (rename/rename): "
1230 "Rename \"%s\"->\"%s\" in branch \"%s\" "
1231 "rename \"%s\"->\"%s\" in \"%s\"%s",
1232 src, ren1_dst, branch1,
1233 src, ren2_dst, branch2,
1234 index_only ? " (left unresolved)": "");
1236 remove_file_from_cache(src);
1237 update_file(0, ren1->pair->one->sha1,
1238 ren1->pair->one->mode, src);
1240 conflict_rename_rename(ren1, branch1, ren2, branch2);
1242 struct merge_file_info mfi;
1243 remove_file(1, ren1_src, 1);
1244 mfi = merge_file(ren1->pair->one,
1249 if (mfi.merge || !mfi.clean)
1250 output(1, "Renamed %s->%s", src, ren1_dst);
1253 output(2, "Auto-merged %s", ren1_dst);
1256 output(1, "CONFLICT (content): merge conflict in %s",
1261 update_stages(ren1_dst,
1267 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1270 /* Renamed in 1, maybe changed in 2 */
1271 struct path_list_item *item;
1272 /* we only use sha1 and mode of these */
1273 struct diff_filespec src_other, dst_other;
1274 int try_merge, stage = a_renames == renames1 ? 3: 2;
1276 remove_file(1, ren1_src, index_only || stage == 3);
1278 hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
1279 src_other.mode = ren1->src_entry->stages[stage].mode;
1280 hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
1281 dst_other.mode = ren1->dst_entry->stages[stage].mode;
1285 if (path_list_has_path(¤t_directory_set, ren1_dst)) {
1287 output(1, "CONFLICT (rename/directory): Renamed %s->%s in %s "
1288 " directory %s added in %s",
1289 ren1_src, ren1_dst, branch1,
1291 conflict_rename_dir(ren1, branch1);
1292 } else if (sha_eq(src_other.sha1, null_sha1)) {
1294 output(1, "CONFLICT (rename/delete): Renamed %s->%s in %s "
1295 "and deleted in %s",
1296 ren1_src, ren1_dst, branch1,
1298 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
1299 } else if (!sha_eq(dst_other.sha1, null_sha1)) {
1300 const char *new_path;
1303 output(1, "CONFLICT (rename/add): Renamed %s->%s in %s. "
1305 ren1_src, ren1_dst, branch1,
1307 new_path = unique_path(ren1_dst, branch2);
1308 output(1, "Added as %s instead", new_path);
1309 update_file(0, dst_other.sha1, dst_other.mode, new_path);
1310 } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) {
1313 ren2->processed = 1;
1314 output(1, "CONFLICT (rename/rename): Renamed %s->%s in %s. "
1315 "Renamed %s->%s in %s",
1316 ren1_src, ren1_dst, branch1,
1317 ren2->pair->one->path, ren2->pair->two->path, branch2);
1318 conflict_rename_rename_2(ren1, branch1, ren2, branch2);
1323 struct diff_filespec *o, *a, *b;
1324 struct merge_file_info mfi;
1325 src_other.path = (char *)ren1_src;
1327 o = ren1->pair->one;
1328 if (a_renames == renames1) {
1329 a = ren1->pair->two;
1332 b = ren1->pair->two;
1335 mfi = merge_file(o, a, b,
1336 a_branch, b_branch);
1339 sha_eq(mfi.sha, ren1->pair->two->sha1) &&
1340 mfi.mode == ren1->pair->two->mode)
1342 * This messaged is part of
1343 * t6022 test. If you change
1344 * it update the test too.
1346 output(3, "Skipped %s (merged same as existing)", ren1_dst);
1348 if (mfi.merge || !mfi.clean)
1349 output(1, "Renamed %s => %s", ren1_src, ren1_dst);
1351 output(2, "Auto-merged %s", ren1_dst);
1353 output(1, "CONFLICT (rename/modify): Merge conflict in %s",
1358 update_stages(ren1_dst,
1361 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1366 path_list_clear(&a_by_dst, 0);
1367 path_list_clear(&b_by_dst, 0);
1372 static unsigned char *stage_sha(const unsigned char *sha, unsigned mode)
1374 return (is_null_sha1(sha) || mode == 0) ? NULL: (unsigned char *)sha;
1377 /* Per entry merge function */
1378 static int process_entry(const char *path, struct stage_data *entry,
1379 const char *branch1,
1380 const char *branch2)
1383 printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
1384 print_index_entry("\tpath: ", entry);
1386 int clean_merge = 1;
1387 unsigned o_mode = entry->stages[1].mode;
1388 unsigned a_mode = entry->stages[2].mode;
1389 unsigned b_mode = entry->stages[3].mode;
1390 unsigned char *o_sha = stage_sha(entry->stages[1].sha, o_mode);
1391 unsigned char *a_sha = stage_sha(entry->stages[2].sha, a_mode);
1392 unsigned char *b_sha = stage_sha(entry->stages[3].sha, b_mode);
1394 if (o_sha && (!a_sha || !b_sha)) {
1395 /* Case A: Deleted in one */
1396 if ((!a_sha && !b_sha) ||
1397 (sha_eq(a_sha, o_sha) && !b_sha) ||
1398 (!a_sha && sha_eq(b_sha, o_sha))) {
1399 /* Deleted in both or deleted in one and
1400 * unchanged in the other */
1402 output(2, "Removed %s", path);
1403 /* do not touch working file if it did not exist */
1404 remove_file(1, path, !a_sha);
1406 /* Deleted in one and changed in the other */
1409 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1410 "and modified in %s. Version %s of %s left in tree.",
1412 branch2, branch2, path);
1413 update_file(0, b_sha, b_mode, path);
1415 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1416 "and modified in %s. Version %s of %s left in tree.",
1418 branch1, branch1, path);
1419 update_file(0, a_sha, a_mode, path);
1423 } else if ((!o_sha && a_sha && !b_sha) ||
1424 (!o_sha && !a_sha && b_sha)) {
1425 /* Case B: Added in one. */
1426 const char *add_branch;
1427 const char *other_branch;
1429 const unsigned char *sha;
1433 add_branch = branch1;
1434 other_branch = branch2;
1437 conf = "file/directory";
1439 add_branch = branch2;
1440 other_branch = branch1;
1443 conf = "directory/file";
1445 if (path_list_has_path(¤t_directory_set, path)) {
1446 const char *new_path = unique_path(path, add_branch);
1448 output(1, "CONFLICT (%s): There is a directory with name %s in %s. "
1450 conf, path, other_branch, path, new_path);
1451 remove_file(0, path, 0);
1452 update_file(0, sha, mode, new_path);
1454 output(2, "Added %s", path);
1455 update_file(1, sha, mode, path);
1457 } else if (a_sha && b_sha) {
1458 /* Case C: Added in both (check for same permissions) and */
1459 /* case D: Modified in both, but differently. */
1460 const char *reason = "content";
1461 struct merge_file_info mfi;
1462 struct diff_filespec o, a, b;
1466 o_sha = (unsigned char *)null_sha1;
1468 output(2, "Auto-merged %s", path);
1469 o.path = a.path = b.path = (char *)path;
1470 hashcpy(o.sha1, o_sha);
1472 hashcpy(a.sha1, a_sha);
1474 hashcpy(b.sha1, b_sha);
1477 mfi = merge_file(&o, &a, &b,
1481 update_file(1, mfi.sha, mfi.mode, path);
1484 output(1, "CONFLICT (%s): Merge conflict in %s",
1488 update_file(0, mfi.sha, mfi.mode, path);
1490 update_file_flags(mfi.sha, mfi.mode, path,
1491 0 /* update_cache */, 1 /* update_working_directory */);
1493 } else if (!o_sha && !a_sha && !b_sha) {
1495 * this entry was deleted altogether. a_mode == 0 means
1496 * we had that path and want to actively remove it.
1498 remove_file(1, path, !a_mode);
1500 die("Fatal merge failure, shouldn't happen.");
1505 static int merge_trees(struct tree *head,
1507 struct tree *common,
1508 const char *branch1,
1509 const char *branch2,
1510 struct tree **result)
1514 if (subtree_merge) {
1515 merge = shift_tree_object(head, merge);
1516 common = shift_tree_object(head, common);
1519 if (sha_eq(common->object.sha1, merge->object.sha1)) {
1520 output(0, "Already uptodate!");
1525 code = git_merge_trees(index_only, common, head, merge);
1528 die("merging of trees %s and %s failed",
1529 sha1_to_hex(head->object.sha1),
1530 sha1_to_hex(merge->object.sha1));
1532 if (unmerged_index()) {
1533 struct path_list *entries, *re_head, *re_merge;
1535 path_list_clear(¤t_file_set, 1);
1536 path_list_clear(¤t_directory_set, 1);
1537 get_files_dirs(head);
1538 get_files_dirs(merge);
1540 entries = get_unmerged();
1541 re_head = get_renames(head, common, head, merge, entries);
1542 re_merge = get_renames(merge, common, head, merge, entries);
1543 clean = process_renames(re_head, re_merge,
1545 for (i = 0; i < entries->nr; i++) {
1546 const char *path = entries->items[i].path;
1547 struct stage_data *e = entries->items[i].util;
1549 && !process_entry(path, e, branch1, branch2))
1553 path_list_clear(re_merge, 0);
1554 path_list_clear(re_head, 0);
1555 path_list_clear(entries, 1);
1562 *result = git_write_tree();
1567 static struct commit_list *reverse_commit_list(struct commit_list *list)
1569 struct commit_list *next = NULL, *current, *backup;
1570 for (current = list; current; current = backup) {
1571 backup = current->next;
1572 current->next = next;
1579 * Merge the commits h1 and h2, return the resulting virtual
1580 * commit object and a flag indicating the cleanness of the merge.
1582 static int merge(struct commit *h1,
1584 const char *branch1,
1585 const char *branch2,
1586 struct commit_list *ca,
1587 struct commit **result)
1589 struct commit_list *iter;
1590 struct commit *merged_common_ancestors;
1591 struct tree *mrtree = mrtree;
1595 output(4, "Merging:");
1596 output_commit_title(h1);
1597 output_commit_title(h2);
1601 ca = get_merge_bases(h1, h2, 1);
1602 ca = reverse_commit_list(ca);
1606 output(5, "found %u common ancestor(s):", commit_list_count(ca));
1607 for (iter = ca; iter; iter = iter->next)
1608 output_commit_title(iter->item);
1611 merged_common_ancestors = pop_commit(&ca);
1612 if (merged_common_ancestors == NULL) {
1613 /* if there is no common ancestor, make an empty tree */
1614 struct tree *tree = xcalloc(1, sizeof(struct tree));
1616 tree->object.parsed = 1;
1617 tree->object.type = OBJ_TREE;
1618 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
1619 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1622 for (iter = ca; iter; iter = iter->next) {
1625 * When the merge fails, the result contains files
1626 * with conflict markers. The cleanness flag is
1627 * ignored, it was never actually used, as result of
1628 * merge_trees has always overwritten it: the committed
1629 * "conflicts" were already resolved.
1632 merge(merged_common_ancestors, iter->item,
1633 "Temporary merge branch 1",
1634 "Temporary merge branch 2",
1636 &merged_common_ancestors);
1639 if (!merged_common_ancestors)
1640 die("merge returned no commit");
1650 clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree,
1651 branch1, branch2, &mrtree);
1654 *result = make_virtual_commit(mrtree, "merged tree");
1655 commit_list_insert(h1, &(*result)->parents);
1656 commit_list_insert(h2, &(*result)->parents->next);
1662 static const char *better_branch_name(const char *branch)
1664 static char githead_env[8 + 40 + 1];
1667 if (strlen(branch) != 40)
1669 sprintf(githead_env, "GITHEAD_%s", branch);
1670 name = getenv(githead_env);
1671 return name ? name : branch;
1674 static struct commit *get_ref(const char *ref)
1676 unsigned char sha1[20];
1677 struct object *object;
1679 if (get_sha1(ref, sha1))
1680 die("Could not resolve ref '%s'", ref);
1681 object = deref_tag(parse_object(sha1), ref, strlen(ref));
1682 if (object->type == OBJ_TREE)
1683 return make_virtual_commit((struct tree*)object,
1684 better_branch_name(ref));
1685 if (object->type != OBJ_COMMIT)
1687 if (parse_commit((struct commit *)object))
1688 die("Could not parse commit '%s'", sha1_to_hex(object->sha1));
1689 return (struct commit *)object;
1692 static int merge_config(const char *var, const char *value)
1694 if (!strcasecmp(var, "merge.verbosity")) {
1695 verbosity = git_config_int(var, value);
1698 if (!strcasecmp(var, "diff.renamelimit")) {
1699 rename_limit = git_config_int(var, value);
1702 return git_default_config(var, value);
1705 int main(int argc, char *argv[])
1707 static const char *bases[20];
1708 static unsigned bases_count = 0;
1710 const char *branch1, *branch2;
1711 struct commit *result, *h1, *h2;
1712 struct commit_list *ca = NULL;
1713 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
1717 int namelen = strlen(argv[0]);
1719 !strcmp(argv[0] + namelen - 8, "-subtree"))
1723 git_config(merge_config);
1724 if (getenv("GIT_MERGE_VERBOSITY"))
1725 verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
1728 die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]);
1730 for (i = 1; i < argc; ++i) {
1731 if (!strcmp(argv[i], "--"))
1733 if (bases_count < sizeof(bases)/sizeof(*bases))
1734 bases[bases_count++] = argv[i];
1736 if (argc - i != 3) /* "--" "<head>" "<remote>" */
1737 die("Not handling anything other than two heads merge.");
1741 branch1 = argv[++i];
1742 branch2 = argv[++i];
1744 h1 = get_ref(branch1);
1745 h2 = get_ref(branch2);
1747 branch1 = better_branch_name(branch1);
1748 branch2 = better_branch_name(branch2);
1751 printf("Merging %s with %s\n", branch1, branch2);
1753 index_fd = hold_locked_index(lock, 1);
1755 for (i = 0; i < bases_count; i++) {
1756 struct commit *ancestor = get_ref(bases[i]);
1757 ca = commit_list_insert(ancestor, &ca);
1759 clean = merge(h1, h2, branch1, branch2, ca, &result);
1761 if (active_cache_changed &&
1762 (write_cache(index_fd, active_cache, active_nr) ||
1763 close(index_fd) || commit_locked_index(lock)))
1764 die ("unable to write %s", get_index_file());
1766 return clean ? 0: 1;