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 int do_progress = 1;
101 static unsigned last_percent;
102 static unsigned merged_cnt;
103 static unsigned total_cnt;
104 static volatile sig_atomic_t progress_update;
105 static struct output_buffer *output_list, *output_end;
107 static int show (int v)
109 return (!call_depth && verbosity >= v) || verbosity >= 5;
112 static void output(int v, const char *fmt, ...)
116 if (buffer_output && show(v)) {
117 struct output_buffer *b = xmalloc(sizeof(*b));
118 nfvasprintf(&b->str, fmt, args);
121 output_end->next = b;
125 } else if (show(v)) {
127 for (i = call_depth; i--;)
129 vfprintf(stdout, fmt, args);
135 static void flush_output()
137 struct output_buffer *b, *n;
138 for (b = output_list; b; b = n) {
140 for (i = call_depth; i--;)
142 fputs(b->str, stdout);
152 static void output_commit_title(struct commit *commit)
156 for (i = call_depth; i--;)
159 printf("virtual %s\n", (char *)commit->util);
161 printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
162 if (parse_commit(commit) != 0)
163 printf("(bad commit)\n");
167 for (s = commit->buffer; *s; s++)
168 if (*s == '\n' && s[1] == '\n') {
172 for (len = 0; s[len] && '\n' != s[len]; len++)
174 printf("%.*s\n", len, s);
179 static void progress_interval(int signum)
184 static void setup_progress_signal(void)
189 memset(&sa, 0, sizeof(sa));
190 sa.sa_handler = progress_interval;
191 sigemptyset(&sa.sa_mask);
192 sa.sa_flags = SA_RESTART;
193 sigaction(SIGALRM, &sa, NULL);
195 v.it_interval.tv_sec = 1;
196 v.it_interval.tv_usec = 0;
197 v.it_value = v.it_interval;
198 setitimer(ITIMER_REAL, &v, NULL);
201 static void display_progress()
203 unsigned percent = total_cnt ? merged_cnt * 100 / total_cnt : 0;
204 if (progress_update || percent != last_percent) {
205 fprintf(stderr, "%4u%% (%u/%u) done\r",
206 percent, merged_cnt, total_cnt);
208 last_percent = percent;
212 static struct cache_entry *make_cache_entry(unsigned int mode,
213 const unsigned char *sha1, const char *path, int stage, int refresh)
216 struct cache_entry *ce;
218 if (!verify_path(path))
222 size = cache_entry_size(len);
223 ce = xcalloc(1, size);
225 hashcpy(ce->sha1, sha1);
226 memcpy(ce->name, path, len);
227 ce->ce_flags = create_ce_flags(len, stage);
228 ce->ce_mode = create_ce_mode(mode);
231 return refresh_cache_entry(ce, 0);
236 static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
237 const char *path, int stage, int refresh, int options)
239 struct cache_entry *ce;
240 ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
242 return error("addinfo_cache failed for path '%s'", path);
243 return add_cache_entry(ce, options);
247 * This is a global variable which is used in a number of places but
248 * only written to in the 'merge' function.
250 * index_only == 1 => Don't leave any non-stage 0 entries in the cache and
251 * don't update the working directory.
252 * 0 => Leave unmerged entries in the cache and update
253 * the working directory.
255 static int index_only = 0;
257 static int git_merge_trees(int index_only,
263 struct object_list *trees = NULL;
264 struct unpack_trees_options opts;
266 memset(&opts, 0, sizeof(opts));
273 opts.fn = threeway_merge;
275 object_list_append(&common->object, &trees);
276 object_list_append(&head->object, &trees);
277 object_list_append(&merge->object, &trees);
279 rc = unpack_trees(trees, &opts);
280 cache_tree_free(&active_cache_tree);
284 static int unmerged_index(void)
287 for (i = 0; i < active_nr; i++) {
288 struct cache_entry *ce = active_cache[i];
295 static struct tree *git_write_tree(void)
297 struct tree *result = NULL;
299 if (unmerged_index()) {
301 output(0, "There are unmerged index entries:");
302 for (i = 0; i < active_nr; i++) {
303 struct cache_entry *ce = active_cache[i];
305 output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name);
310 if (!active_cache_tree)
311 active_cache_tree = cache_tree();
313 if (!cache_tree_fully_valid(active_cache_tree) &&
314 cache_tree_update(active_cache_tree,
315 active_cache, active_nr, 0, 0) < 0)
316 die("error building trees");
318 result = lookup_tree(active_cache_tree->sha1);
323 static int save_files_dirs(const unsigned char *sha1,
324 const char *base, int baselen, const char *path,
325 unsigned int mode, int stage)
327 int len = strlen(path);
328 char *newpath = xmalloc(baselen + len + 1);
329 memcpy(newpath, base, baselen);
330 memcpy(newpath + baselen, path, len);
331 newpath[baselen + len] = '\0';
334 path_list_insert(newpath, ¤t_directory_set);
336 path_list_insert(newpath, ¤t_file_set);
339 return READ_TREE_RECURSIVE;
342 static int get_files_dirs(struct tree *tree)
345 if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0)
347 n = current_file_set.nr + current_directory_set.nr;
352 * Returns a index_entry instance which doesn't have to correspond to
353 * a real cache entry in Git's index.
355 static struct stage_data *insert_stage_data(const char *path,
356 struct tree *o, struct tree *a, struct tree *b,
357 struct path_list *entries)
359 struct path_list_item *item;
360 struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
361 get_tree_entry(o->object.sha1, path,
362 e->stages[1].sha, &e->stages[1].mode);
363 get_tree_entry(a->object.sha1, path,
364 e->stages[2].sha, &e->stages[2].mode);
365 get_tree_entry(b->object.sha1, path,
366 e->stages[3].sha, &e->stages[3].mode);
367 item = path_list_insert(path, entries);
373 * Create a dictionary mapping file names to stage_data objects. The
374 * dictionary contains one entry for every path with a non-zero stage entry.
376 static struct path_list *get_unmerged(void)
378 struct path_list *unmerged = xcalloc(1, sizeof(struct path_list));
381 unmerged->strdup_paths = 1;
382 total_cnt += active_nr;
384 for (i = 0; i < active_nr; i++, merged_cnt++) {
385 struct path_list_item *item;
386 struct stage_data *e;
387 struct cache_entry *ce = active_cache[i];
393 item = path_list_lookup(ce->name, unmerged);
395 item = path_list_insert(ce->name, unmerged);
396 item->util = xcalloc(1, sizeof(struct stage_data));
399 e->stages[ce_stage(ce)].mode = ntohl(ce->ce_mode);
400 hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
408 struct diff_filepair *pair;
409 struct stage_data *src_entry;
410 struct stage_data *dst_entry;
411 unsigned processed:1;
415 * Get information of all renames which occurred between 'o_tree' and
416 * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
417 * 'b_tree') to be able to associate the correct cache entries with
418 * the rename information. 'tree' is always equal to either a_tree or b_tree.
420 static struct path_list *get_renames(struct tree *tree,
424 struct path_list *entries)
427 struct path_list *renames;
428 struct diff_options opts;
430 renames = xcalloc(1, sizeof(struct path_list));
433 opts.detect_rename = DIFF_DETECT_RENAME;
434 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
435 if (diff_setup_done(&opts) < 0)
436 die("diff setup failed");
437 diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
439 for (i = 0; i < diff_queued_diff.nr; ++i) {
440 struct path_list_item *item;
442 struct diff_filepair *pair = diff_queued_diff.queue[i];
443 if (pair->status != 'R') {
444 diff_free_filepair(pair);
447 re = xmalloc(sizeof(*re));
450 item = path_list_lookup(re->pair->one->path, entries);
452 re->src_entry = insert_stage_data(re->pair->one->path,
453 o_tree, a_tree, b_tree, entries);
455 re->src_entry = item->util;
457 item = path_list_lookup(re->pair->two->path, entries);
459 re->dst_entry = insert_stage_data(re->pair->two->path,
460 o_tree, a_tree, b_tree, entries);
462 re->dst_entry = item->util;
463 item = path_list_insert(pair->one->path, renames);
466 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
467 diff_queued_diff.nr = 0;
472 static int update_stages(const char *path, struct diff_filespec *o,
473 struct diff_filespec *a, struct diff_filespec *b,
476 int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
478 if (remove_file_from_cache(path))
481 if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
484 if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
487 if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
492 static int remove_path(const char *name)
501 dirs = xmalloc(len+1);
502 memcpy(dirs, name, len);
504 while ((slash = strrchr(name, '/'))) {
507 if (rmdir(name) != 0)
514 static int remove_file(int clean, const char *path, int no_wd)
516 int update_cache = index_only || clean;
517 int update_working_directory = !index_only && !no_wd;
520 if (remove_file_from_cache(path))
523 if (update_working_directory) {
525 if (errno != ENOENT || errno != EISDIR)
532 static char *unique_path(const char *path, const char *branch)
534 char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
537 char *p = newpath + strlen(path);
538 strcpy(newpath, path);
544 while (path_list_has_path(¤t_file_set, newpath) ||
545 path_list_has_path(¤t_directory_set, newpath) ||
546 lstat(newpath, &st) == 0)
547 sprintf(p, "_%d", suffix++);
549 path_list_insert(newpath, ¤t_file_set);
553 static int mkdir_p(const char *path, unsigned long mode)
555 /* path points to cache entries, so xstrdup before messing with it */
556 char *buf = xstrdup(path);
557 int result = safe_create_leading_directories(buf);
562 static void flush_buffer(int fd, const char *buf, unsigned long size)
565 long ret = write_in_full(fd, buf, size);
570 die("merge-recursive: %s", strerror(errno));
572 die("merge-recursive: disk full?");
579 static void update_file_flags(const unsigned char *sha,
589 enum object_type type;
593 buf = read_sha1_file(sha, &type, &size);
595 die("cannot read object %s '%s'", sha1_to_hex(sha), path);
596 if (type != OBJ_BLOB)
597 die("blob expected for %s '%s'", sha1_to_hex(sha), path);
599 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
601 if (mkdir_p(path, 0777))
602 die("failed to create path %s: %s", path, strerror(errno));
608 fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
610 die("failed to open %s: %s", path, strerror(errno));
611 flush_buffer(fd, buf, size);
613 } else if (S_ISLNK(mode)) {
614 char *lnk = xmalloc(size + 1);
615 memcpy(lnk, buf, size);
622 die("do not know what to do with %06o %s '%s'",
623 mode, sha1_to_hex(sha), path);
626 add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
629 static void update_file(int clean,
630 const unsigned char *sha,
634 update_file_flags(sha, mode, path, index_only || clean, !index_only);
637 /* Low level file merging, update and removal */
639 struct merge_file_info
641 unsigned char sha[20];
647 static void fill_mm(const unsigned char *sha1, mmfile_t *mm)
650 enum object_type type;
652 if (!hashcmp(sha1, null_sha1)) {
653 mm->ptr = xstrdup("");
658 mm->ptr = read_sha1_file(sha1, &type, &size);
659 if (!mm->ptr || type != OBJ_BLOB)
660 die("unable to read blob object %s", sha1_to_hex(sha1));
665 * Customizable low-level merge drivers support.
668 struct ll_merge_driver;
669 typedef int (*ll_merge_fn)(const struct ll_merge_driver *,
672 mmfile_t *src1, const char *name1,
673 mmfile_t *src2, const char *name2,
676 struct ll_merge_driver {
678 const char *description;
680 const char *recursive;
681 struct ll_merge_driver *next;
686 * Built-in low-levels
688 static int ll_xdl_merge(const struct ll_merge_driver *drv_unused,
689 const char *path_unused,
691 mmfile_t *src1, const char *name1,
692 mmfile_t *src2, const char *name2,
697 memset(&xpp, 0, sizeof(xpp));
698 return xdl_merge(orig,
701 &xpp, XDL_MERGE_ZEALOUS,
705 static int ll_union_merge(const struct ll_merge_driver *drv_unused,
706 const char *path_unused,
708 mmfile_t *src1, const char *name1,
709 mmfile_t *src2, const char *name2,
714 const int marker_size = 7;
716 int status = ll_xdl_merge(drv_unused, path_unused,
717 orig, src1, NULL, src2, NULL, result);
721 src = dst = result->ptr;
724 if ((marker_size < size) &&
725 (*src == '<' || *src == '=' || *src == '>')) {
728 for (i = 0; i < marker_size; i++)
731 if (src[marker_size] != '\n')
733 src += marker_size + 1;
734 size -= marker_size + 1;
742 } while (ch != '\n' && size);
744 result->size = dst - result->ptr;
748 static int ll_binary_merge(const struct ll_merge_driver *drv_unused,
749 const char *path_unused,
751 mmfile_t *src1, const char *name1,
752 mmfile_t *src2, const char *name2,
756 * The tentative merge result is "ours" for the final round,
757 * or common ancestor for an internal merge. Still return
758 * "conflicted merge" status.
760 mmfile_t *stolen = index_only ? orig : src1;
762 result->ptr = stolen->ptr;
763 result->size = stolen->size;
768 #define LL_BINARY_MERGE 0
769 #define LL_TEXT_MERGE 1
770 #define LL_UNION_MERGE 2
771 static struct ll_merge_driver ll_merge_drv[] = {
772 { "binary", "built-in binary merge", ll_binary_merge },
773 { "text", "built-in 3-way text merge", ll_xdl_merge },
774 { "union", "built-in union merge", ll_union_merge },
777 static void create_temp(mmfile_t *src, char *path)
781 strcpy(path, ".merge_file_XXXXXX");
784 die("unable to create temp-file");
785 if (write_in_full(fd, src->ptr, src->size) != src->size)
786 die("unable to write temp-file");
791 * User defined low-level merge driver support.
793 static int ll_ext_merge(const struct ll_merge_driver *fn,
796 mmfile_t *src1, const char *name1,
797 mmfile_t *src2, const char *name2,
802 struct interp table[] = {
807 struct child_process child;
808 const char *args[20];
812 if (fn->cmdline == NULL)
813 die("custom merge driver %s lacks command line.", fn->name);
817 create_temp(orig, temp[0]);
818 create_temp(src1, temp[1]);
819 create_temp(src2, temp[2]);
821 interp_set_entry(table, 0, temp[0]);
822 interp_set_entry(table, 1, temp[1]);
823 interp_set_entry(table, 2, temp[2]);
825 output(1, "merging %s using %s", path,
826 fn->description ? fn->description : fn->name);
828 interpolate(cmdbuf, sizeof(cmdbuf), fn->cmdline, table, 3);
830 memset(&child, 0, sizeof(child));
837 status = run_command(&child);
838 if (status < -ERR_RUN_COMMAND_FORK)
839 ; /* failure in run-command */
842 fd = open(temp[1], O_RDONLY);
847 result->size = st.st_size;
848 result->ptr = xmalloc(result->size + 1);
849 if (read_in_full(fd, result->ptr, result->size) != result->size) {
857 for (i = 0; i < 3; i++)
863 * merge.default and merge.driver configuration items
865 static struct ll_merge_driver *ll_user_merge, **ll_user_merge_tail;
866 static const char *default_ll_merge;
868 static int read_merge_config(const char *var, const char *value)
870 struct ll_merge_driver *fn;
871 const char *ep, *name;
874 if (!strcmp(var, "merge.default")) {
876 default_ll_merge = strdup(value);
881 * We are not interested in anything but "merge.<name>.variable";
882 * especially, we do not want to look at variables such as
883 * "merge.summary", "merge.tool", and "merge.verbosity".
885 if (prefixcmp(var, "merge.") || (ep = strrchr(var, '.')) == var + 5)
889 * Find existing one as we might be processing merge.<name>.var2
890 * after seeing merge.<name>.var1.
894 for (fn = ll_user_merge; fn; fn = fn->next)
895 if (!strncmp(fn->name, name, namelen) && !fn->name[namelen])
899 fn = xcalloc(1, sizeof(struct ll_merge_driver));
900 namebuf = xmalloc(namelen + 1);
901 memcpy(namebuf, name, namelen);
902 namebuf[namelen] = 0;
904 fn->fn = ll_ext_merge;
906 *ll_user_merge_tail = fn;
907 ll_user_merge_tail = &(fn->next);
912 if (!strcmp("name", ep)) {
914 return error("%s: lacks value", var);
915 fn->description = strdup(value);
919 if (!strcmp("driver", ep)) {
921 return error("%s: lacks value", var);
923 * merge.<name>.driver specifies the command line:
927 * The command-line will be interpolated with the following
928 * tokens and is given to the shell:
930 * %O - temporary file name for the merge base.
931 * %A - temporary file name for our version.
932 * %B - temporary file name for the other branches' version.
934 * The external merge driver should write the results in the
935 * file named by %A, and signal that it has done with zero exit
938 fn->cmdline = strdup(value);
942 if (!strcmp("recursive", ep)) {
944 return error("%s: lacks value", var);
945 fn->recursive = strdup(value);
952 static void initialize_ll_merge(void)
954 if (ll_user_merge_tail)
956 ll_user_merge_tail = &ll_user_merge;
957 git_config(read_merge_config);
960 static const struct ll_merge_driver *find_ll_merge_driver(const char *merge_attr)
962 struct ll_merge_driver *fn;
966 initialize_ll_merge();
968 if (ATTR_TRUE(merge_attr))
969 return &ll_merge_drv[LL_TEXT_MERGE];
970 else if (ATTR_FALSE(merge_attr))
971 return &ll_merge_drv[LL_BINARY_MERGE];
972 else if (ATTR_UNSET(merge_attr)) {
973 if (!default_ll_merge)
974 return &ll_merge_drv[LL_TEXT_MERGE];
976 name = default_ll_merge;
981 for (fn = ll_user_merge; fn; fn = fn->next)
982 if (!strcmp(fn->name, name))
985 for (i = 0; i < ARRAY_SIZE(ll_merge_drv); i++)
986 if (!strcmp(ll_merge_drv[i].name, name))
987 return &ll_merge_drv[i];
989 /* default to the 3-way */
990 return &ll_merge_drv[LL_TEXT_MERGE];
993 static const char *git_path_check_merge(const char *path)
995 static struct git_attr_check attr_merge_check;
997 if (!attr_merge_check.attr)
998 attr_merge_check.attr = git_attr("merge", 5);
1000 if (git_checkattr(path, 1, &attr_merge_check))
1002 return attr_merge_check.value;
1005 static int ll_merge(mmbuffer_t *result_buf,
1006 struct diff_filespec *o,
1007 struct diff_filespec *a,
1008 struct diff_filespec *b,
1009 const char *branch1,
1010 const char *branch2)
1012 mmfile_t orig, src1, src2;
1013 char *name1, *name2;
1015 const char *ll_driver_name;
1016 const struct ll_merge_driver *driver;
1018 name1 = xstrdup(mkpath("%s:%s", branch1, a->path));
1019 name2 = xstrdup(mkpath("%s:%s", branch2, b->path));
1021 fill_mm(o->sha1, &orig);
1022 fill_mm(a->sha1, &src1);
1023 fill_mm(b->sha1, &src2);
1025 ll_driver_name = git_path_check_merge(a->path);
1026 driver = find_ll_merge_driver(ll_driver_name);
1028 if (index_only && driver->recursive)
1029 driver = find_ll_merge_driver(driver->recursive);
1030 merge_status = driver->fn(driver, a->path,
1031 &orig, &src1, name1, &src2, name2,
1039 return merge_status;
1042 static struct merge_file_info merge_file(struct diff_filespec *o,
1043 struct diff_filespec *a, struct diff_filespec *b,
1044 const char *branch1, const char *branch2)
1046 struct merge_file_info result;
1050 if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
1052 if (S_ISREG(a->mode)) {
1053 result.mode = a->mode;
1054 hashcpy(result.sha, a->sha1);
1056 result.mode = b->mode;
1057 hashcpy(result.sha, b->sha1);
1060 if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1))
1063 result.mode = a->mode == o->mode ? b->mode: a->mode;
1065 if (sha_eq(a->sha1, o->sha1))
1066 hashcpy(result.sha, b->sha1);
1067 else if (sha_eq(b->sha1, o->sha1))
1068 hashcpy(result.sha, a->sha1);
1069 else if (S_ISREG(a->mode)) {
1070 mmbuffer_t result_buf;
1073 merge_status = ll_merge(&result_buf, o, a, b,
1076 if ((merge_status < 0) || !result_buf.ptr)
1077 die("Failed to execute internal merge");
1079 if (write_sha1_file(result_buf.ptr, result_buf.size,
1080 blob_type, result.sha))
1081 die("Unable to add %s to database",
1084 free(result_buf.ptr);
1085 result.clean = (merge_status == 0);
1087 if (!(S_ISLNK(a->mode) || S_ISLNK(b->mode)))
1088 die("cannot merge modes?");
1090 hashcpy(result.sha, a->sha1);
1092 if (!sha_eq(a->sha1, b->sha1))
1100 static void conflict_rename_rename(struct rename *ren1,
1101 const char *branch1,
1102 struct rename *ren2,
1103 const char *branch2)
1107 const char *ren1_dst = ren1->pair->two->path;
1108 const char *ren2_dst = ren2->pair->two->path;
1109 const char *dst_name1 = ren1_dst;
1110 const char *dst_name2 = ren2_dst;
1111 if (path_list_has_path(¤t_directory_set, ren1_dst)) {
1112 dst_name1 = del[delp++] = unique_path(ren1_dst, branch1);
1113 output(1, "%s is a directory in %s added as %s instead",
1114 ren1_dst, branch2, dst_name1);
1115 remove_file(0, ren1_dst, 0);
1117 if (path_list_has_path(¤t_directory_set, ren2_dst)) {
1118 dst_name2 = del[delp++] = unique_path(ren2_dst, branch2);
1119 output(1, "%s is a directory in %s added as %s instead",
1120 ren2_dst, branch1, dst_name2);
1121 remove_file(0, ren2_dst, 0);
1124 remove_file_from_cache(dst_name1);
1125 remove_file_from_cache(dst_name2);
1127 * Uncomment to leave the conflicting names in the resulting tree
1129 * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1);
1130 * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2);
1133 update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
1134 update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
1140 static void conflict_rename_dir(struct rename *ren1,
1141 const char *branch1)
1143 char *new_path = unique_path(ren1->pair->two->path, branch1);
1144 output(1, "Renamed %s to %s instead", ren1->pair->one->path, new_path);
1145 remove_file(0, ren1->pair->two->path, 0);
1146 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
1150 static void conflict_rename_rename_2(struct rename *ren1,
1151 const char *branch1,
1152 struct rename *ren2,
1153 const char *branch2)
1155 char *new_path1 = unique_path(ren1->pair->two->path, branch1);
1156 char *new_path2 = unique_path(ren2->pair->two->path, branch2);
1157 output(1, "Renamed %s to %s and %s to %s instead",
1158 ren1->pair->one->path, new_path1,
1159 ren2->pair->one->path, new_path2);
1160 remove_file(0, ren1->pair->two->path, 0);
1161 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
1162 update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
1167 static int process_renames(struct path_list *a_renames,
1168 struct path_list *b_renames,
1169 const char *a_branch,
1170 const char *b_branch)
1172 int clean_merge = 1, i, j;
1173 struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
1174 const struct rename *sre;
1176 for (i = 0; i < a_renames->nr; i++) {
1177 sre = a_renames->items[i].util;
1178 path_list_insert(sre->pair->two->path, &a_by_dst)->util
1181 for (i = 0; i < b_renames->nr; i++) {
1182 sre = b_renames->items[i].util;
1183 path_list_insert(sre->pair->two->path, &b_by_dst)->util
1187 for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
1190 struct path_list *renames1, *renames2, *renames2Dst;
1191 struct rename *ren1 = NULL, *ren2 = NULL;
1192 const char *branch1, *branch2;
1193 const char *ren1_src, *ren1_dst;
1195 if (i >= a_renames->nr) {
1197 ren2 = b_renames->items[j++].util;
1198 } else if (j >= b_renames->nr) {
1200 ren1 = a_renames->items[i++].util;
1202 compare = strcmp(a_renames->items[i].path,
1203 b_renames->items[j].path);
1205 ren1 = a_renames->items[i++].util;
1207 ren2 = b_renames->items[j++].util;
1210 /* TODO: refactor, so that 1/2 are not needed */
1212 renames1 = a_renames;
1213 renames2 = b_renames;
1214 renames2Dst = &b_by_dst;
1219 renames1 = b_renames;
1220 renames2 = a_renames;
1221 renames2Dst = &a_by_dst;
1228 src = ren1->pair->one->path;
1230 ren1->dst_entry->processed = 1;
1231 ren1->src_entry->processed = 1;
1233 if (ren1->processed)
1235 ren1->processed = 1;
1237 ren1_src = ren1->pair->one->path;
1238 ren1_dst = ren1->pair->two->path;
1241 const char *ren2_src = ren2->pair->one->path;
1242 const char *ren2_dst = ren2->pair->two->path;
1243 /* Renamed in 1 and renamed in 2 */
1244 if (strcmp(ren1_src, ren2_src) != 0)
1245 die("ren1.src != ren2.src");
1246 ren2->dst_entry->processed = 1;
1247 ren2->processed = 1;
1248 if (strcmp(ren1_dst, ren2_dst) != 0) {
1250 output(1, "CONFLICT (rename/rename): "
1251 "Rename \"%s\"->\"%s\" in branch \"%s\" "
1252 "rename \"%s\"->\"%s\" in \"%s\"%s",
1253 src, ren1_dst, branch1,
1254 src, ren2_dst, branch2,
1255 index_only ? " (left unresolved)": "");
1257 remove_file_from_cache(src);
1258 update_file(0, ren1->pair->one->sha1,
1259 ren1->pair->one->mode, src);
1261 conflict_rename_rename(ren1, branch1, ren2, branch2);
1263 struct merge_file_info mfi;
1264 remove_file(1, ren1_src, 1);
1265 mfi = merge_file(ren1->pair->one,
1270 if (mfi.merge || !mfi.clean)
1271 output(1, "Renamed %s->%s", src, ren1_dst);
1274 output(2, "Auto-merged %s", ren1_dst);
1277 output(1, "CONFLICT (content): merge conflict in %s",
1282 update_stages(ren1_dst,
1288 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1291 /* Renamed in 1, maybe changed in 2 */
1292 struct path_list_item *item;
1293 /* we only use sha1 and mode of these */
1294 struct diff_filespec src_other, dst_other;
1295 int try_merge, stage = a_renames == renames1 ? 3: 2;
1297 remove_file(1, ren1_src, index_only || stage == 3);
1299 hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
1300 src_other.mode = ren1->src_entry->stages[stage].mode;
1301 hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
1302 dst_other.mode = ren1->dst_entry->stages[stage].mode;
1306 if (path_list_has_path(¤t_directory_set, ren1_dst)) {
1308 output(1, "CONFLICT (rename/directory): Renamed %s->%s in %s "
1309 " directory %s added in %s",
1310 ren1_src, ren1_dst, branch1,
1312 conflict_rename_dir(ren1, branch1);
1313 } else if (sha_eq(src_other.sha1, null_sha1)) {
1315 output(1, "CONFLICT (rename/delete): Renamed %s->%s in %s "
1316 "and deleted in %s",
1317 ren1_src, ren1_dst, branch1,
1319 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
1320 } else if (!sha_eq(dst_other.sha1, null_sha1)) {
1321 const char *new_path;
1324 output(1, "CONFLICT (rename/add): Renamed %s->%s in %s. "
1326 ren1_src, ren1_dst, branch1,
1328 new_path = unique_path(ren1_dst, branch2);
1329 output(1, "Added as %s instead", new_path);
1330 update_file(0, dst_other.sha1, dst_other.mode, new_path);
1331 } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) {
1334 ren2->processed = 1;
1335 output(1, "CONFLICT (rename/rename): Renamed %s->%s in %s. "
1336 "Renamed %s->%s in %s",
1337 ren1_src, ren1_dst, branch1,
1338 ren2->pair->one->path, ren2->pair->two->path, branch2);
1339 conflict_rename_rename_2(ren1, branch1, ren2, branch2);
1344 struct diff_filespec *o, *a, *b;
1345 struct merge_file_info mfi;
1346 src_other.path = (char *)ren1_src;
1348 o = ren1->pair->one;
1349 if (a_renames == renames1) {
1350 a = ren1->pair->two;
1353 b = ren1->pair->two;
1356 mfi = merge_file(o, a, b,
1357 a_branch, b_branch);
1359 if (mfi.merge || !mfi.clean)
1360 output(1, "Renamed %s => %s", ren1_src, ren1_dst);
1362 output(2, "Auto-merged %s", ren1_dst);
1364 output(1, "CONFLICT (rename/modify): Merge conflict in %s",
1369 update_stages(ren1_dst,
1372 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1376 path_list_clear(&a_by_dst, 0);
1377 path_list_clear(&b_by_dst, 0);
1382 static unsigned char *has_sha(const unsigned char *sha)
1384 return is_null_sha1(sha) ? NULL: (unsigned char *)sha;
1387 /* Per entry merge function */
1388 static int process_entry(const char *path, struct stage_data *entry,
1389 const char *branch1,
1390 const char *branch2)
1393 printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
1394 print_index_entry("\tpath: ", entry);
1396 int clean_merge = 1;
1397 unsigned char *o_sha = has_sha(entry->stages[1].sha);
1398 unsigned char *a_sha = has_sha(entry->stages[2].sha);
1399 unsigned char *b_sha = has_sha(entry->stages[3].sha);
1400 unsigned o_mode = entry->stages[1].mode;
1401 unsigned a_mode = entry->stages[2].mode;
1402 unsigned b_mode = entry->stages[3].mode;
1404 if (o_sha && (!a_sha || !b_sha)) {
1405 /* Case A: Deleted in one */
1406 if ((!a_sha && !b_sha) ||
1407 (sha_eq(a_sha, o_sha) && !b_sha) ||
1408 (!a_sha && sha_eq(b_sha, o_sha))) {
1409 /* Deleted in both or deleted in one and
1410 * unchanged in the other */
1412 output(2, "Removed %s", path);
1413 /* do not touch working file if it did not exist */
1414 remove_file(1, path, !a_sha);
1416 /* Deleted in one and changed in the other */
1419 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1420 "and modified in %s. Version %s of %s left in tree.",
1422 branch2, branch2, path);
1423 update_file(0, b_sha, b_mode, path);
1425 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1426 "and modified in %s. Version %s of %s left in tree.",
1428 branch1, branch1, path);
1429 update_file(0, a_sha, a_mode, path);
1433 } else if ((!o_sha && a_sha && !b_sha) ||
1434 (!o_sha && !a_sha && b_sha)) {
1435 /* Case B: Added in one. */
1436 const char *add_branch;
1437 const char *other_branch;
1439 const unsigned char *sha;
1443 add_branch = branch1;
1444 other_branch = branch2;
1447 conf = "file/directory";
1449 add_branch = branch2;
1450 other_branch = branch1;
1453 conf = "directory/file";
1455 if (path_list_has_path(¤t_directory_set, path)) {
1456 const char *new_path = unique_path(path, add_branch);
1458 output(1, "CONFLICT (%s): There is a directory with name %s in %s. "
1460 conf, path, other_branch, path, new_path);
1461 remove_file(0, path, 0);
1462 update_file(0, sha, mode, new_path);
1464 output(2, "Added %s", path);
1465 update_file(1, sha, mode, path);
1467 } else if (a_sha && b_sha) {
1468 /* Case C: Added in both (check for same permissions) and */
1469 /* case D: Modified in both, but differently. */
1470 const char *reason = "content";
1471 struct merge_file_info mfi;
1472 struct diff_filespec o, a, b;
1476 o_sha = (unsigned char *)null_sha1;
1478 output(2, "Auto-merged %s", path);
1479 o.path = a.path = b.path = (char *)path;
1480 hashcpy(o.sha1, o_sha);
1482 hashcpy(a.sha1, a_sha);
1484 hashcpy(b.sha1, b_sha);
1487 mfi = merge_file(&o, &a, &b,
1491 update_file(1, mfi.sha, mfi.mode, path);
1494 output(1, "CONFLICT (%s): Merge conflict in %s",
1498 update_file(0, mfi.sha, mfi.mode, path);
1500 update_file_flags(mfi.sha, mfi.mode, path,
1501 0 /* update_cache */, 1 /* update_working_directory */);
1504 die("Fatal merge failure, shouldn't happen.");
1509 static int merge_trees(struct tree *head,
1511 struct tree *common,
1512 const char *branch1,
1513 const char *branch2,
1514 struct tree **result)
1518 if (subtree_merge) {
1519 merge = shift_tree_object(head, merge);
1520 common = shift_tree_object(head, common);
1523 if (sha_eq(common->object.sha1, merge->object.sha1)) {
1524 output(0, "Already uptodate!");
1529 code = git_merge_trees(index_only, common, head, merge);
1532 die("merging of trees %s and %s failed",
1533 sha1_to_hex(head->object.sha1),
1534 sha1_to_hex(merge->object.sha1));
1536 if (unmerged_index()) {
1537 struct path_list *entries, *re_head, *re_merge;
1539 path_list_clear(¤t_file_set, 1);
1540 path_list_clear(¤t_directory_set, 1);
1541 get_files_dirs(head);
1542 get_files_dirs(merge);
1544 entries = get_unmerged();
1545 re_head = get_renames(head, common, head, merge, entries);
1546 re_merge = get_renames(merge, common, head, merge, entries);
1547 clean = process_renames(re_head, re_merge,
1549 total_cnt += entries->nr;
1550 for (i = 0; i < entries->nr; i++, merged_cnt++) {
1551 const char *path = entries->items[i].path;
1552 struct stage_data *e = entries->items[i].util;
1554 && !process_entry(path, e, branch1, branch2))
1560 path_list_clear(re_merge, 0);
1561 path_list_clear(re_head, 0);
1562 path_list_clear(entries, 1);
1569 *result = git_write_tree();
1574 static struct commit_list *reverse_commit_list(struct commit_list *list)
1576 struct commit_list *next = NULL, *current, *backup;
1577 for (current = list; current; current = backup) {
1578 backup = current->next;
1579 current->next = next;
1586 * Merge the commits h1 and h2, return the resulting virtual
1587 * commit object and a flag indicating the cleanness of the merge.
1589 static int merge(struct commit *h1,
1591 const char *branch1,
1592 const char *branch2,
1593 struct commit_list *ca,
1594 struct commit **result)
1596 struct commit_list *iter;
1597 struct commit *merged_common_ancestors;
1598 struct tree *mrtree;
1602 output(4, "Merging:");
1603 output_commit_title(h1);
1604 output_commit_title(h2);
1608 ca = get_merge_bases(h1, h2, 1);
1609 ca = reverse_commit_list(ca);
1613 output(5, "found %u common ancestor(s):", commit_list_count(ca));
1614 for (iter = ca; iter; iter = iter->next)
1615 output_commit_title(iter->item);
1618 merged_common_ancestors = pop_commit(&ca);
1619 if (merged_common_ancestors == NULL) {
1620 /* if there is no common ancestor, make an empty tree */
1621 struct tree *tree = xcalloc(1, sizeof(struct tree));
1623 tree->object.parsed = 1;
1624 tree->object.type = OBJ_TREE;
1625 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
1626 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1629 for (iter = ca; iter; iter = iter->next) {
1632 * When the merge fails, the result contains files
1633 * with conflict markers. The cleanness flag is
1634 * ignored, it was never actually used, as result of
1635 * merge_trees has always overwritten it: the committed
1636 * "conflicts" were already resolved.
1639 merge(merged_common_ancestors, iter->item,
1640 "Temporary merge branch 1",
1641 "Temporary merge branch 2",
1643 &merged_common_ancestors);
1646 if (!merged_common_ancestors)
1647 die("merge returned no commit");
1657 clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree,
1658 branch1, branch2, &mrtree);
1661 *result = make_virtual_commit(mrtree, "merged tree");
1662 commit_list_insert(h1, &(*result)->parents);
1663 commit_list_insert(h2, &(*result)->parents->next);
1665 if (!call_depth && do_progress) {
1666 /* Make sure we end at 100% */
1669 merged_cnt = total_cnt;
1670 progress_update = 1;
1672 fputc('\n', stderr);
1678 static const char *better_branch_name(const char *branch)
1680 static char githead_env[8 + 40 + 1];
1683 if (strlen(branch) != 40)
1685 sprintf(githead_env, "GITHEAD_%s", branch);
1686 name = getenv(githead_env);
1687 return name ? name : branch;
1690 static struct commit *get_ref(const char *ref)
1692 unsigned char sha1[20];
1693 struct object *object;
1695 if (get_sha1(ref, sha1))
1696 die("Could not resolve ref '%s'", ref);
1697 object = deref_tag(parse_object(sha1), ref, strlen(ref));
1698 if (object->type == OBJ_TREE)
1699 return make_virtual_commit((struct tree*)object,
1700 better_branch_name(ref));
1701 if (object->type != OBJ_COMMIT)
1703 if (parse_commit((struct commit *)object))
1704 die("Could not parse commit '%s'", sha1_to_hex(object->sha1));
1705 return (struct commit *)object;
1708 static int merge_config(const char *var, const char *value)
1710 if (!strcasecmp(var, "merge.verbosity")) {
1711 verbosity = git_config_int(var, value);
1714 return git_default_config(var, value);
1717 int main(int argc, char *argv[])
1719 static const char *bases[20];
1720 static unsigned bases_count = 0;
1722 const char *branch1, *branch2;
1723 struct commit *result, *h1, *h2;
1724 struct commit_list *ca = NULL;
1725 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
1729 int namelen = strlen(argv[0]);
1731 !strcmp(argv[0] + namelen - 8, "-subtree"))
1735 git_config(merge_config);
1736 if (getenv("GIT_MERGE_VERBOSITY"))
1737 verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
1740 die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]);
1742 for (i = 1; i < argc; ++i) {
1743 if (!strcmp(argv[i], "--"))
1745 if (bases_count < sizeof(bases)/sizeof(*bases))
1746 bases[bases_count++] = argv[i];
1748 if (argc - i != 3) /* "--" "<head>" "<remote>" */
1749 die("Not handling anything other than two heads merge.");
1750 if (verbosity >= 5) {
1755 do_progress = isatty(1);
1757 branch1 = argv[++i];
1758 branch2 = argv[++i];
1760 h1 = get_ref(branch1);
1761 h2 = get_ref(branch2);
1763 branch1 = better_branch_name(branch1);
1764 branch2 = better_branch_name(branch2);
1767 setup_progress_signal();
1769 printf("Merging %s with %s\n", branch1, branch2);
1771 index_fd = hold_locked_index(lock, 1);
1773 for (i = 0; i < bases_count; i++) {
1774 struct commit *ancestor = get_ref(bases[i]);
1775 ca = commit_list_insert(ancestor, &ca);
1777 clean = merge(h1, h2, branch1, branch2, ca, &result);
1779 if (active_cache_changed &&
1780 (write_cache(index_fd, active_cache, active_nr) ||
1781 close(index_fd) || commit_locked_index(lock)))
1782 die ("unable to write %s", get_index_file());
1784 return clean ? 0: 1;