Add a demonstration/test of customized merge.
[git/gitweb.git] / merge-recursive.c
blob3b34401d0b25126b7955c0d44dad3e69a9592129
1 /*
2 * Recursive Merge algorithm stolen from git-merge-recursive.py by
3 * Fredrik Kuivinen.
4 * The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006
5 */
6 #include "cache.h"
7 #include "cache-tree.h"
8 #include "commit.h"
9 #include "blob.h"
10 #include "tree-walk.h"
11 #include "diff.h"
12 #include "diffcore.h"
13 #include "run-command.h"
14 #include "tag.h"
15 #include "unpack-trees.h"
16 #include "path-list.h"
17 #include "xdiff-interface.h"
18 #include "attr.h"
20 static int subtree_merge;
22 static struct tree *shift_tree_object(struct tree *one, struct tree *two)
24 unsigned char shifted[20];
27 * NEEDSWORK: this limits the recursion depth to hardcoded
28 * value '2' to avoid excessive overhead.
30 shift_tree(one->object.sha1, two->object.sha1, shifted, 2);
31 if (!hashcmp(two->object.sha1, shifted))
32 return two;
33 return lookup_tree(shifted);
37 * A virtual commit has
38 * - (const char *)commit->util set to the name, and
39 * - *(int *)commit->object.sha1 set to the virtual id.
42 static unsigned commit_list_count(const struct commit_list *l)
44 unsigned c = 0;
45 for (; l; l = l->next )
46 c++;
47 return c;
50 static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
52 struct commit *commit = xcalloc(1, sizeof(struct commit));
53 static unsigned virtual_id = 1;
54 commit->tree = tree;
55 commit->util = (void*)comment;
56 *(int*)commit->object.sha1 = virtual_id++;
57 /* avoid warnings */
58 commit->object.parsed = 1;
59 return commit;
63 * Since we use get_tree_entry(), which does not put the read object into
64 * the object pool, we cannot rely on a == b.
66 static int sha_eq(const unsigned char *a, const unsigned char *b)
68 if (!a && !b)
69 return 2;
70 return a && b && hashcmp(a, b) == 0;
74 * Since we want to write the index eventually, we cannot reuse the index
75 * for these (temporary) data.
77 struct stage_data
79 struct
81 unsigned mode;
82 unsigned char sha[20];
83 } stages[4];
84 unsigned processed:1;
87 struct output_buffer
89 struct output_buffer *next;
90 char *str;
93 static struct path_list current_file_set = {NULL, 0, 0, 1};
94 static struct path_list current_directory_set = {NULL, 0, 0, 1};
96 static int call_depth = 0;
97 static int verbosity = 2;
98 static int buffer_output = 1;
99 static int do_progress = 1;
100 static unsigned last_percent;
101 static unsigned merged_cnt;
102 static unsigned total_cnt;
103 static volatile sig_atomic_t progress_update;
104 static struct output_buffer *output_list, *output_end;
106 static int show (int v)
108 return (!call_depth && verbosity >= v) || verbosity >= 5;
111 static void output(int v, const char *fmt, ...)
113 va_list args;
114 va_start(args, fmt);
115 if (buffer_output && show(v)) {
116 struct output_buffer *b = xmalloc(sizeof(*b));
117 nfvasprintf(&b->str, fmt, args);
118 b->next = NULL;
119 if (output_end)
120 output_end->next = b;
121 else
122 output_list = b;
123 output_end = b;
124 } else if (show(v)) {
125 int i;
126 for (i = call_depth; i--;)
127 fputs(" ", stdout);
128 vfprintf(stdout, fmt, args);
129 fputc('\n', stdout);
131 va_end(args);
134 static void flush_output()
136 struct output_buffer *b, *n;
137 for (b = output_list; b; b = n) {
138 int i;
139 for (i = call_depth; i--;)
140 fputs(" ", stdout);
141 fputs(b->str, stdout);
142 fputc('\n', stdout);
143 n = b->next;
144 free(b->str);
145 free(b);
147 output_list = NULL;
148 output_end = NULL;
151 static void output_commit_title(struct commit *commit)
153 int i;
154 flush_output();
155 for (i = call_depth; i--;)
156 fputs(" ", stdout);
157 if (commit->util)
158 printf("virtual %s\n", (char *)commit->util);
159 else {
160 printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
161 if (parse_commit(commit) != 0)
162 printf("(bad commit)\n");
163 else {
164 const char *s;
165 int len;
166 for (s = commit->buffer; *s; s++)
167 if (*s == '\n' && s[1] == '\n') {
168 s += 2;
169 break;
171 for (len = 0; s[len] && '\n' != s[len]; len++)
172 ; /* do nothing */
173 printf("%.*s\n", len, s);
178 static void progress_interval(int signum)
180 progress_update = 1;
183 static void setup_progress_signal(void)
185 struct sigaction sa;
186 struct itimerval v;
188 memset(&sa, 0, sizeof(sa));
189 sa.sa_handler = progress_interval;
190 sigemptyset(&sa.sa_mask);
191 sa.sa_flags = SA_RESTART;
192 sigaction(SIGALRM, &sa, NULL);
194 v.it_interval.tv_sec = 1;
195 v.it_interval.tv_usec = 0;
196 v.it_value = v.it_interval;
197 setitimer(ITIMER_REAL, &v, NULL);
200 static void display_progress()
202 unsigned percent = total_cnt ? merged_cnt * 100 / total_cnt : 0;
203 if (progress_update || percent != last_percent) {
204 fprintf(stderr, "%4u%% (%u/%u) done\r",
205 percent, merged_cnt, total_cnt);
206 progress_update = 0;
207 last_percent = percent;
211 static struct cache_entry *make_cache_entry(unsigned int mode,
212 const unsigned char *sha1, const char *path, int stage, int refresh)
214 int size, len;
215 struct cache_entry *ce;
217 if (!verify_path(path))
218 return NULL;
220 len = strlen(path);
221 size = cache_entry_size(len);
222 ce = xcalloc(1, size);
224 hashcpy(ce->sha1, sha1);
225 memcpy(ce->name, path, len);
226 ce->ce_flags = create_ce_flags(len, stage);
227 ce->ce_mode = create_ce_mode(mode);
229 if (refresh)
230 return refresh_cache_entry(ce, 0);
232 return ce;
235 static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
236 const char *path, int stage, int refresh, int options)
238 struct cache_entry *ce;
239 ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
240 if (!ce)
241 return error("addinfo_cache failed for path '%s'", path);
242 return add_cache_entry(ce, options);
246 * This is a global variable which is used in a number of places but
247 * only written to in the 'merge' function.
249 * index_only == 1 => Don't leave any non-stage 0 entries in the cache and
250 * don't update the working directory.
251 * 0 => Leave unmerged entries in the cache and update
252 * the working directory.
254 static int index_only = 0;
256 static int git_merge_trees(int index_only,
257 struct tree *common,
258 struct tree *head,
259 struct tree *merge)
261 int rc;
262 struct object_list *trees = NULL;
263 struct unpack_trees_options opts;
265 memset(&opts, 0, sizeof(opts));
266 if (index_only)
267 opts.index_only = 1;
268 else
269 opts.update = 1;
270 opts.merge = 1;
271 opts.head_idx = 2;
272 opts.fn = threeway_merge;
274 object_list_append(&common->object, &trees);
275 object_list_append(&head->object, &trees);
276 object_list_append(&merge->object, &trees);
278 rc = unpack_trees(trees, &opts);
279 cache_tree_free(&active_cache_tree);
280 return rc;
283 static int unmerged_index(void)
285 int i;
286 for (i = 0; i < active_nr; i++) {
287 struct cache_entry *ce = active_cache[i];
288 if (ce_stage(ce))
289 return 1;
291 return 0;
294 static struct tree *git_write_tree(void)
296 struct tree *result = NULL;
298 if (unmerged_index()) {
299 int i;
300 output(0, "There are unmerged index entries:");
301 for (i = 0; i < active_nr; i++) {
302 struct cache_entry *ce = active_cache[i];
303 if (ce_stage(ce))
304 output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name);
306 return NULL;
309 if (!active_cache_tree)
310 active_cache_tree = cache_tree();
312 if (!cache_tree_fully_valid(active_cache_tree) &&
313 cache_tree_update(active_cache_tree,
314 active_cache, active_nr, 0, 0) < 0)
315 die("error building trees");
317 result = lookup_tree(active_cache_tree->sha1);
319 return result;
322 static int save_files_dirs(const unsigned char *sha1,
323 const char *base, int baselen, const char *path,
324 unsigned int mode, int stage)
326 int len = strlen(path);
327 char *newpath = xmalloc(baselen + len + 1);
328 memcpy(newpath, base, baselen);
329 memcpy(newpath + baselen, path, len);
330 newpath[baselen + len] = '\0';
332 if (S_ISDIR(mode))
333 path_list_insert(newpath, &current_directory_set);
334 else
335 path_list_insert(newpath, &current_file_set);
336 free(newpath);
338 return READ_TREE_RECURSIVE;
341 static int get_files_dirs(struct tree *tree)
343 int n;
344 if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0)
345 return 0;
346 n = current_file_set.nr + current_directory_set.nr;
347 return n;
351 * Returns a index_entry instance which doesn't have to correspond to
352 * a real cache entry in Git's index.
354 static struct stage_data *insert_stage_data(const char *path,
355 struct tree *o, struct tree *a, struct tree *b,
356 struct path_list *entries)
358 struct path_list_item *item;
359 struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
360 get_tree_entry(o->object.sha1, path,
361 e->stages[1].sha, &e->stages[1].mode);
362 get_tree_entry(a->object.sha1, path,
363 e->stages[2].sha, &e->stages[2].mode);
364 get_tree_entry(b->object.sha1, path,
365 e->stages[3].sha, &e->stages[3].mode);
366 item = path_list_insert(path, entries);
367 item->util = e;
368 return e;
372 * Create a dictionary mapping file names to stage_data objects. The
373 * dictionary contains one entry for every path with a non-zero stage entry.
375 static struct path_list *get_unmerged(void)
377 struct path_list *unmerged = xcalloc(1, sizeof(struct path_list));
378 int i;
380 unmerged->strdup_paths = 1;
381 total_cnt += active_nr;
383 for (i = 0; i < active_nr; i++, merged_cnt++) {
384 struct path_list_item *item;
385 struct stage_data *e;
386 struct cache_entry *ce = active_cache[i];
387 if (do_progress)
388 display_progress();
389 if (!ce_stage(ce))
390 continue;
392 item = path_list_lookup(ce->name, unmerged);
393 if (!item) {
394 item = path_list_insert(ce->name, unmerged);
395 item->util = xcalloc(1, sizeof(struct stage_data));
397 e = item->util;
398 e->stages[ce_stage(ce)].mode = ntohl(ce->ce_mode);
399 hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
402 return unmerged;
405 struct rename
407 struct diff_filepair *pair;
408 struct stage_data *src_entry;
409 struct stage_data *dst_entry;
410 unsigned processed:1;
414 * Get information of all renames which occurred between 'o_tree' and
415 * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
416 * 'b_tree') to be able to associate the correct cache entries with
417 * the rename information. 'tree' is always equal to either a_tree or b_tree.
419 static struct path_list *get_renames(struct tree *tree,
420 struct tree *o_tree,
421 struct tree *a_tree,
422 struct tree *b_tree,
423 struct path_list *entries)
425 int i;
426 struct path_list *renames;
427 struct diff_options opts;
429 renames = xcalloc(1, sizeof(struct path_list));
430 diff_setup(&opts);
431 opts.recursive = 1;
432 opts.detect_rename = DIFF_DETECT_RENAME;
433 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
434 if (diff_setup_done(&opts) < 0)
435 die("diff setup failed");
436 diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
437 diffcore_std(&opts);
438 for (i = 0; i < diff_queued_diff.nr; ++i) {
439 struct path_list_item *item;
440 struct rename *re;
441 struct diff_filepair *pair = diff_queued_diff.queue[i];
442 if (pair->status != 'R') {
443 diff_free_filepair(pair);
444 continue;
446 re = xmalloc(sizeof(*re));
447 re->processed = 0;
448 re->pair = pair;
449 item = path_list_lookup(re->pair->one->path, entries);
450 if (!item)
451 re->src_entry = insert_stage_data(re->pair->one->path,
452 o_tree, a_tree, b_tree, entries);
453 else
454 re->src_entry = item->util;
456 item = path_list_lookup(re->pair->two->path, entries);
457 if (!item)
458 re->dst_entry = insert_stage_data(re->pair->two->path,
459 o_tree, a_tree, b_tree, entries);
460 else
461 re->dst_entry = item->util;
462 item = path_list_insert(pair->one->path, renames);
463 item->util = re;
465 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
466 diff_queued_diff.nr = 0;
467 diff_flush(&opts);
468 return renames;
471 static int update_stages(const char *path, struct diff_filespec *o,
472 struct diff_filespec *a, struct diff_filespec *b,
473 int clear)
475 int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
476 if (clear)
477 if (remove_file_from_cache(path))
478 return -1;
479 if (o)
480 if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
481 return -1;
482 if (a)
483 if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
484 return -1;
485 if (b)
486 if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
487 return -1;
488 return 0;
491 static int remove_path(const char *name)
493 int ret, len;
494 char *slash, *dirs;
496 ret = unlink(name);
497 if (ret)
498 return ret;
499 len = strlen(name);
500 dirs = xmalloc(len+1);
501 memcpy(dirs, name, len);
502 dirs[len] = '\0';
503 while ((slash = strrchr(name, '/'))) {
504 *slash = '\0';
505 len = slash - name;
506 if (rmdir(name) != 0)
507 break;
509 free(dirs);
510 return ret;
513 static int remove_file(int clean, const char *path, int no_wd)
515 int update_cache = index_only || clean;
516 int update_working_directory = !index_only && !no_wd;
518 if (update_cache) {
519 if (remove_file_from_cache(path))
520 return -1;
522 if (update_working_directory) {
523 unlink(path);
524 if (errno != ENOENT || errno != EISDIR)
525 return -1;
526 remove_path(path);
528 return 0;
531 static char *unique_path(const char *path, const char *branch)
533 char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
534 int suffix = 0;
535 struct stat st;
536 char *p = newpath + strlen(path);
537 strcpy(newpath, path);
538 *(p++) = '~';
539 strcpy(p, branch);
540 for (; *p; ++p)
541 if ('/' == *p)
542 *p = '_';
543 while (path_list_has_path(&current_file_set, newpath) ||
544 path_list_has_path(&current_directory_set, newpath) ||
545 lstat(newpath, &st) == 0)
546 sprintf(p, "_%d", suffix++);
548 path_list_insert(newpath, &current_file_set);
549 return newpath;
552 static int mkdir_p(const char *path, unsigned long mode)
554 /* path points to cache entries, so xstrdup before messing with it */
555 char *buf = xstrdup(path);
556 int result = safe_create_leading_directories(buf);
557 free(buf);
558 return result;
561 static void flush_buffer(int fd, const char *buf, unsigned long size)
563 while (size > 0) {
564 long ret = write_in_full(fd, buf, size);
565 if (ret < 0) {
566 /* Ignore epipe */
567 if (errno == EPIPE)
568 break;
569 die("merge-recursive: %s", strerror(errno));
570 } else if (!ret) {
571 die("merge-recursive: disk full?");
573 size -= ret;
574 buf += ret;
578 static void update_file_flags(const unsigned char *sha,
579 unsigned mode,
580 const char *path,
581 int update_cache,
582 int update_wd)
584 if (index_only)
585 update_wd = 0;
587 if (update_wd) {
588 enum object_type type;
589 void *buf;
590 unsigned long size;
592 buf = read_sha1_file(sha, &type, &size);
593 if (!buf)
594 die("cannot read object %s '%s'", sha1_to_hex(sha), path);
595 if (type != OBJ_BLOB)
596 die("blob expected for %s '%s'", sha1_to_hex(sha), path);
598 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
599 int fd;
600 if (mkdir_p(path, 0777))
601 die("failed to create path %s: %s", path, strerror(errno));
602 unlink(path);
603 if (mode & 0100)
604 mode = 0777;
605 else
606 mode = 0666;
607 fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
608 if (fd < 0)
609 die("failed to open %s: %s", path, strerror(errno));
610 flush_buffer(fd, buf, size);
611 close(fd);
612 } else if (S_ISLNK(mode)) {
613 char *lnk = xmalloc(size + 1);
614 memcpy(lnk, buf, size);
615 lnk[size] = '\0';
616 mkdir_p(path, 0777);
617 unlink(path);
618 symlink(lnk, path);
619 free(lnk);
620 } else
621 die("do not know what to do with %06o %s '%s'",
622 mode, sha1_to_hex(sha), path);
624 if (update_cache)
625 add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
628 static void update_file(int clean,
629 const unsigned char *sha,
630 unsigned mode,
631 const char *path)
633 update_file_flags(sha, mode, path, index_only || clean, !index_only);
636 /* Low level file merging, update and removal */
638 struct merge_file_info
640 unsigned char sha[20];
641 unsigned mode;
642 unsigned clean:1,
643 merge:1;
646 static void fill_mm(const unsigned char *sha1, mmfile_t *mm)
648 unsigned long size;
649 enum object_type type;
651 if (!hashcmp(sha1, null_sha1)) {
652 mm->ptr = xstrdup("");
653 mm->size = 0;
654 return;
657 mm->ptr = read_sha1_file(sha1, &type, &size);
658 if (!mm->ptr || type != OBJ_BLOB)
659 die("unable to read blob object %s", sha1_to_hex(sha1));
660 mm->size = size;
663 /* Low-level merge functions */
664 typedef int (*ll_merge_fn)(mmfile_t *orig,
665 mmfile_t *src1, const char *name1,
666 mmfile_t *src2, const char *name2,
667 mmbuffer_t *result);
669 static int ll_xdl_merge(mmfile_t *orig,
670 mmfile_t *src1, const char *name1,
671 mmfile_t *src2, const char *name2,
672 mmbuffer_t *result)
674 xpparam_t xpp;
676 memset(&xpp, 0, sizeof(xpp));
677 return xdl_merge(orig,
678 src1, name1,
679 src2, name2,
680 &xpp, XDL_MERGE_ZEALOUS,
681 result);
684 static int ll_union_merge(mmfile_t *orig,
685 mmfile_t *src1, const char *name1,
686 mmfile_t *src2, const char *name2,
687 mmbuffer_t *result)
689 char *src, *dst;
690 long size;
691 const int marker_size = 7;
693 int status = ll_xdl_merge(orig, src1, NULL, src2, NULL, result);
694 if (status <= 0)
695 return status;
696 size = result->size;
697 src = dst = result->ptr;
698 while (size) {
699 char ch;
700 if ((marker_size < size) &&
701 (*src == '<' || *src == '=' || *src == '>')) {
702 int i;
703 ch = *src;
704 for (i = 0; i < marker_size; i++)
705 if (src[i] != ch)
706 goto not_a_marker;
707 if (src[marker_size] != '\n')
708 goto not_a_marker;
709 src += marker_size + 1;
710 size -= marker_size + 1;
711 continue;
713 not_a_marker:
714 do {
715 ch = *src++;
716 *dst++ = ch;
717 size--;
718 } while (ch != '\n' && size);
720 result->size = dst - result->ptr;
721 return 0;
724 static int ll_binary_merge(mmfile_t *orig,
725 mmfile_t *src1, const char *name1,
726 mmfile_t *src2, const char *name2,
727 mmbuffer_t *result)
730 * The tentative merge result is "ours" for the final round,
731 * or common ancestor for an internal merge. Still return
732 * "conflicted merge" status.
734 mmfile_t *stolen = index_only ? orig : src1;
736 result->ptr = stolen->ptr;
737 result->size = stolen->size;
738 stolen->ptr = NULL;
739 return 1;
742 static struct {
743 const char *name;
744 ll_merge_fn fn;
745 } ll_merge_fns[] = {
746 { "text", ll_xdl_merge },
747 { "binary", ll_binary_merge },
748 { "union", ll_union_merge },
749 { NULL, NULL },
752 static ll_merge_fn find_ll_merge_fn(void *merge_attr)
754 const char *name;
755 int i;
757 if (ATTR_TRUE(merge_attr) || ATTR_UNSET(merge_attr))
758 return ll_xdl_merge;
759 else if (ATTR_FALSE(merge_attr))
760 return ll_binary_merge;
762 /* Otherwise merge_attr may name the merge function */
763 name = merge_attr;
764 for (i = 0; ll_merge_fns[i].name; i++)
765 if (!strcmp(ll_merge_fns[i].name, name))
766 return ll_merge_fns[i].fn;
768 /* default to the 3-way */
769 return ll_xdl_merge;
772 static void *git_path_check_merge(const char *path)
774 static struct git_attr_check attr_merge_check;
776 if (!attr_merge_check.attr)
777 attr_merge_check.attr = git_attr("merge", 5);
779 if (git_checkattr(path, 1, &attr_merge_check))
780 return ATTR__UNSET;
781 return attr_merge_check.value;
784 static int ll_merge(mmbuffer_t *result_buf,
785 struct diff_filespec *o,
786 struct diff_filespec *a,
787 struct diff_filespec *b,
788 const char *branch1,
789 const char *branch2)
791 mmfile_t orig, src1, src2;
792 char *name1, *name2;
793 int merge_status;
794 void *merge_attr;
795 ll_merge_fn fn;
797 name1 = xstrdup(mkpath("%s:%s", branch1, a->path));
798 name2 = xstrdup(mkpath("%s:%s", branch2, b->path));
800 fill_mm(o->sha1, &orig);
801 fill_mm(a->sha1, &src1);
802 fill_mm(b->sha1, &src2);
804 merge_attr = git_path_check_merge(a->path);
805 fn = find_ll_merge_fn(merge_attr);
807 merge_status = fn(&orig, &src1, name1, &src2, name2, result_buf);
809 free(name1);
810 free(name2);
811 free(orig.ptr);
812 free(src1.ptr);
813 free(src2.ptr);
814 return merge_status;
817 static struct merge_file_info merge_file(struct diff_filespec *o,
818 struct diff_filespec *a, struct diff_filespec *b,
819 const char *branch1, const char *branch2)
821 struct merge_file_info result;
822 result.merge = 0;
823 result.clean = 1;
825 if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
826 result.clean = 0;
827 if (S_ISREG(a->mode)) {
828 result.mode = a->mode;
829 hashcpy(result.sha, a->sha1);
830 } else {
831 result.mode = b->mode;
832 hashcpy(result.sha, b->sha1);
834 } else {
835 if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1))
836 result.merge = 1;
838 result.mode = a->mode == o->mode ? b->mode: a->mode;
840 if (sha_eq(a->sha1, o->sha1))
841 hashcpy(result.sha, b->sha1);
842 else if (sha_eq(b->sha1, o->sha1))
843 hashcpy(result.sha, a->sha1);
844 else if (S_ISREG(a->mode)) {
845 mmbuffer_t result_buf;
846 int merge_status;
848 merge_status = ll_merge(&result_buf, o, a, b,
849 branch1, branch2);
851 if ((merge_status < 0) || !result_buf.ptr)
852 die("Failed to execute internal merge");
854 if (write_sha1_file(result_buf.ptr, result_buf.size,
855 blob_type, result.sha))
856 die("Unable to add %s to database",
857 a->path);
859 free(result_buf.ptr);
860 result.clean = (merge_status == 0);
861 } else {
862 if (!(S_ISLNK(a->mode) || S_ISLNK(b->mode)))
863 die("cannot merge modes?");
865 hashcpy(result.sha, a->sha1);
867 if (!sha_eq(a->sha1, b->sha1))
868 result.clean = 0;
872 return result;
875 static void conflict_rename_rename(struct rename *ren1,
876 const char *branch1,
877 struct rename *ren2,
878 const char *branch2)
880 char *del[2];
881 int delp = 0;
882 const char *ren1_dst = ren1->pair->two->path;
883 const char *ren2_dst = ren2->pair->two->path;
884 const char *dst_name1 = ren1_dst;
885 const char *dst_name2 = ren2_dst;
886 if (path_list_has_path(&current_directory_set, ren1_dst)) {
887 dst_name1 = del[delp++] = unique_path(ren1_dst, branch1);
888 output(1, "%s is a directory in %s added as %s instead",
889 ren1_dst, branch2, dst_name1);
890 remove_file(0, ren1_dst, 0);
892 if (path_list_has_path(&current_directory_set, ren2_dst)) {
893 dst_name2 = del[delp++] = unique_path(ren2_dst, branch2);
894 output(1, "%s is a directory in %s added as %s instead",
895 ren2_dst, branch1, dst_name2);
896 remove_file(0, ren2_dst, 0);
898 if (index_only) {
899 remove_file_from_cache(dst_name1);
900 remove_file_from_cache(dst_name2);
902 * Uncomment to leave the conflicting names in the resulting tree
904 * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1);
905 * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2);
907 } else {
908 update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
909 update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
911 while (delp--)
912 free(del[delp]);
915 static void conflict_rename_dir(struct rename *ren1,
916 const char *branch1)
918 char *new_path = unique_path(ren1->pair->two->path, branch1);
919 output(1, "Renamed %s to %s instead", ren1->pair->one->path, new_path);
920 remove_file(0, ren1->pair->two->path, 0);
921 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
922 free(new_path);
925 static void conflict_rename_rename_2(struct rename *ren1,
926 const char *branch1,
927 struct rename *ren2,
928 const char *branch2)
930 char *new_path1 = unique_path(ren1->pair->two->path, branch1);
931 char *new_path2 = unique_path(ren2->pair->two->path, branch2);
932 output(1, "Renamed %s to %s and %s to %s instead",
933 ren1->pair->one->path, new_path1,
934 ren2->pair->one->path, new_path2);
935 remove_file(0, ren1->pair->two->path, 0);
936 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
937 update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
938 free(new_path2);
939 free(new_path1);
942 static int process_renames(struct path_list *a_renames,
943 struct path_list *b_renames,
944 const char *a_branch,
945 const char *b_branch)
947 int clean_merge = 1, i, j;
948 struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
949 const struct rename *sre;
951 for (i = 0; i < a_renames->nr; i++) {
952 sre = a_renames->items[i].util;
953 path_list_insert(sre->pair->two->path, &a_by_dst)->util
954 = sre->dst_entry;
956 for (i = 0; i < b_renames->nr; i++) {
957 sre = b_renames->items[i].util;
958 path_list_insert(sre->pair->two->path, &b_by_dst)->util
959 = sre->dst_entry;
962 for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
963 int compare;
964 char *src;
965 struct path_list *renames1, *renames2, *renames2Dst;
966 struct rename *ren1 = NULL, *ren2 = NULL;
967 const char *branch1, *branch2;
968 const char *ren1_src, *ren1_dst;
970 if (i >= a_renames->nr) {
971 compare = 1;
972 ren2 = b_renames->items[j++].util;
973 } else if (j >= b_renames->nr) {
974 compare = -1;
975 ren1 = a_renames->items[i++].util;
976 } else {
977 compare = strcmp(a_renames->items[i].path,
978 b_renames->items[j].path);
979 if (compare <= 0)
980 ren1 = a_renames->items[i++].util;
981 if (compare >= 0)
982 ren2 = b_renames->items[j++].util;
985 /* TODO: refactor, so that 1/2 are not needed */
986 if (ren1) {
987 renames1 = a_renames;
988 renames2 = b_renames;
989 renames2Dst = &b_by_dst;
990 branch1 = a_branch;
991 branch2 = b_branch;
992 } else {
993 struct rename *tmp;
994 renames1 = b_renames;
995 renames2 = a_renames;
996 renames2Dst = &a_by_dst;
997 branch1 = b_branch;
998 branch2 = a_branch;
999 tmp = ren2;
1000 ren2 = ren1;
1001 ren1 = tmp;
1003 src = ren1->pair->one->path;
1005 ren1->dst_entry->processed = 1;
1006 ren1->src_entry->processed = 1;
1008 if (ren1->processed)
1009 continue;
1010 ren1->processed = 1;
1012 ren1_src = ren1->pair->one->path;
1013 ren1_dst = ren1->pair->two->path;
1015 if (ren2) {
1016 const char *ren2_src = ren2->pair->one->path;
1017 const char *ren2_dst = ren2->pair->two->path;
1018 /* Renamed in 1 and renamed in 2 */
1019 if (strcmp(ren1_src, ren2_src) != 0)
1020 die("ren1.src != ren2.src");
1021 ren2->dst_entry->processed = 1;
1022 ren2->processed = 1;
1023 if (strcmp(ren1_dst, ren2_dst) != 0) {
1024 clean_merge = 0;
1025 output(1, "CONFLICT (rename/rename): "
1026 "Rename \"%s\"->\"%s\" in branch \"%s\" "
1027 "rename \"%s\"->\"%s\" in \"%s\"%s",
1028 src, ren1_dst, branch1,
1029 src, ren2_dst, branch2,
1030 index_only ? " (left unresolved)": "");
1031 if (index_only) {
1032 remove_file_from_cache(src);
1033 update_file(0, ren1->pair->one->sha1,
1034 ren1->pair->one->mode, src);
1036 conflict_rename_rename(ren1, branch1, ren2, branch2);
1037 } else {
1038 struct merge_file_info mfi;
1039 remove_file(1, ren1_src, 1);
1040 mfi = merge_file(ren1->pair->one,
1041 ren1->pair->two,
1042 ren2->pair->two,
1043 branch1,
1044 branch2);
1045 if (mfi.merge || !mfi.clean)
1046 output(1, "Renamed %s->%s", src, ren1_dst);
1048 if (mfi.merge)
1049 output(2, "Auto-merged %s", ren1_dst);
1051 if (!mfi.clean) {
1052 output(1, "CONFLICT (content): merge conflict in %s",
1053 ren1_dst);
1054 clean_merge = 0;
1056 if (!index_only)
1057 update_stages(ren1_dst,
1058 ren1->pair->one,
1059 ren1->pair->two,
1060 ren2->pair->two,
1061 1 /* clear */);
1063 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1065 } else {
1066 /* Renamed in 1, maybe changed in 2 */
1067 struct path_list_item *item;
1068 /* we only use sha1 and mode of these */
1069 struct diff_filespec src_other, dst_other;
1070 int try_merge, stage = a_renames == renames1 ? 3: 2;
1072 remove_file(1, ren1_src, index_only || stage == 3);
1074 hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
1075 src_other.mode = ren1->src_entry->stages[stage].mode;
1076 hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
1077 dst_other.mode = ren1->dst_entry->stages[stage].mode;
1079 try_merge = 0;
1081 if (path_list_has_path(&current_directory_set, ren1_dst)) {
1082 clean_merge = 0;
1083 output(1, "CONFLICT (rename/directory): Renamed %s->%s in %s "
1084 " directory %s added in %s",
1085 ren1_src, ren1_dst, branch1,
1086 ren1_dst, branch2);
1087 conflict_rename_dir(ren1, branch1);
1088 } else if (sha_eq(src_other.sha1, null_sha1)) {
1089 clean_merge = 0;
1090 output(1, "CONFLICT (rename/delete): Renamed %s->%s in %s "
1091 "and deleted in %s",
1092 ren1_src, ren1_dst, branch1,
1093 branch2);
1094 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
1095 } else if (!sha_eq(dst_other.sha1, null_sha1)) {
1096 const char *new_path;
1097 clean_merge = 0;
1098 try_merge = 1;
1099 output(1, "CONFLICT (rename/add): Renamed %s->%s in %s. "
1100 "%s added in %s",
1101 ren1_src, ren1_dst, branch1,
1102 ren1_dst, branch2);
1103 new_path = unique_path(ren1_dst, branch2);
1104 output(1, "Added as %s instead", new_path);
1105 update_file(0, dst_other.sha1, dst_other.mode, new_path);
1106 } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) {
1107 ren2 = item->util;
1108 clean_merge = 0;
1109 ren2->processed = 1;
1110 output(1, "CONFLICT (rename/rename): Renamed %s->%s in %s. "
1111 "Renamed %s->%s in %s",
1112 ren1_src, ren1_dst, branch1,
1113 ren2->pair->one->path, ren2->pair->two->path, branch2);
1114 conflict_rename_rename_2(ren1, branch1, ren2, branch2);
1115 } else
1116 try_merge = 1;
1118 if (try_merge) {
1119 struct diff_filespec *o, *a, *b;
1120 struct merge_file_info mfi;
1121 src_other.path = (char *)ren1_src;
1123 o = ren1->pair->one;
1124 if (a_renames == renames1) {
1125 a = ren1->pair->two;
1126 b = &src_other;
1127 } else {
1128 b = ren1->pair->two;
1129 a = &src_other;
1131 mfi = merge_file(o, a, b,
1132 a_branch, b_branch);
1134 if (mfi.merge || !mfi.clean)
1135 output(1, "Renamed %s => %s", ren1_src, ren1_dst);
1136 if (mfi.merge)
1137 output(2, "Auto-merged %s", ren1_dst);
1138 if (!mfi.clean) {
1139 output(1, "CONFLICT (rename/modify): Merge conflict in %s",
1140 ren1_dst);
1141 clean_merge = 0;
1143 if (!index_only)
1144 update_stages(ren1_dst,
1145 o, a, b, 1);
1147 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1151 path_list_clear(&a_by_dst, 0);
1152 path_list_clear(&b_by_dst, 0);
1154 return clean_merge;
1157 static unsigned char *has_sha(const unsigned char *sha)
1159 return is_null_sha1(sha) ? NULL: (unsigned char *)sha;
1162 /* Per entry merge function */
1163 static int process_entry(const char *path, struct stage_data *entry,
1164 const char *branch1,
1165 const char *branch2)
1168 printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
1169 print_index_entry("\tpath: ", entry);
1171 int clean_merge = 1;
1172 unsigned char *o_sha = has_sha(entry->stages[1].sha);
1173 unsigned char *a_sha = has_sha(entry->stages[2].sha);
1174 unsigned char *b_sha = has_sha(entry->stages[3].sha);
1175 unsigned o_mode = entry->stages[1].mode;
1176 unsigned a_mode = entry->stages[2].mode;
1177 unsigned b_mode = entry->stages[3].mode;
1179 if (o_sha && (!a_sha || !b_sha)) {
1180 /* Case A: Deleted in one */
1181 if ((!a_sha && !b_sha) ||
1182 (sha_eq(a_sha, o_sha) && !b_sha) ||
1183 (!a_sha && sha_eq(b_sha, o_sha))) {
1184 /* Deleted in both or deleted in one and
1185 * unchanged in the other */
1186 if (a_sha)
1187 output(2, "Removed %s", path);
1188 /* do not touch working file if it did not exist */
1189 remove_file(1, path, !a_sha);
1190 } else {
1191 /* Deleted in one and changed in the other */
1192 clean_merge = 0;
1193 if (!a_sha) {
1194 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1195 "and modified in %s. Version %s of %s left in tree.",
1196 path, branch1,
1197 branch2, branch2, path);
1198 update_file(0, b_sha, b_mode, path);
1199 } else {
1200 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1201 "and modified in %s. Version %s of %s left in tree.",
1202 path, branch2,
1203 branch1, branch1, path);
1204 update_file(0, a_sha, a_mode, path);
1208 } else if ((!o_sha && a_sha && !b_sha) ||
1209 (!o_sha && !a_sha && b_sha)) {
1210 /* Case B: Added in one. */
1211 const char *add_branch;
1212 const char *other_branch;
1213 unsigned mode;
1214 const unsigned char *sha;
1215 const char *conf;
1217 if (a_sha) {
1218 add_branch = branch1;
1219 other_branch = branch2;
1220 mode = a_mode;
1221 sha = a_sha;
1222 conf = "file/directory";
1223 } else {
1224 add_branch = branch2;
1225 other_branch = branch1;
1226 mode = b_mode;
1227 sha = b_sha;
1228 conf = "directory/file";
1230 if (path_list_has_path(&current_directory_set, path)) {
1231 const char *new_path = unique_path(path, add_branch);
1232 clean_merge = 0;
1233 output(1, "CONFLICT (%s): There is a directory with name %s in %s. "
1234 "Added %s as %s",
1235 conf, path, other_branch, path, new_path);
1236 remove_file(0, path, 0);
1237 update_file(0, sha, mode, new_path);
1238 } else {
1239 output(2, "Added %s", path);
1240 update_file(1, sha, mode, path);
1242 } else if (a_sha && b_sha) {
1243 /* Case C: Added in both (check for same permissions) and */
1244 /* case D: Modified in both, but differently. */
1245 const char *reason = "content";
1246 struct merge_file_info mfi;
1247 struct diff_filespec o, a, b;
1249 if (!o_sha) {
1250 reason = "add/add";
1251 o_sha = (unsigned char *)null_sha1;
1253 output(2, "Auto-merged %s", path);
1254 o.path = a.path = b.path = (char *)path;
1255 hashcpy(o.sha1, o_sha);
1256 o.mode = o_mode;
1257 hashcpy(a.sha1, a_sha);
1258 a.mode = a_mode;
1259 hashcpy(b.sha1, b_sha);
1260 b.mode = b_mode;
1262 mfi = merge_file(&o, &a, &b,
1263 branch1, branch2);
1265 if (mfi.clean)
1266 update_file(1, mfi.sha, mfi.mode, path);
1267 else {
1268 clean_merge = 0;
1269 output(1, "CONFLICT (%s): Merge conflict in %s",
1270 reason, path);
1272 if (index_only)
1273 update_file(0, mfi.sha, mfi.mode, path);
1274 else
1275 update_file_flags(mfi.sha, mfi.mode, path,
1276 0 /* update_cache */, 1 /* update_working_directory */);
1278 } else
1279 die("Fatal merge failure, shouldn't happen.");
1281 return clean_merge;
1284 static int merge_trees(struct tree *head,
1285 struct tree *merge,
1286 struct tree *common,
1287 const char *branch1,
1288 const char *branch2,
1289 struct tree **result)
1291 int code, clean;
1293 if (subtree_merge) {
1294 merge = shift_tree_object(head, merge);
1295 common = shift_tree_object(head, common);
1298 if (sha_eq(common->object.sha1, merge->object.sha1)) {
1299 output(0, "Already uptodate!");
1300 *result = head;
1301 return 1;
1304 code = git_merge_trees(index_only, common, head, merge);
1306 if (code != 0)
1307 die("merging of trees %s and %s failed",
1308 sha1_to_hex(head->object.sha1),
1309 sha1_to_hex(merge->object.sha1));
1311 if (unmerged_index()) {
1312 struct path_list *entries, *re_head, *re_merge;
1313 int i;
1314 path_list_clear(&current_file_set, 1);
1315 path_list_clear(&current_directory_set, 1);
1316 get_files_dirs(head);
1317 get_files_dirs(merge);
1319 entries = get_unmerged();
1320 re_head = get_renames(head, common, head, merge, entries);
1321 re_merge = get_renames(merge, common, head, merge, entries);
1322 clean = process_renames(re_head, re_merge,
1323 branch1, branch2);
1324 total_cnt += entries->nr;
1325 for (i = 0; i < entries->nr; i++, merged_cnt++) {
1326 const char *path = entries->items[i].path;
1327 struct stage_data *e = entries->items[i].util;
1328 if (!e->processed
1329 && !process_entry(path, e, branch1, branch2))
1330 clean = 0;
1331 if (do_progress)
1332 display_progress();
1335 path_list_clear(re_merge, 0);
1336 path_list_clear(re_head, 0);
1337 path_list_clear(entries, 1);
1340 else
1341 clean = 1;
1343 if (index_only)
1344 *result = git_write_tree();
1346 return clean;
1349 static struct commit_list *reverse_commit_list(struct commit_list *list)
1351 struct commit_list *next = NULL, *current, *backup;
1352 for (current = list; current; current = backup) {
1353 backup = current->next;
1354 current->next = next;
1355 next = current;
1357 return next;
1361 * Merge the commits h1 and h2, return the resulting virtual
1362 * commit object and a flag indicating the cleanness of the merge.
1364 static int merge(struct commit *h1,
1365 struct commit *h2,
1366 const char *branch1,
1367 const char *branch2,
1368 struct commit_list *ca,
1369 struct commit **result)
1371 struct commit_list *iter;
1372 struct commit *merged_common_ancestors;
1373 struct tree *mrtree;
1374 int clean;
1376 if (show(4)) {
1377 output(4, "Merging:");
1378 output_commit_title(h1);
1379 output_commit_title(h2);
1382 if (!ca) {
1383 ca = get_merge_bases(h1, h2, 1);
1384 ca = reverse_commit_list(ca);
1387 if (show(5)) {
1388 output(5, "found %u common ancestor(s):", commit_list_count(ca));
1389 for (iter = ca; iter; iter = iter->next)
1390 output_commit_title(iter->item);
1393 merged_common_ancestors = pop_commit(&ca);
1394 if (merged_common_ancestors == NULL) {
1395 /* if there is no common ancestor, make an empty tree */
1396 struct tree *tree = xcalloc(1, sizeof(struct tree));
1398 tree->object.parsed = 1;
1399 tree->object.type = OBJ_TREE;
1400 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
1401 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1404 for (iter = ca; iter; iter = iter->next) {
1405 call_depth++;
1407 * When the merge fails, the result contains files
1408 * with conflict markers. The cleanness flag is
1409 * ignored, it was never actually used, as result of
1410 * merge_trees has always overwritten it: the committed
1411 * "conflicts" were already resolved.
1413 discard_cache();
1414 merge(merged_common_ancestors, iter->item,
1415 "Temporary merge branch 1",
1416 "Temporary merge branch 2",
1417 NULL,
1418 &merged_common_ancestors);
1419 call_depth--;
1421 if (!merged_common_ancestors)
1422 die("merge returned no commit");
1425 discard_cache();
1426 if (!call_depth) {
1427 read_cache();
1428 index_only = 0;
1429 } else
1430 index_only = 1;
1432 clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree,
1433 branch1, branch2, &mrtree);
1435 if (index_only) {
1436 *result = make_virtual_commit(mrtree, "merged tree");
1437 commit_list_insert(h1, &(*result)->parents);
1438 commit_list_insert(h2, &(*result)->parents->next);
1440 if (!call_depth && do_progress) {
1441 /* Make sure we end at 100% */
1442 if (!total_cnt)
1443 total_cnt = 1;
1444 merged_cnt = total_cnt;
1445 progress_update = 1;
1446 display_progress();
1447 fputc('\n', stderr);
1449 flush_output();
1450 return clean;
1453 static const char *better_branch_name(const char *branch)
1455 static char githead_env[8 + 40 + 1];
1456 char *name;
1458 if (strlen(branch) != 40)
1459 return branch;
1460 sprintf(githead_env, "GITHEAD_%s", branch);
1461 name = getenv(githead_env);
1462 return name ? name : branch;
1465 static struct commit *get_ref(const char *ref)
1467 unsigned char sha1[20];
1468 struct object *object;
1470 if (get_sha1(ref, sha1))
1471 die("Could not resolve ref '%s'", ref);
1472 object = deref_tag(parse_object(sha1), ref, strlen(ref));
1473 if (object->type == OBJ_TREE)
1474 return make_virtual_commit((struct tree*)object,
1475 better_branch_name(ref));
1476 if (object->type != OBJ_COMMIT)
1477 return NULL;
1478 if (parse_commit((struct commit *)object))
1479 die("Could not parse commit '%s'", sha1_to_hex(object->sha1));
1480 return (struct commit *)object;
1483 static int merge_config(const char *var, const char *value)
1485 if (!strcasecmp(var, "merge.verbosity")) {
1486 verbosity = git_config_int(var, value);
1487 return 0;
1489 return git_default_config(var, value);
1492 int main(int argc, char *argv[])
1494 static const char *bases[20];
1495 static unsigned bases_count = 0;
1496 int i, clean;
1497 const char *branch1, *branch2;
1498 struct commit *result, *h1, *h2;
1499 struct commit_list *ca = NULL;
1500 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
1501 int index_fd;
1503 if (argv[0]) {
1504 int namelen = strlen(argv[0]);
1505 if (8 < namelen &&
1506 !strcmp(argv[0] + namelen - 8, "-subtree"))
1507 subtree_merge = 1;
1510 git_config(merge_config);
1511 if (getenv("GIT_MERGE_VERBOSITY"))
1512 verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
1514 if (argc < 4)
1515 die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]);
1517 for (i = 1; i < argc; ++i) {
1518 if (!strcmp(argv[i], "--"))
1519 break;
1520 if (bases_count < sizeof(bases)/sizeof(*bases))
1521 bases[bases_count++] = argv[i];
1523 if (argc - i != 3) /* "--" "<head>" "<remote>" */
1524 die("Not handling anything other than two heads merge.");
1525 if (verbosity >= 5) {
1526 buffer_output = 0;
1527 do_progress = 0;
1529 else
1530 do_progress = isatty(1);
1532 branch1 = argv[++i];
1533 branch2 = argv[++i];
1535 h1 = get_ref(branch1);
1536 h2 = get_ref(branch2);
1538 branch1 = better_branch_name(branch1);
1539 branch2 = better_branch_name(branch2);
1541 if (do_progress)
1542 setup_progress_signal();
1543 if (show(3))
1544 printf("Merging %s with %s\n", branch1, branch2);
1546 index_fd = hold_locked_index(lock, 1);
1548 for (i = 0; i < bases_count; i++) {
1549 struct commit *ancestor = get_ref(bases[i]);
1550 ca = commit_list_insert(ancestor, &ca);
1552 clean = merge(h1, h2, branch1, branch2, ca, &result);
1554 if (active_cache_changed &&
1555 (write_cache(index_fd, active_cache, active_nr) ||
1556 close(index_fd) || commit_locked_index(lock)))
1557 die ("unable to write %s", get_index_file());
1559 return clean ? 0: 1;