Remove case-sensitive file in t3030-merge-recursive.
[git/fastimport.git] / merge-recursive.c
blobcea6c877171d5f9275007c164704f02b52e3a267
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"
19 static int subtree_merge;
21 static struct tree *shift_tree_object(struct tree *one, struct tree *two)
23 unsigned char shifted[20];
26 * NEEDSWORK: this limits the recursion depth to hardcoded
27 * value '2' to avoid excessive overhead.
29 shift_tree(one->object.sha1, two->object.sha1, shifted, 2);
30 if (!hashcmp(two->object.sha1, shifted))
31 return two;
32 return lookup_tree(shifted);
36 * A virtual commit has
37 * - (const char *)commit->util set to the name, and
38 * - *(int *)commit->object.sha1 set to the virtual id.
41 static unsigned commit_list_count(const struct commit_list *l)
43 unsigned c = 0;
44 for (; l; l = l->next )
45 c++;
46 return c;
49 static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
51 struct commit *commit = xcalloc(1, sizeof(struct commit));
52 static unsigned virtual_id = 1;
53 commit->tree = tree;
54 commit->util = (void*)comment;
55 *(int*)commit->object.sha1 = virtual_id++;
56 /* avoid warnings */
57 commit->object.parsed = 1;
58 return commit;
62 * Since we use get_tree_entry(), which does not put the read object into
63 * the object pool, we cannot rely on a == b.
65 static int sha_eq(const unsigned char *a, const unsigned char *b)
67 if (!a && !b)
68 return 2;
69 return a && b && hashcmp(a, b) == 0;
73 * Since we want to write the index eventually, we cannot reuse the index
74 * for these (temporary) data.
76 struct stage_data
78 struct
80 unsigned mode;
81 unsigned char sha[20];
82 } stages[4];
83 unsigned processed:1;
86 struct output_buffer
88 struct output_buffer *next;
89 char *str;
92 static struct path_list current_file_set = {NULL, 0, 0, 1};
93 static struct path_list current_directory_set = {NULL, 0, 0, 1};
95 static int call_depth = 0;
96 static int verbosity = 2;
97 static int buffer_output = 1;
98 static int do_progress = 1;
99 static unsigned last_percent;
100 static unsigned merged_cnt;
101 static unsigned total_cnt;
102 static volatile sig_atomic_t progress_update;
103 static struct output_buffer *output_list, *output_end;
105 static int show (int v)
107 return (!call_depth && verbosity >= v) || verbosity >= 5;
110 static void output(int v, const char *fmt, ...)
112 va_list args;
113 va_start(args, fmt);
114 if (buffer_output && show(v)) {
115 struct output_buffer *b = xmalloc(sizeof(*b));
116 nfvasprintf(&b->str, fmt, args);
117 b->next = NULL;
118 if (output_end)
119 output_end->next = b;
120 else
121 output_list = b;
122 output_end = b;
123 } else if (show(v)) {
124 int i;
125 for (i = call_depth; i--;)
126 fputs(" ", stdout);
127 vfprintf(stdout, fmt, args);
128 fputc('\n', stdout);
130 va_end(args);
133 static void flush_output()
135 struct output_buffer *b, *n;
136 for (b = output_list; b; b = n) {
137 int i;
138 for (i = call_depth; i--;)
139 fputs(" ", stdout);
140 fputs(b->str, stdout);
141 fputc('\n', stdout);
142 n = b->next;
143 free(b->str);
144 free(b);
146 output_list = NULL;
147 output_end = NULL;
150 static void output_commit_title(struct commit *commit)
152 int i;
153 flush_output();
154 for (i = call_depth; i--;)
155 fputs(" ", stdout);
156 if (commit->util)
157 printf("virtual %s\n", (char *)commit->util);
158 else {
159 printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
160 if (parse_commit(commit) != 0)
161 printf("(bad commit)\n");
162 else {
163 const char *s;
164 int len;
165 for (s = commit->buffer; *s; s++)
166 if (*s == '\n' && s[1] == '\n') {
167 s += 2;
168 break;
170 for (len = 0; s[len] && '\n' != s[len]; len++)
171 ; /* do nothing */
172 printf("%.*s\n", len, s);
177 static void progress_interval(int signum)
179 progress_update = 1;
182 static void setup_progress_signal(void)
184 struct sigaction sa;
185 struct itimerval v;
187 memset(&sa, 0, sizeof(sa));
188 sa.sa_handler = progress_interval;
189 sigemptyset(&sa.sa_mask);
190 sa.sa_flags = SA_RESTART;
191 sigaction(SIGALRM, &sa, NULL);
193 v.it_interval.tv_sec = 1;
194 v.it_interval.tv_usec = 0;
195 v.it_value = v.it_interval;
196 setitimer(ITIMER_REAL, &v, NULL);
199 static void display_progress()
201 unsigned percent = total_cnt ? merged_cnt * 100 / total_cnt : 0;
202 if (progress_update || percent != last_percent) {
203 fprintf(stderr, "%4u%% (%u/%u) done\r",
204 percent, merged_cnt, total_cnt);
205 progress_update = 0;
206 last_percent = percent;
210 static struct cache_entry *make_cache_entry(unsigned int mode,
211 const unsigned char *sha1, const char *path, int stage, int refresh)
213 int size, len;
214 struct cache_entry *ce;
216 if (!verify_path(path))
217 return NULL;
219 len = strlen(path);
220 size = cache_entry_size(len);
221 ce = xcalloc(1, size);
223 hashcpy(ce->sha1, sha1);
224 memcpy(ce->name, path, len);
225 ce->ce_flags = create_ce_flags(len, stage);
226 ce->ce_mode = create_ce_mode(mode);
228 if (refresh)
229 return refresh_cache_entry(ce, 0);
231 return ce;
234 static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
235 const char *path, int stage, int refresh, int options)
237 struct cache_entry *ce;
238 ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
239 if (!ce)
240 return error("addinfo_cache failed for path '%s'", path);
241 return add_cache_entry(ce, options);
245 * This is a global variable which is used in a number of places but
246 * only written to in the 'merge' function.
248 * index_only == 1 => Don't leave any non-stage 0 entries in the cache and
249 * don't update the working directory.
250 * 0 => Leave unmerged entries in the cache and update
251 * the working directory.
253 static int index_only = 0;
255 static int git_merge_trees(int index_only,
256 struct tree *common,
257 struct tree *head,
258 struct tree *merge)
260 int rc;
261 struct object_list *trees = NULL;
262 struct unpack_trees_options opts;
264 memset(&opts, 0, sizeof(opts));
265 if (index_only)
266 opts.index_only = 1;
267 else
268 opts.update = 1;
269 opts.merge = 1;
270 opts.head_idx = 2;
271 opts.fn = threeway_merge;
273 object_list_append(&common->object, &trees);
274 object_list_append(&head->object, &trees);
275 object_list_append(&merge->object, &trees);
277 rc = unpack_trees(trees, &opts);
278 cache_tree_free(&active_cache_tree);
279 return rc;
282 static int unmerged_index(void)
284 int i;
285 for (i = 0; i < active_nr; i++) {
286 struct cache_entry *ce = active_cache[i];
287 if (ce_stage(ce))
288 return 1;
290 return 0;
293 static struct tree *git_write_tree(void)
295 struct tree *result = NULL;
297 if (unmerged_index()) {
298 int i;
299 output(0, "There are unmerged index entries:");
300 for (i = 0; i < active_nr; i++) {
301 struct cache_entry *ce = active_cache[i];
302 if (ce_stage(ce))
303 output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name);
305 return NULL;
308 if (!active_cache_tree)
309 active_cache_tree = cache_tree();
311 if (!cache_tree_fully_valid(active_cache_tree) &&
312 cache_tree_update(active_cache_tree,
313 active_cache, active_nr, 0, 0) < 0)
314 die("error building trees");
316 result = lookup_tree(active_cache_tree->sha1);
318 return result;
321 static int save_files_dirs(const unsigned char *sha1,
322 const char *base, int baselen, const char *path,
323 unsigned int mode, int stage)
325 int len = strlen(path);
326 char *newpath = xmalloc(baselen + len + 1);
327 memcpy(newpath, base, baselen);
328 memcpy(newpath + baselen, path, len);
329 newpath[baselen + len] = '\0';
331 if (S_ISDIR(mode))
332 path_list_insert(newpath, &current_directory_set);
333 else
334 path_list_insert(newpath, &current_file_set);
335 free(newpath);
337 return READ_TREE_RECURSIVE;
340 static int get_files_dirs(struct tree *tree)
342 int n;
343 if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0)
344 return 0;
345 n = current_file_set.nr + current_directory_set.nr;
346 return n;
350 * Returns a index_entry instance which doesn't have to correspond to
351 * a real cache entry in Git's index.
353 static struct stage_data *insert_stage_data(const char *path,
354 struct tree *o, struct tree *a, struct tree *b,
355 struct path_list *entries)
357 struct path_list_item *item;
358 struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
359 get_tree_entry(o->object.sha1, path,
360 e->stages[1].sha, &e->stages[1].mode);
361 get_tree_entry(a->object.sha1, path,
362 e->stages[2].sha, &e->stages[2].mode);
363 get_tree_entry(b->object.sha1, path,
364 e->stages[3].sha, &e->stages[3].mode);
365 item = path_list_insert(path, entries);
366 item->util = e;
367 return e;
371 * Create a dictionary mapping file names to stage_data objects. The
372 * dictionary contains one entry for every path with a non-zero stage entry.
374 static struct path_list *get_unmerged(void)
376 struct path_list *unmerged = xcalloc(1, sizeof(struct path_list));
377 int i;
379 unmerged->strdup_paths = 1;
380 total_cnt += active_nr;
382 for (i = 0; i < active_nr; i++, merged_cnt++) {
383 struct path_list_item *item;
384 struct stage_data *e;
385 struct cache_entry *ce = active_cache[i];
386 if (do_progress)
387 display_progress();
388 if (!ce_stage(ce))
389 continue;
391 item = path_list_lookup(ce->name, unmerged);
392 if (!item) {
393 item = path_list_insert(ce->name, unmerged);
394 item->util = xcalloc(1, sizeof(struct stage_data));
396 e = item->util;
397 e->stages[ce_stage(ce)].mode = ntohl(ce->ce_mode);
398 hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
401 return unmerged;
404 struct rename
406 struct diff_filepair *pair;
407 struct stage_data *src_entry;
408 struct stage_data *dst_entry;
409 unsigned processed:1;
413 * Get information of all renames which occurred between 'o_tree' and
414 * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
415 * 'b_tree') to be able to associate the correct cache entries with
416 * the rename information. 'tree' is always equal to either a_tree or b_tree.
418 static struct path_list *get_renames(struct tree *tree,
419 struct tree *o_tree,
420 struct tree *a_tree,
421 struct tree *b_tree,
422 struct path_list *entries)
424 int i;
425 struct path_list *renames;
426 struct diff_options opts;
428 renames = xcalloc(1, sizeof(struct path_list));
429 diff_setup(&opts);
430 opts.recursive = 1;
431 opts.detect_rename = DIFF_DETECT_RENAME;
432 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
433 if (diff_setup_done(&opts) < 0)
434 die("diff setup failed");
435 diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
436 diffcore_std(&opts);
437 for (i = 0; i < diff_queued_diff.nr; ++i) {
438 struct path_list_item *item;
439 struct rename *re;
440 struct diff_filepair *pair = diff_queued_diff.queue[i];
441 if (pair->status != 'R') {
442 diff_free_filepair(pair);
443 continue;
445 re = xmalloc(sizeof(*re));
446 re->processed = 0;
447 re->pair = pair;
448 item = path_list_lookup(re->pair->one->path, entries);
449 if (!item)
450 re->src_entry = insert_stage_data(re->pair->one->path,
451 o_tree, a_tree, b_tree, entries);
452 else
453 re->src_entry = item->util;
455 item = path_list_lookup(re->pair->two->path, entries);
456 if (!item)
457 re->dst_entry = insert_stage_data(re->pair->two->path,
458 o_tree, a_tree, b_tree, entries);
459 else
460 re->dst_entry = item->util;
461 item = path_list_insert(pair->one->path, renames);
462 item->util = re;
464 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
465 diff_queued_diff.nr = 0;
466 diff_flush(&opts);
467 return renames;
470 static int update_stages(const char *path, struct diff_filespec *o,
471 struct diff_filespec *a, struct diff_filespec *b,
472 int clear)
474 int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
475 if (clear)
476 if (remove_file_from_cache(path))
477 return -1;
478 if (o)
479 if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
480 return -1;
481 if (a)
482 if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
483 return -1;
484 if (b)
485 if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
486 return -1;
487 return 0;
490 static int remove_path(const char *name)
492 int ret, len;
493 char *slash, *dirs;
495 ret = unlink(name);
496 if (ret)
497 return ret;
498 len = strlen(name);
499 dirs = xmalloc(len+1);
500 memcpy(dirs, name, len);
501 dirs[len] = '\0';
502 while ((slash = strrchr(name, '/'))) {
503 *slash = '\0';
504 len = slash - name;
505 if (rmdir(name) != 0)
506 break;
508 free(dirs);
509 return ret;
512 static int remove_file(int clean, const char *path, int no_wd)
514 int update_cache = index_only || clean;
515 int update_working_directory = !index_only && !no_wd;
517 if (update_cache) {
518 if (remove_file_from_cache(path))
519 return -1;
521 if (update_working_directory) {
522 unlink(path);
523 if (errno != ENOENT || errno != EISDIR)
524 return -1;
525 remove_path(path);
527 return 0;
530 static char *unique_path(const char *path, const char *branch)
532 char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
533 int suffix = 0;
534 struct stat st;
535 char *p = newpath + strlen(path);
536 strcpy(newpath, path);
537 *(p++) = '~';
538 strcpy(p, branch);
539 for (; *p; ++p)
540 if ('/' == *p)
541 *p = '_';
542 while (path_list_has_path(&current_file_set, newpath) ||
543 path_list_has_path(&current_directory_set, newpath) ||
544 lstat(newpath, &st) == 0)
545 sprintf(p, "_%d", suffix++);
547 path_list_insert(newpath, &current_file_set);
548 return newpath;
551 static int mkdir_p(const char *path, unsigned long mode)
553 /* path points to cache entries, so xstrdup before messing with it */
554 char *buf = xstrdup(path);
555 int result = safe_create_leading_directories(buf);
556 free(buf);
557 return result;
560 static void flush_buffer(int fd, const char *buf, unsigned long size)
562 while (size > 0) {
563 long ret = write_in_full(fd, buf, size);
564 if (ret < 0) {
565 /* Ignore epipe */
566 if (errno == EPIPE)
567 break;
568 die("merge-recursive: %s", strerror(errno));
569 } else if (!ret) {
570 die("merge-recursive: disk full?");
572 size -= ret;
573 buf += ret;
577 static int make_room_for_path(const char *path)
579 int status;
580 const char *msg = "failed to create path '%s'%s";
582 status = mkdir_p(path, 0777);
583 if (status) {
584 if (status == -3) {
585 /* something else exists */
586 error(msg, path, ": perhaps a D/F conflict?");
587 return -1;
589 die(msg, path, "");
592 /* Successful unlink is good.. */
593 if (!unlink(path))
594 return 0;
595 /* .. and so is no existing file */
596 if (errno == ENOENT)
597 return 0;
598 /* .. but not some other error (who really cares what?) */
599 return error(msg, path, ": perhaps a D/F conflict?");
602 static void update_file_flags(const unsigned char *sha,
603 unsigned mode,
604 const char *path,
605 int update_cache,
606 int update_wd)
608 if (index_only)
609 update_wd = 0;
611 if (update_wd) {
612 enum object_type type;
613 void *buf;
614 unsigned long size;
616 buf = read_sha1_file(sha, &type, &size);
617 if (!buf)
618 die("cannot read object %s '%s'", sha1_to_hex(sha), path);
619 if (type != OBJ_BLOB)
620 die("blob expected for %s '%s'", sha1_to_hex(sha), path);
622 if (make_room_for_path(path) < 0) {
623 update_wd = 0;
624 goto update_index;
626 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
627 int fd;
628 if (mode & 0100)
629 mode = 0777;
630 else
631 mode = 0666;
632 fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
633 if (fd < 0)
634 die("failed to open %s: %s", path, strerror(errno));
635 flush_buffer(fd, buf, size);
636 close(fd);
637 } else if (S_ISLNK(mode)) {
638 char *lnk = xmalloc(size + 1);
639 memcpy(lnk, buf, size);
640 lnk[size] = '\0';
641 mkdir_p(path, 0777);
642 unlink(path);
643 symlink(lnk, path);
644 free(lnk);
645 } else
646 die("do not know what to do with %06o %s '%s'",
647 mode, sha1_to_hex(sha), path);
649 update_index:
650 if (update_cache)
651 add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
654 static void update_file(int clean,
655 const unsigned char *sha,
656 unsigned mode,
657 const char *path)
659 update_file_flags(sha, mode, path, index_only || clean, !index_only);
662 /* Low level file merging, update and removal */
664 struct merge_file_info
666 unsigned char sha[20];
667 unsigned mode;
668 unsigned clean:1,
669 merge:1;
672 static void fill_mm(const unsigned char *sha1, mmfile_t *mm)
674 unsigned long size;
675 enum object_type type;
677 if (!hashcmp(sha1, null_sha1)) {
678 mm->ptr = xstrdup("");
679 mm->size = 0;
680 return;
683 mm->ptr = read_sha1_file(sha1, &type, &size);
684 if (!mm->ptr || type != OBJ_BLOB)
685 die("unable to read blob object %s", sha1_to_hex(sha1));
686 mm->size = size;
689 static struct merge_file_info merge_file(struct diff_filespec *o,
690 struct diff_filespec *a, struct diff_filespec *b,
691 const char *branch1, const char *branch2)
693 struct merge_file_info result;
694 result.merge = 0;
695 result.clean = 1;
697 if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
698 result.clean = 0;
699 if (S_ISREG(a->mode)) {
700 result.mode = a->mode;
701 hashcpy(result.sha, a->sha1);
702 } else {
703 result.mode = b->mode;
704 hashcpy(result.sha, b->sha1);
706 } else {
707 if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1))
708 result.merge = 1;
710 result.mode = a->mode == o->mode ? b->mode: a->mode;
712 if (sha_eq(a->sha1, o->sha1))
713 hashcpy(result.sha, b->sha1);
714 else if (sha_eq(b->sha1, o->sha1))
715 hashcpy(result.sha, a->sha1);
716 else if (S_ISREG(a->mode)) {
717 mmfile_t orig, src1, src2;
718 mmbuffer_t result_buf;
719 xpparam_t xpp;
720 char *name1, *name2;
721 int merge_status;
723 name1 = xstrdup(mkpath("%s:%s", branch1, a->path));
724 name2 = xstrdup(mkpath("%s:%s", branch2, b->path));
726 fill_mm(o->sha1, &orig);
727 fill_mm(a->sha1, &src1);
728 fill_mm(b->sha1, &src2);
730 memset(&xpp, 0, sizeof(xpp));
731 merge_status = xdl_merge(&orig,
732 &src1, name1,
733 &src2, name2,
734 &xpp, XDL_MERGE_ZEALOUS,
735 &result_buf);
736 free(name1);
737 free(name2);
738 free(orig.ptr);
739 free(src1.ptr);
740 free(src2.ptr);
742 if ((merge_status < 0) || !result_buf.ptr)
743 die("Failed to execute internal merge");
745 if (write_sha1_file(result_buf.ptr, result_buf.size,
746 blob_type, result.sha))
747 die("Unable to add %s to database",
748 a->path);
750 free(result_buf.ptr);
751 result.clean = (merge_status == 0);
752 } else {
753 if (!(S_ISLNK(a->mode) || S_ISLNK(b->mode)))
754 die("cannot merge modes?");
756 hashcpy(result.sha, a->sha1);
758 if (!sha_eq(a->sha1, b->sha1))
759 result.clean = 0;
763 return result;
766 static void conflict_rename_rename(struct rename *ren1,
767 const char *branch1,
768 struct rename *ren2,
769 const char *branch2)
771 char *del[2];
772 int delp = 0;
773 const char *ren1_dst = ren1->pair->two->path;
774 const char *ren2_dst = ren2->pair->two->path;
775 const char *dst_name1 = ren1_dst;
776 const char *dst_name2 = ren2_dst;
777 if (path_list_has_path(&current_directory_set, ren1_dst)) {
778 dst_name1 = del[delp++] = unique_path(ren1_dst, branch1);
779 output(1, "%s is a directory in %s added as %s instead",
780 ren1_dst, branch2, dst_name1);
781 remove_file(0, ren1_dst, 0);
783 if (path_list_has_path(&current_directory_set, ren2_dst)) {
784 dst_name2 = del[delp++] = unique_path(ren2_dst, branch2);
785 output(1, "%s is a directory in %s added as %s instead",
786 ren2_dst, branch1, dst_name2);
787 remove_file(0, ren2_dst, 0);
789 if (index_only) {
790 remove_file_from_cache(dst_name1);
791 remove_file_from_cache(dst_name2);
793 * Uncomment to leave the conflicting names in the resulting tree
795 * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1);
796 * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2);
798 } else {
799 update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
800 update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
802 while (delp--)
803 free(del[delp]);
806 static void conflict_rename_dir(struct rename *ren1,
807 const char *branch1)
809 char *new_path = unique_path(ren1->pair->two->path, branch1);
810 output(1, "Renamed %s to %s instead", ren1->pair->one->path, new_path);
811 remove_file(0, ren1->pair->two->path, 0);
812 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
813 free(new_path);
816 static void conflict_rename_rename_2(struct rename *ren1,
817 const char *branch1,
818 struct rename *ren2,
819 const char *branch2)
821 char *new_path1 = unique_path(ren1->pair->two->path, branch1);
822 char *new_path2 = unique_path(ren2->pair->two->path, branch2);
823 output(1, "Renamed %s to %s and %s to %s instead",
824 ren1->pair->one->path, new_path1,
825 ren2->pair->one->path, new_path2);
826 remove_file(0, ren1->pair->two->path, 0);
827 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
828 update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
829 free(new_path2);
830 free(new_path1);
833 static int process_renames(struct path_list *a_renames,
834 struct path_list *b_renames,
835 const char *a_branch,
836 const char *b_branch)
838 int clean_merge = 1, i, j;
839 struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
840 const struct rename *sre;
842 for (i = 0; i < a_renames->nr; i++) {
843 sre = a_renames->items[i].util;
844 path_list_insert(sre->pair->two->path, &a_by_dst)->util
845 = sre->dst_entry;
847 for (i = 0; i < b_renames->nr; i++) {
848 sre = b_renames->items[i].util;
849 path_list_insert(sre->pair->two->path, &b_by_dst)->util
850 = sre->dst_entry;
853 for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
854 int compare;
855 char *src;
856 struct path_list *renames1, *renames2, *renames2Dst;
857 struct rename *ren1 = NULL, *ren2 = NULL;
858 const char *branch1, *branch2;
859 const char *ren1_src, *ren1_dst;
861 if (i >= a_renames->nr) {
862 compare = 1;
863 ren2 = b_renames->items[j++].util;
864 } else if (j >= b_renames->nr) {
865 compare = -1;
866 ren1 = a_renames->items[i++].util;
867 } else {
868 compare = strcmp(a_renames->items[i].path,
869 b_renames->items[j].path);
870 if (compare <= 0)
871 ren1 = a_renames->items[i++].util;
872 if (compare >= 0)
873 ren2 = b_renames->items[j++].util;
876 /* TODO: refactor, so that 1/2 are not needed */
877 if (ren1) {
878 renames1 = a_renames;
879 renames2 = b_renames;
880 renames2Dst = &b_by_dst;
881 branch1 = a_branch;
882 branch2 = b_branch;
883 } else {
884 struct rename *tmp;
885 renames1 = b_renames;
886 renames2 = a_renames;
887 renames2Dst = &a_by_dst;
888 branch1 = b_branch;
889 branch2 = a_branch;
890 tmp = ren2;
891 ren2 = ren1;
892 ren1 = tmp;
894 src = ren1->pair->one->path;
896 ren1->dst_entry->processed = 1;
897 ren1->src_entry->processed = 1;
899 if (ren1->processed)
900 continue;
901 ren1->processed = 1;
903 ren1_src = ren1->pair->one->path;
904 ren1_dst = ren1->pair->two->path;
906 if (ren2) {
907 const char *ren2_src = ren2->pair->one->path;
908 const char *ren2_dst = ren2->pair->two->path;
909 /* Renamed in 1 and renamed in 2 */
910 if (strcmp(ren1_src, ren2_src) != 0)
911 die("ren1.src != ren2.src");
912 ren2->dst_entry->processed = 1;
913 ren2->processed = 1;
914 if (strcmp(ren1_dst, ren2_dst) != 0) {
915 clean_merge = 0;
916 output(1, "CONFLICT (rename/rename): "
917 "Rename \"%s\"->\"%s\" in branch \"%s\" "
918 "rename \"%s\"->\"%s\" in \"%s\"%s",
919 src, ren1_dst, branch1,
920 src, ren2_dst, branch2,
921 index_only ? " (left unresolved)": "");
922 if (index_only) {
923 remove_file_from_cache(src);
924 update_file(0, ren1->pair->one->sha1,
925 ren1->pair->one->mode, src);
927 conflict_rename_rename(ren1, branch1, ren2, branch2);
928 } else {
929 struct merge_file_info mfi;
930 remove_file(1, ren1_src, 1);
931 mfi = merge_file(ren1->pair->one,
932 ren1->pair->two,
933 ren2->pair->two,
934 branch1,
935 branch2);
936 if (mfi.merge || !mfi.clean)
937 output(1, "Renamed %s->%s", src, ren1_dst);
939 if (mfi.merge)
940 output(2, "Auto-merged %s", ren1_dst);
942 if (!mfi.clean) {
943 output(1, "CONFLICT (content): merge conflict in %s",
944 ren1_dst);
945 clean_merge = 0;
947 if (!index_only)
948 update_stages(ren1_dst,
949 ren1->pair->one,
950 ren1->pair->two,
951 ren2->pair->two,
952 1 /* clear */);
954 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
956 } else {
957 /* Renamed in 1, maybe changed in 2 */
958 struct path_list_item *item;
959 /* we only use sha1 and mode of these */
960 struct diff_filespec src_other, dst_other;
961 int try_merge, stage = a_renames == renames1 ? 3: 2;
963 remove_file(1, ren1_src, index_only || stage == 3);
965 hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
966 src_other.mode = ren1->src_entry->stages[stage].mode;
967 hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
968 dst_other.mode = ren1->dst_entry->stages[stage].mode;
970 try_merge = 0;
972 if (path_list_has_path(&current_directory_set, ren1_dst)) {
973 clean_merge = 0;
974 output(1, "CONFLICT (rename/directory): Renamed %s->%s in %s "
975 " directory %s added in %s",
976 ren1_src, ren1_dst, branch1,
977 ren1_dst, branch2);
978 conflict_rename_dir(ren1, branch1);
979 } else if (sha_eq(src_other.sha1, null_sha1)) {
980 clean_merge = 0;
981 output(1, "CONFLICT (rename/delete): Renamed %s->%s in %s "
982 "and deleted in %s",
983 ren1_src, ren1_dst, branch1,
984 branch2);
985 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
986 } else if (!sha_eq(dst_other.sha1, null_sha1)) {
987 const char *new_path;
988 clean_merge = 0;
989 try_merge = 1;
990 output(1, "CONFLICT (rename/add): Renamed %s->%s in %s. "
991 "%s added in %s",
992 ren1_src, ren1_dst, branch1,
993 ren1_dst, branch2);
994 new_path = unique_path(ren1_dst, branch2);
995 output(1, "Added as %s instead", new_path);
996 update_file(0, dst_other.sha1, dst_other.mode, new_path);
997 } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) {
998 ren2 = item->util;
999 clean_merge = 0;
1000 ren2->processed = 1;
1001 output(1, "CONFLICT (rename/rename): Renamed %s->%s in %s. "
1002 "Renamed %s->%s in %s",
1003 ren1_src, ren1_dst, branch1,
1004 ren2->pair->one->path, ren2->pair->two->path, branch2);
1005 conflict_rename_rename_2(ren1, branch1, ren2, branch2);
1006 } else
1007 try_merge = 1;
1009 if (try_merge) {
1010 struct diff_filespec *o, *a, *b;
1011 struct merge_file_info mfi;
1012 src_other.path = (char *)ren1_src;
1014 o = ren1->pair->one;
1015 if (a_renames == renames1) {
1016 a = ren1->pair->two;
1017 b = &src_other;
1018 } else {
1019 b = ren1->pair->two;
1020 a = &src_other;
1022 mfi = merge_file(o, a, b,
1023 a_branch, b_branch);
1025 if (mfi.merge || !mfi.clean)
1026 output(1, "Renamed %s => %s", ren1_src, ren1_dst);
1027 if (mfi.merge)
1028 output(2, "Auto-merged %s", ren1_dst);
1029 if (!mfi.clean) {
1030 output(1, "CONFLICT (rename/modify): Merge conflict in %s",
1031 ren1_dst);
1032 clean_merge = 0;
1034 if (!index_only)
1035 update_stages(ren1_dst,
1036 o, a, b, 1);
1038 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
1042 path_list_clear(&a_by_dst, 0);
1043 path_list_clear(&b_by_dst, 0);
1045 return clean_merge;
1048 static unsigned char *stage_sha(const unsigned char *sha, unsigned mode)
1050 return (is_null_sha1(sha) || mode == 0) ? NULL: (unsigned char *)sha;
1053 /* Per entry merge function */
1054 static int process_entry(const char *path, struct stage_data *entry,
1055 const char *branch1,
1056 const char *branch2)
1059 printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
1060 print_index_entry("\tpath: ", entry);
1062 int clean_merge = 1;
1063 unsigned o_mode = entry->stages[1].mode;
1064 unsigned a_mode = entry->stages[2].mode;
1065 unsigned b_mode = entry->stages[3].mode;
1066 unsigned char *o_sha = stage_sha(entry->stages[1].sha, o_mode);
1067 unsigned char *a_sha = stage_sha(entry->stages[2].sha, a_mode);
1068 unsigned char *b_sha = stage_sha(entry->stages[3].sha, b_mode);
1070 if (o_sha && (!a_sha || !b_sha)) {
1071 /* Case A: Deleted in one */
1072 if ((!a_sha && !b_sha) ||
1073 (sha_eq(a_sha, o_sha) && !b_sha) ||
1074 (!a_sha && sha_eq(b_sha, o_sha))) {
1075 /* Deleted in both or deleted in one and
1076 * unchanged in the other */
1077 if (a_sha)
1078 output(2, "Removed %s", path);
1079 /* do not touch working file if it did not exist */
1080 remove_file(1, path, !a_sha);
1081 } else {
1082 /* Deleted in one and changed in the other */
1083 clean_merge = 0;
1084 if (!a_sha) {
1085 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1086 "and modified in %s. Version %s of %s left in tree.",
1087 path, branch1,
1088 branch2, branch2, path);
1089 update_file(0, b_sha, b_mode, path);
1090 } else {
1091 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1092 "and modified in %s. Version %s of %s left in tree.",
1093 path, branch2,
1094 branch1, branch1, path);
1095 update_file(0, a_sha, a_mode, path);
1099 } else if ((!o_sha && a_sha && !b_sha) ||
1100 (!o_sha && !a_sha && b_sha)) {
1101 /* Case B: Added in one. */
1102 const char *add_branch;
1103 const char *other_branch;
1104 unsigned mode;
1105 const unsigned char *sha;
1106 const char *conf;
1108 if (a_sha) {
1109 add_branch = branch1;
1110 other_branch = branch2;
1111 mode = a_mode;
1112 sha = a_sha;
1113 conf = "file/directory";
1114 } else {
1115 add_branch = branch2;
1116 other_branch = branch1;
1117 mode = b_mode;
1118 sha = b_sha;
1119 conf = "directory/file";
1121 if (path_list_has_path(&current_directory_set, path)) {
1122 const char *new_path = unique_path(path, add_branch);
1123 clean_merge = 0;
1124 output(1, "CONFLICT (%s): There is a directory with name %s in %s. "
1125 "Added %s as %s",
1126 conf, path, other_branch, path, new_path);
1127 remove_file(0, path, 0);
1128 update_file(0, sha, mode, new_path);
1129 } else {
1130 output(2, "Added %s", path);
1131 update_file(1, sha, mode, path);
1133 } else if (a_sha && b_sha) {
1134 /* Case C: Added in both (check for same permissions) and */
1135 /* case D: Modified in both, but differently. */
1136 const char *reason = "content";
1137 struct merge_file_info mfi;
1138 struct diff_filespec o, a, b;
1140 if (!o_sha) {
1141 reason = "add/add";
1142 o_sha = (unsigned char *)null_sha1;
1144 output(2, "Auto-merged %s", path);
1145 o.path = a.path = b.path = (char *)path;
1146 hashcpy(o.sha1, o_sha);
1147 o.mode = o_mode;
1148 hashcpy(a.sha1, a_sha);
1149 a.mode = a_mode;
1150 hashcpy(b.sha1, b_sha);
1151 b.mode = b_mode;
1153 mfi = merge_file(&o, &a, &b,
1154 branch1, branch2);
1156 if (mfi.clean)
1157 update_file(1, mfi.sha, mfi.mode, path);
1158 else {
1159 clean_merge = 0;
1160 output(1, "CONFLICT (%s): Merge conflict in %s",
1161 reason, path);
1163 if (index_only)
1164 update_file(0, mfi.sha, mfi.mode, path);
1165 else
1166 update_file_flags(mfi.sha, mfi.mode, path,
1167 0 /* update_cache */, 1 /* update_working_directory */);
1169 } else if (!o_sha && !a_sha && !b_sha) {
1171 * this entry was deleted altogether. a_mode == 0 means
1172 * we had that path and want to actively remove it.
1174 remove_file(1, path, !a_mode);
1175 } else
1176 die("Fatal merge failure, shouldn't happen.");
1178 return clean_merge;
1181 static int merge_trees(struct tree *head,
1182 struct tree *merge,
1183 struct tree *common,
1184 const char *branch1,
1185 const char *branch2,
1186 struct tree **result)
1188 int code, clean;
1190 if (subtree_merge) {
1191 merge = shift_tree_object(head, merge);
1192 common = shift_tree_object(head, common);
1195 if (sha_eq(common->object.sha1, merge->object.sha1)) {
1196 output(0, "Already uptodate!");
1197 *result = head;
1198 return 1;
1201 code = git_merge_trees(index_only, common, head, merge);
1203 if (code != 0)
1204 die("merging of trees %s and %s failed",
1205 sha1_to_hex(head->object.sha1),
1206 sha1_to_hex(merge->object.sha1));
1208 if (unmerged_index()) {
1209 struct path_list *entries, *re_head, *re_merge;
1210 int i;
1211 path_list_clear(&current_file_set, 1);
1212 path_list_clear(&current_directory_set, 1);
1213 get_files_dirs(head);
1214 get_files_dirs(merge);
1216 entries = get_unmerged();
1217 re_head = get_renames(head, common, head, merge, entries);
1218 re_merge = get_renames(merge, common, head, merge, entries);
1219 clean = process_renames(re_head, re_merge,
1220 branch1, branch2);
1221 total_cnt += entries->nr;
1222 for (i = 0; i < entries->nr; i++, merged_cnt++) {
1223 const char *path = entries->items[i].path;
1224 struct stage_data *e = entries->items[i].util;
1225 if (!e->processed
1226 && !process_entry(path, e, branch1, branch2))
1227 clean = 0;
1228 if (do_progress)
1229 display_progress();
1232 path_list_clear(re_merge, 0);
1233 path_list_clear(re_head, 0);
1234 path_list_clear(entries, 1);
1237 else
1238 clean = 1;
1240 if (index_only)
1241 *result = git_write_tree();
1243 return clean;
1246 static struct commit_list *reverse_commit_list(struct commit_list *list)
1248 struct commit_list *next = NULL, *current, *backup;
1249 for (current = list; current; current = backup) {
1250 backup = current->next;
1251 current->next = next;
1252 next = current;
1254 return next;
1258 * Merge the commits h1 and h2, return the resulting virtual
1259 * commit object and a flag indicating the cleanness of the merge.
1261 static int merge(struct commit *h1,
1262 struct commit *h2,
1263 const char *branch1,
1264 const char *branch2,
1265 struct commit_list *ca,
1266 struct commit **result)
1268 struct commit_list *iter;
1269 struct commit *merged_common_ancestors;
1270 struct tree *mrtree;
1271 int clean;
1273 if (show(4)) {
1274 output(4, "Merging:");
1275 output_commit_title(h1);
1276 output_commit_title(h2);
1279 if (!ca) {
1280 ca = get_merge_bases(h1, h2, 1);
1281 ca = reverse_commit_list(ca);
1284 if (show(5)) {
1285 output(5, "found %u common ancestor(s):", commit_list_count(ca));
1286 for (iter = ca; iter; iter = iter->next)
1287 output_commit_title(iter->item);
1290 merged_common_ancestors = pop_commit(&ca);
1291 if (merged_common_ancestors == NULL) {
1292 /* if there is no common ancestor, make an empty tree */
1293 struct tree *tree = xcalloc(1, sizeof(struct tree));
1295 tree->object.parsed = 1;
1296 tree->object.type = OBJ_TREE;
1297 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
1298 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1301 for (iter = ca; iter; iter = iter->next) {
1302 call_depth++;
1304 * When the merge fails, the result contains files
1305 * with conflict markers. The cleanness flag is
1306 * ignored, it was never actually used, as result of
1307 * merge_trees has always overwritten it: the committed
1308 * "conflicts" were already resolved.
1310 discard_cache();
1311 merge(merged_common_ancestors, iter->item,
1312 "Temporary merge branch 1",
1313 "Temporary merge branch 2",
1314 NULL,
1315 &merged_common_ancestors);
1316 call_depth--;
1318 if (!merged_common_ancestors)
1319 die("merge returned no commit");
1322 discard_cache();
1323 if (!call_depth) {
1324 read_cache();
1325 index_only = 0;
1326 } else
1327 index_only = 1;
1329 clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree,
1330 branch1, branch2, &mrtree);
1332 if (index_only) {
1333 *result = make_virtual_commit(mrtree, "merged tree");
1334 commit_list_insert(h1, &(*result)->parents);
1335 commit_list_insert(h2, &(*result)->parents->next);
1337 if (!call_depth && do_progress) {
1338 /* Make sure we end at 100% */
1339 if (!total_cnt)
1340 total_cnt = 1;
1341 merged_cnt = total_cnt;
1342 progress_update = 1;
1343 display_progress();
1344 fputc('\n', stderr);
1346 flush_output();
1347 return clean;
1350 static const char *better_branch_name(const char *branch)
1352 static char githead_env[8 + 40 + 1];
1353 char *name;
1355 if (strlen(branch) != 40)
1356 return branch;
1357 sprintf(githead_env, "GITHEAD_%s", branch);
1358 name = getenv(githead_env);
1359 return name ? name : branch;
1362 static struct commit *get_ref(const char *ref)
1364 unsigned char sha1[20];
1365 struct object *object;
1367 if (get_sha1(ref, sha1))
1368 die("Could not resolve ref '%s'", ref);
1369 object = deref_tag(parse_object(sha1), ref, strlen(ref));
1370 if (object->type == OBJ_TREE)
1371 return make_virtual_commit((struct tree*)object,
1372 better_branch_name(ref));
1373 if (object->type != OBJ_COMMIT)
1374 return NULL;
1375 if (parse_commit((struct commit *)object))
1376 die("Could not parse commit '%s'", sha1_to_hex(object->sha1));
1377 return (struct commit *)object;
1380 static int merge_config(const char *var, const char *value)
1382 if (!strcasecmp(var, "merge.verbosity")) {
1383 verbosity = git_config_int(var, value);
1384 return 0;
1386 return git_default_config(var, value);
1389 int main(int argc, char *argv[])
1391 static const char *bases[20];
1392 static unsigned bases_count = 0;
1393 int i, clean;
1394 const char *branch1, *branch2;
1395 struct commit *result, *h1, *h2;
1396 struct commit_list *ca = NULL;
1397 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
1398 int index_fd;
1400 if (argv[0]) {
1401 int namelen = strlen(argv[0]);
1402 if (8 < namelen &&
1403 !strcmp(argv[0] + namelen - 8, "-subtree"))
1404 subtree_merge = 1;
1407 git_config(merge_config);
1408 if (getenv("GIT_MERGE_VERBOSITY"))
1409 verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
1411 if (argc < 4)
1412 die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]);
1414 for (i = 1; i < argc; ++i) {
1415 if (!strcmp(argv[i], "--"))
1416 break;
1417 if (bases_count < sizeof(bases)/sizeof(*bases))
1418 bases[bases_count++] = argv[i];
1420 if (argc - i != 3) /* "--" "<head>" "<remote>" */
1421 die("Not handling anything other than two heads merge.");
1422 if (verbosity >= 5) {
1423 buffer_output = 0;
1424 do_progress = 0;
1426 else
1427 do_progress = isatty(1);
1429 branch1 = argv[++i];
1430 branch2 = argv[++i];
1432 h1 = get_ref(branch1);
1433 h2 = get_ref(branch2);
1435 branch1 = better_branch_name(branch1);
1436 branch2 = better_branch_name(branch2);
1438 if (do_progress)
1439 setup_progress_signal();
1440 if (show(3))
1441 printf("Merging %s with %s\n", branch1, branch2);
1443 index_fd = hold_locked_index(lock, 1);
1445 for (i = 0; i < bases_count; i++) {
1446 struct commit *ancestor = get_ref(bases[i]);
1447 ca = commit_list_insert(ancestor, &ca);
1449 clean = merge(h1, h2, branch1, branch2, ca, &result);
1451 if (active_cache_changed &&
1452 (write_cache(index_fd, active_cache, active_nr) ||
1453 close(index_fd) || commit_locked_index(lock)))
1454 die ("unable to write %s", get_index_file());
1456 return clean ? 0: 1;