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 "tag.h"
14#include "unpack-trees.h"
15#include "path-list.h"
16#include "xdiff-interface.h"
17#include "ll-merge.h"
18
19static int subtree_merge;
20
21static struct tree *shift_tree_object(struct tree *one, struct tree *two)
22{
23 unsigned char shifted[20];
24
25 /*
26 * NEEDSWORK: this limits the recursion depth to hardcoded
27 * value '2' to avoid excessive overhead.
28 */
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);
33}
34
35/*
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.
39 */
40
41static unsigned commit_list_count(const struct commit_list *l)
42{
43 unsigned c = 0;
44 for (; l; l = l->next )
45 c++;
46 return c;
47}
48
49static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
50{
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;
59}
60
61/*
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.
64 */
65static int sha_eq(const unsigned char *a, const unsigned char *b)
66{
67 if (!a && !b)
68 return 2;
69 return a && b && hashcmp(a, b) == 0;
70}
71
72/*
73 * Since we want to write the index eventually, we cannot reuse the index
74 * for these (temporary) data.
75 */
76struct stage_data
77{
78 struct
79 {
80 unsigned mode;
81 unsigned char sha[20];
82 } stages[4];
83 unsigned processed:1;
84};
85
86static struct path_list current_file_set = {NULL, 0, 0, 1};
87static struct path_list current_directory_set = {NULL, 0, 0, 1};
88
89static int call_depth = 0;
90static int verbosity = 2;
91static int rename_limit = -1;
92static int buffer_output = 1;
93static struct strbuf obuf = STRBUF_INIT;
94
95static int show(int v)
96{
97 return (!call_depth && verbosity >= v) || verbosity >= 5;
98}
99
100static void flush_output(void)
101{
102 if (obuf.len) {
103 fputs(obuf.buf, stdout);
104 strbuf_reset(&obuf);
105 }
106}
107
108static void output(int v, const char *fmt, ...)
109{
110 int len;
111 va_list ap;
112
113 if (!show(v))
114 return;
115
116 strbuf_grow(&obuf, call_depth * 2 + 2);
117 memset(obuf.buf + obuf.len, ' ', call_depth * 2);
118 strbuf_setlen(&obuf, obuf.len + call_depth * 2);
119
120 va_start(ap, fmt);
121 len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap);
122 va_end(ap);
123
124 if (len < 0)
125 len = 0;
126 if (len >= strbuf_avail(&obuf)) {
127 strbuf_grow(&obuf, len + 2);
128 va_start(ap, fmt);
129 len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap);
130 va_end(ap);
131 if (len >= strbuf_avail(&obuf)) {
132 die("this should not happen, your snprintf is broken");
133 }
134 }
135 strbuf_setlen(&obuf, obuf.len + len);
136 strbuf_add(&obuf, "\n", 1);
137 if (!buffer_output)
138 flush_output();
139}
140
141static void output_commit_title(struct commit *commit)
142{
143 int i;
144 flush_output();
145 for (i = call_depth; i--;)
146 fputs(" ", stdout);
147 if (commit->util)
148 printf("virtual %s\n", (char *)commit->util);
149 else {
150 printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
151 if (parse_commit(commit) != 0)
152 printf("(bad commit)\n");
153 else {
154 const char *s;
155 int len;
156 for (s = commit->buffer; *s; s++)
157 if (*s == '\n' && s[1] == '\n') {
158 s += 2;
159 break;
160 }
161 for (len = 0; s[len] && '\n' != s[len]; len++)
162 ; /* do nothing */
163 printf("%.*s\n", len, s);
164 }
165 }
166}
167
168static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
169 const char *path, int stage, int refresh, int options)
170{
171 struct cache_entry *ce;
172 ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
173 if (!ce)
174 return error("addinfo_cache failed for path '%s'", path);
175 return add_cache_entry(ce, options);
176}
177
178/*
179 * This is a global variable which is used in a number of places but
180 * only written to in the 'merge' function.
181 *
182 * index_only == 1 => Don't leave any non-stage 0 entries in the cache and
183 * don't update the working directory.
184 * 0 => Leave unmerged entries in the cache and update
185 * the working directory.
186 */
187static int index_only = 0;
188
189static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
190{
191 parse_tree(tree);
192 init_tree_desc(desc, tree->buffer, tree->size);
193}
194
195static int git_merge_trees(int index_only,
196 struct tree *common,
197 struct tree *head,
198 struct tree *merge)
199{
200 int rc;
201 struct tree_desc t[3];
202 struct unpack_trees_options opts;
203
204 memset(&opts, 0, sizeof(opts));
205 if (index_only)
206 opts.index_only = 1;
207 else
208 opts.update = 1;
209 opts.merge = 1;
210 opts.head_idx = 2;
211 opts.fn = threeway_merge;
212
213 init_tree_desc_from_tree(t+0, common);
214 init_tree_desc_from_tree(t+1, head);
215 init_tree_desc_from_tree(t+2, merge);
216
217 rc = unpack_trees(3, t, &opts);
218 cache_tree_free(&active_cache_tree);
219 return rc;
220}
221
222static int unmerged_index(void)
223{
224 int i;
225 for (i = 0; i < active_nr; i++) {
226 struct cache_entry *ce = active_cache[i];
227 if (ce_stage(ce))
228 return 1;
229 }
230 return 0;
231}
232
233static struct tree *git_write_tree(void)
234{
235 struct tree *result = NULL;
236
237 if (unmerged_index()) {
238 int i;
239 output(0, "There are unmerged index entries:");
240 for (i = 0; i < active_nr; i++) {
241 struct cache_entry *ce = active_cache[i];
242 if (ce_stage(ce))
243 output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name);
244 }
245 return NULL;
246 }
247
248 if (!active_cache_tree)
249 active_cache_tree = cache_tree();
250
251 if (!cache_tree_fully_valid(active_cache_tree) &&
252 cache_tree_update(active_cache_tree,
253 active_cache, active_nr, 0, 0) < 0)
254 die("error building trees");
255
256 result = lookup_tree(active_cache_tree->sha1);
257
258 return result;
259}
260
261static int save_files_dirs(const unsigned char *sha1,
262 const char *base, int baselen, const char *path,
263 unsigned int mode, int stage)
264{
265 int len = strlen(path);
266 char *newpath = xmalloc(baselen + len + 1);
267 memcpy(newpath, base, baselen);
268 memcpy(newpath + baselen, path, len);
269 newpath[baselen + len] = '\0';
270
271 if (S_ISDIR(mode))
272 path_list_insert(newpath, ¤t_directory_set);
273 else
274 path_list_insert(newpath, ¤t_file_set);
275 free(newpath);
276
277 return READ_TREE_RECURSIVE;
278}
279
280static int get_files_dirs(struct tree *tree)
281{
282 int n;
283 if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0)
284 return 0;
285 n = current_file_set.nr + current_directory_set.nr;
286 return n;
287}
288
289/*
290 * Returns an index_entry instance which doesn't have to correspond to
291 * a real cache entry in Git's index.
292 */
293static struct stage_data *insert_stage_data(const char *path,
294 struct tree *o, struct tree *a, struct tree *b,
295 struct path_list *entries)
296{
297 struct path_list_item *item;
298 struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
299 get_tree_entry(o->object.sha1, path,
300 e->stages[1].sha, &e->stages[1].mode);
301 get_tree_entry(a->object.sha1, path,
302 e->stages[2].sha, &e->stages[2].mode);
303 get_tree_entry(b->object.sha1, path,
304 e->stages[3].sha, &e->stages[3].mode);
305 item = path_list_insert(path, entries);
306 item->util = e;
307 return e;
308}
309
310/*
311 * Create a dictionary mapping file names to stage_data objects. The
312 * dictionary contains one entry for every path with a non-zero stage entry.
313 */
314static struct path_list *get_unmerged(void)
315{
316 struct path_list *unmerged = xcalloc(1, sizeof(struct path_list));
317 int i;
318
319 unmerged->strdup_paths = 1;
320
321 for (i = 0; i < active_nr; i++) {
322 struct path_list_item *item;
323 struct stage_data *e;
324 struct cache_entry *ce = active_cache[i];
325 if (!ce_stage(ce))
326 continue;
327
328 item = path_list_lookup(ce->name, unmerged);
329 if (!item) {
330 item = path_list_insert(ce->name, unmerged);
331 item->util = xcalloc(1, sizeof(struct stage_data));
332 }
333 e = item->util;
334 e->stages[ce_stage(ce)].mode = ce->ce_mode;
335 hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
336 }
337
338 return unmerged;
339}
340
341struct rename
342{
343 struct diff_filepair *pair;
344 struct stage_data *src_entry;
345 struct stage_data *dst_entry;
346 unsigned processed:1;
347};
348
349/*
350 * Get information of all renames which occurred between 'o_tree' and
351 * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
352 * 'b_tree') to be able to associate the correct cache entries with
353 * the rename information. 'tree' is always equal to either a_tree or b_tree.
354 */
355static struct path_list *get_renames(struct tree *tree,
356 struct tree *o_tree,
357 struct tree *a_tree,
358 struct tree *b_tree,
359 struct path_list *entries)
360{
361 int i;
362 struct path_list *renames;
363 struct diff_options opts;
364
365 renames = xcalloc(1, sizeof(struct path_list));
366 diff_setup(&opts);
367 DIFF_OPT_SET(&opts, RECURSIVE);
368 opts.detect_rename = DIFF_DETECT_RENAME;
369 opts.rename_limit = rename_limit;
370 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
371 if (diff_setup_done(&opts) < 0)
372 die("diff setup failed");
373 diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
374 diffcore_std(&opts);
375 for (i = 0; i < diff_queued_diff.nr; ++i) {
376 struct path_list_item *item;
377 struct rename *re;
378 struct diff_filepair *pair = diff_queued_diff.queue[i];
379 if (pair->status != 'R') {
380 diff_free_filepair(pair);
381 continue;
382 }
383 re = xmalloc(sizeof(*re));
384 re->processed = 0;
385 re->pair = pair;
386 item = path_list_lookup(re->pair->one->path, entries);
387 if (!item)
388 re->src_entry = insert_stage_data(re->pair->one->path,
389 o_tree, a_tree, b_tree, entries);
390 else
391 re->src_entry = item->util;
392
393 item = path_list_lookup(re->pair->two->path, entries);
394 if (!item)
395 re->dst_entry = insert_stage_data(re->pair->two->path,
396 o_tree, a_tree, b_tree, entries);
397 else
398 re->dst_entry = item->util;
399 item = path_list_insert(pair->one->path, renames);
400 item->util = re;
401 }
402 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
403 diff_queued_diff.nr = 0;
404 diff_flush(&opts);
405 return renames;
406}
407
408static int update_stages(const char *path, struct diff_filespec *o,
409 struct diff_filespec *a, struct diff_filespec *b,
410 int clear)
411{
412 int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
413 if (clear)
414 if (remove_file_from_cache(path))
415 return -1;
416 if (o)
417 if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
418 return -1;
419 if (a)
420 if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
421 return -1;
422 if (b)
423 if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
424 return -1;
425 return 0;
426}
427
428static int remove_path(const char *name)
429{
430 int ret;
431 char *slash, *dirs;
432
433 ret = unlink(name);
434 if (ret)
435 return ret;
436 dirs = xstrdup(name);
437 while ((slash = strrchr(name, '/'))) {
438 *slash = '\0';
439 if (rmdir(name) != 0)
440 break;
441 }
442 free(dirs);
443 return ret;
444}
445
446static int remove_file(int clean, const char *path, int no_wd)
447{
448 int update_cache = index_only || clean;
449 int update_working_directory = !index_only && !no_wd;
450
451 if (update_cache) {
452 if (remove_file_from_cache(path))
453 return -1;
454 }
455 if (update_working_directory) {
456 unlink(path);
457 if (errno != ENOENT || errno != EISDIR)
458 return -1;
459 remove_path(path);
460 }
461 return 0;
462}
463
464static char *unique_path(const char *path, const char *branch)
465{
466 char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
467 int suffix = 0;
468 struct stat st;
469 char *p = newpath + strlen(path);
470 strcpy(newpath, path);
471 *(p++) = '~';
472 strcpy(p, branch);
473 for (; *p; ++p)
474 if ('/' == *p)
475 *p = '_';
476 while (path_list_has_path(¤t_file_set, newpath) ||
477 path_list_has_path(¤t_directory_set, newpath) ||
478 lstat(newpath, &st) == 0)
479 sprintf(p, "_%d", suffix++);
480
481 path_list_insert(newpath, ¤t_file_set);
482 return newpath;
483}
484
485static int mkdir_p(const char *path, unsigned long mode)
486{
487 /* path points to cache entries, so xstrdup before messing with it */
488 char *buf = xstrdup(path);
489 int result = safe_create_leading_directories(buf);
490 free(buf);
491 return result;
492}
493
494static void flush_buffer(int fd, const char *buf, unsigned long size)
495{
496 while (size > 0) {
497 long ret = write_in_full(fd, buf, size);
498 if (ret < 0) {
499 /* Ignore epipe */
500 if (errno == EPIPE)
501 break;
502 die("merge-recursive: %s", strerror(errno));
503 } else if (!ret) {
504 die("merge-recursive: disk full?");
505 }
506 size -= ret;
507 buf += ret;
508 }
509}
510
511static int make_room_for_path(const char *path)
512{
513 int status;
514 const char *msg = "failed to create path '%s'%s";
515
516 status = mkdir_p(path, 0777);
517 if (status) {
518 if (status == -3) {
519 /* something else exists */
520 error(msg, path, ": perhaps a D/F conflict?");
521 return -1;
522 }
523 die(msg, path, "");
524 }
525
526 /* Successful unlink is good.. */
527 if (!unlink(path))
528 return 0;
529 /* .. and so is no existing file */
530 if (errno == ENOENT)
531 return 0;
532 /* .. but not some other error (who really cares what?) */
533 return error(msg, path, ": perhaps a D/F conflict?");
534}
535
536static void update_file_flags(const unsigned char *sha,
537 unsigned mode,
538 const char *path,
539 int update_cache,
540 int update_wd)
541{
542 if (index_only)
543 update_wd = 0;
544
545 if (update_wd) {
546 enum object_type type;
547 void *buf;
548 unsigned long size;
549
550 if (S_ISGITLINK(mode))
551 die("cannot read object %s '%s': It is a submodule!",
552 sha1_to_hex(sha), path);
553
554 buf = read_sha1_file(sha, &type, &size);
555 if (!buf)
556 die("cannot read object %s '%s'", sha1_to_hex(sha), path);
557 if (type != OBJ_BLOB)
558 die("blob expected for %s '%s'", sha1_to_hex(sha), path);
559
560 if (make_room_for_path(path) < 0) {
561 update_wd = 0;
562 goto update_index;
563 }
564 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
565 int fd;
566 if (mode & 0100)
567 mode = 0777;
568 else
569 mode = 0666;
570 fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
571 if (fd < 0)
572 die("failed to open %s: %s", path, strerror(errno));
573 flush_buffer(fd, buf, size);
574 close(fd);
575 } else if (S_ISLNK(mode)) {
576 char *lnk = xmemdupz(buf, size);
577 mkdir_p(path, 0777);
578 unlink(path);
579 symlink(lnk, path);
580 free(lnk);
581 } else
582 die("do not know what to do with %06o %s '%s'",
583 mode, sha1_to_hex(sha), path);
584 }
585 update_index:
586 if (update_cache)
587 add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
588}
589
590static void update_file(int clean,
591 const unsigned char *sha,
592 unsigned mode,
593 const char *path)
594{
595 update_file_flags(sha, mode, path, index_only || clean, !index_only);
596}
597
598/* Low level file merging, update and removal */
599
600struct merge_file_info
601{
602 unsigned char sha[20];
603 unsigned mode;
604 unsigned clean:1,
605 merge:1;
606};
607
608static void fill_mm(const unsigned char *sha1, mmfile_t *mm)
609{
610 unsigned long size;
611 enum object_type type;
612
613 if (!hashcmp(sha1, null_sha1)) {
614 mm->ptr = xstrdup("");
615 mm->size = 0;
616 return;
617 }
618
619 mm->ptr = read_sha1_file(sha1, &type, &size);
620 if (!mm->ptr || type != OBJ_BLOB)
621 die("unable to read blob object %s", sha1_to_hex(sha1));
622 mm->size = size;
623}
624
625static int merge_3way(mmbuffer_t *result_buf,
626 struct diff_filespec *o,
627 struct diff_filespec *a,
628 struct diff_filespec *b,
629 const char *branch1,
630 const char *branch2)
631{
632 mmfile_t orig, src1, src2;
633 char *name1, *name2;
634 int merge_status;
635
636 name1 = xstrdup(mkpath("%s:%s", branch1, a->path));
637 name2 = xstrdup(mkpath("%s:%s", branch2, b->path));
638
639 fill_mm(o->sha1, &orig);
640 fill_mm(a->sha1, &src1);
641 fill_mm(b->sha1, &src2);
642
643 merge_status = ll_merge(result_buf, a->path, &orig,
644 &src1, name1, &src2, name2,
645 index_only);
646
647 free(name1);
648 free(name2);
649 free(orig.ptr);
650 free(src1.ptr);
651 free(src2.ptr);
652 return merge_status;
653}
654
655static struct merge_file_info merge_file(struct diff_filespec *o,
656 struct diff_filespec *a, struct diff_filespec *b,
657 const char *branch1, const char *branch2)
658{
659 struct merge_file_info result;
660 result.merge = 0;
661 result.clean = 1;
662
663 if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
664 result.clean = 0;
665 if (S_ISREG(a->mode)) {
666 result.mode = a->mode;
667 hashcpy(result.sha, a->sha1);
668 } else {
669 result.mode = b->mode;
670 hashcpy(result.sha, b->sha1);
671 }
672 } else {
673 if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1))
674 result.merge = 1;
675
676 result.mode = a->mode == o->mode ? b->mode: a->mode;
677
678 if (sha_eq(a->sha1, o->sha1))
679 hashcpy(result.sha, b->sha1);
680 else if (sha_eq(b->sha1, o->sha1))
681 hashcpy(result.sha, a->sha1);
682 else if (S_ISREG(a->mode)) {
683 mmbuffer_t result_buf;
684 int merge_status;
685
686 merge_status = merge_3way(&result_buf, o, a, b,
687 branch1, branch2);
688
689 if ((merge_status < 0) || !result_buf.ptr)
690 die("Failed to execute internal merge");
691
692 if (write_sha1_file(result_buf.ptr, result_buf.size,
693 blob_type, result.sha))
694 die("Unable to add %s to database",
695 a->path);
696
697 free(result_buf.ptr);
698 result.clean = (merge_status == 0);
699 } else if (S_ISGITLINK(a->mode)) {
700 result.clean = 0;
701 hashcpy(result.sha, a->sha1);
702 } else if (S_ISLNK(a->mode)) {
703 hashcpy(result.sha, a->sha1);
704
705 if (!sha_eq(a->sha1, b->sha1))
706 result.clean = 0;
707 } else {
708 die("unsupported object type in the tree");
709 }
710 }
711
712 return result;
713}
714
715static void conflict_rename_rename(struct rename *ren1,
716 const char *branch1,
717 struct rename *ren2,
718 const char *branch2)
719{
720 char *del[2];
721 int delp = 0;
722 const char *ren1_dst = ren1->pair->two->path;
723 const char *ren2_dst = ren2->pair->two->path;
724 const char *dst_name1 = ren1_dst;
725 const char *dst_name2 = ren2_dst;
726 if (path_list_has_path(¤t_directory_set, ren1_dst)) {
727 dst_name1 = del[delp++] = unique_path(ren1_dst, branch1);
728 output(1, "%s is a directory in %s added as %s instead",
729 ren1_dst, branch2, dst_name1);
730 remove_file(0, ren1_dst, 0);
731 }
732 if (path_list_has_path(¤t_directory_set, ren2_dst)) {
733 dst_name2 = del[delp++] = unique_path(ren2_dst, branch2);
734 output(1, "%s is a directory in %s added as %s instead",
735 ren2_dst, branch1, dst_name2);
736 remove_file(0, ren2_dst, 0);
737 }
738 if (index_only) {
739 remove_file_from_cache(dst_name1);
740 remove_file_from_cache(dst_name2);
741 /*
742 * Uncomment to leave the conflicting names in the resulting tree
743 *
744 * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1);
745 * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2);
746 */
747 } else {
748 update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
749 update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
750 }
751 while (delp--)
752 free(del[delp]);
753}
754
755static void conflict_rename_dir(struct rename *ren1,
756 const char *branch1)
757{
758 char *new_path = unique_path(ren1->pair->two->path, branch1);
759 output(1, "Renamed %s to %s instead", ren1->pair->one->path, new_path);
760 remove_file(0, ren1->pair->two->path, 0);
761 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
762 free(new_path);
763}
764
765static void conflict_rename_rename_2(struct rename *ren1,
766 const char *branch1,
767 struct rename *ren2,
768 const char *branch2)
769{
770 char *new_path1 = unique_path(ren1->pair->two->path, branch1);
771 char *new_path2 = unique_path(ren2->pair->two->path, branch2);
772 output(1, "Renamed %s to %s and %s to %s instead",
773 ren1->pair->one->path, new_path1,
774 ren2->pair->one->path, new_path2);
775 remove_file(0, ren1->pair->two->path, 0);
776 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
777 update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
778 free(new_path2);
779 free(new_path1);
780}
781
782static int process_renames(struct path_list *a_renames,
783 struct path_list *b_renames,
784 const char *a_branch,
785 const char *b_branch)
786{
787 int clean_merge = 1, i, j;
788 struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
789 const struct rename *sre;
790
791 for (i = 0; i < a_renames->nr; i++) {
792 sre = a_renames->items[i].util;
793 path_list_insert(sre->pair->two->path, &a_by_dst)->util
794 = sre->dst_entry;
795 }
796 for (i = 0; i < b_renames->nr; i++) {
797 sre = b_renames->items[i].util;
798 path_list_insert(sre->pair->two->path, &b_by_dst)->util
799 = sre->dst_entry;
800 }
801
802 for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
803 int compare;
804 char *src;
805 struct path_list *renames1, *renames2, *renames2Dst;
806 struct rename *ren1 = NULL, *ren2 = NULL;
807 const char *branch1, *branch2;
808 const char *ren1_src, *ren1_dst;
809
810 if (i >= a_renames->nr) {
811 compare = 1;
812 ren2 = b_renames->items[j++].util;
813 } else if (j >= b_renames->nr) {
814 compare = -1;
815 ren1 = a_renames->items[i++].util;
816 } else {
817 compare = strcmp(a_renames->items[i].path,
818 b_renames->items[j].path);
819 if (compare <= 0)
820 ren1 = a_renames->items[i++].util;
821 if (compare >= 0)
822 ren2 = b_renames->items[j++].util;
823 }
824
825 /* TODO: refactor, so that 1/2 are not needed */
826 if (ren1) {
827 renames1 = a_renames;
828 renames2 = b_renames;
829 renames2Dst = &b_by_dst;
830 branch1 = a_branch;
831 branch2 = b_branch;
832 } else {
833 struct rename *tmp;
834 renames1 = b_renames;
835 renames2 = a_renames;
836 renames2Dst = &a_by_dst;
837 branch1 = b_branch;
838 branch2 = a_branch;
839 tmp = ren2;
840 ren2 = ren1;
841 ren1 = tmp;
842 }
843 src = ren1->pair->one->path;
844
845 ren1->dst_entry->processed = 1;
846 ren1->src_entry->processed = 1;
847
848 if (ren1->processed)
849 continue;
850 ren1->processed = 1;
851
852 ren1_src = ren1->pair->one->path;
853 ren1_dst = ren1->pair->two->path;
854
855 if (ren2) {
856 const char *ren2_src = ren2->pair->one->path;
857 const char *ren2_dst = ren2->pair->two->path;
858 /* Renamed in 1 and renamed in 2 */
859 if (strcmp(ren1_src, ren2_src) != 0)
860 die("ren1.src != ren2.src");
861 ren2->dst_entry->processed = 1;
862 ren2->processed = 1;
863 if (strcmp(ren1_dst, ren2_dst) != 0) {
864 clean_merge = 0;
865 output(1, "CONFLICT (rename/rename): "
866 "Rename \"%s\"->\"%s\" in branch \"%s\" "
867 "rename \"%s\"->\"%s\" in \"%s\"%s",
868 src, ren1_dst, branch1,
869 src, ren2_dst, branch2,
870 index_only ? " (left unresolved)": "");
871 if (index_only) {
872 remove_file_from_cache(src);
873 update_file(0, ren1->pair->one->sha1,
874 ren1->pair->one->mode, src);
875 }
876 conflict_rename_rename(ren1, branch1, ren2, branch2);
877 } else {
878 struct merge_file_info mfi;
879 remove_file(1, ren1_src, 1);
880 mfi = merge_file(ren1->pair->one,
881 ren1->pair->two,
882 ren2->pair->two,
883 branch1,
884 branch2);
885 if (mfi.merge || !mfi.clean)
886 output(1, "Renamed %s->%s", src, ren1_dst);
887
888 if (mfi.merge)
889 output(2, "Auto-merged %s", ren1_dst);
890
891 if (!mfi.clean) {
892 output(1, "CONFLICT (content): merge conflict in %s",
893 ren1_dst);
894 clean_merge = 0;
895
896 if (!index_only)
897 update_stages(ren1_dst,
898 ren1->pair->one,
899 ren1->pair->two,
900 ren2->pair->two,
901 1 /* clear */);
902 }
903 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
904 }
905 } else {
906 /* Renamed in 1, maybe changed in 2 */
907 struct path_list_item *item;
908 /* we only use sha1 and mode of these */
909 struct diff_filespec src_other, dst_other;
910 int try_merge, stage = a_renames == renames1 ? 3: 2;
911
912 remove_file(1, ren1_src, index_only || stage == 3);
913
914 hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
915 src_other.mode = ren1->src_entry->stages[stage].mode;
916 hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
917 dst_other.mode = ren1->dst_entry->stages[stage].mode;
918
919 try_merge = 0;
920
921 if (path_list_has_path(¤t_directory_set, ren1_dst)) {
922 clean_merge = 0;
923 output(1, "CONFLICT (rename/directory): Renamed %s->%s in %s "
924 " directory %s added in %s",
925 ren1_src, ren1_dst, branch1,
926 ren1_dst, branch2);
927 conflict_rename_dir(ren1, branch1);
928 } else if (sha_eq(src_other.sha1, null_sha1)) {
929 clean_merge = 0;
930 output(1, "CONFLICT (rename/delete): Renamed %s->%s in %s "
931 "and deleted in %s",
932 ren1_src, ren1_dst, branch1,
933 branch2);
934 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
935 } else if (!sha_eq(dst_other.sha1, null_sha1)) {
936 const char *new_path;
937 clean_merge = 0;
938 try_merge = 1;
939 output(1, "CONFLICT (rename/add): Renamed %s->%s in %s. "
940 "%s added in %s",
941 ren1_src, ren1_dst, branch1,
942 ren1_dst, branch2);
943 new_path = unique_path(ren1_dst, branch2);
944 output(1, "Added as %s instead", new_path);
945 update_file(0, dst_other.sha1, dst_other.mode, new_path);
946 } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) {
947 ren2 = item->util;
948 clean_merge = 0;
949 ren2->processed = 1;
950 output(1, "CONFLICT (rename/rename): Renamed %s->%s in %s. "
951 "Renamed %s->%s in %s",
952 ren1_src, ren1_dst, branch1,
953 ren2->pair->one->path, ren2->pair->two->path, branch2);
954 conflict_rename_rename_2(ren1, branch1, ren2, branch2);
955 } else
956 try_merge = 1;
957
958 if (try_merge) {
959 struct diff_filespec *o, *a, *b;
960 struct merge_file_info mfi;
961 src_other.path = (char *)ren1_src;
962
963 o = ren1->pair->one;
964 if (a_renames == renames1) {
965 a = ren1->pair->two;
966 b = &src_other;
967 } else {
968 b = ren1->pair->two;
969 a = &src_other;
970 }
971 mfi = merge_file(o, a, b,
972 a_branch, b_branch);
973
974 if (mfi.clean &&
975 sha_eq(mfi.sha, ren1->pair->two->sha1) &&
976 mfi.mode == ren1->pair->two->mode)
977 /*
978 * This messaged is part of
979 * t6022 test. If you change
980 * it update the test too.
981 */
982 output(3, "Skipped %s (merged same as existing)", ren1_dst);
983 else {
984 if (mfi.merge || !mfi.clean)
985 output(1, "Renamed %s => %s", ren1_src, ren1_dst);
986 if (mfi.merge)
987 output(2, "Auto-merged %s", ren1_dst);
988 if (!mfi.clean) {
989 output(1, "CONFLICT (rename/modify): Merge conflict in %s",
990 ren1_dst);
991 clean_merge = 0;
992
993 if (!index_only)
994 update_stages(ren1_dst,
995 o, a, b, 1);
996 }
997 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
998 }
999 }
1000 }
1001 }
1002 path_list_clear(&a_by_dst, 0);
1003 path_list_clear(&b_by_dst, 0);
1004
1005 return clean_merge;
1006}
1007
1008static unsigned char *stage_sha(const unsigned char *sha, unsigned mode)
1009{
1010 return (is_null_sha1(sha) || mode == 0) ? NULL: (unsigned char *)sha;
1011}
1012
1013/* Per entry merge function */
1014static int process_entry(const char *path, struct stage_data *entry,
1015 const char *branch1,
1016 const char *branch2)
1017{
1018 /*
1019 printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
1020 print_index_entry("\tpath: ", entry);
1021 */
1022 int clean_merge = 1;
1023 unsigned o_mode = entry->stages[1].mode;
1024 unsigned a_mode = entry->stages[2].mode;
1025 unsigned b_mode = entry->stages[3].mode;
1026 unsigned char *o_sha = stage_sha(entry->stages[1].sha, o_mode);
1027 unsigned char *a_sha = stage_sha(entry->stages[2].sha, a_mode);
1028 unsigned char *b_sha = stage_sha(entry->stages[3].sha, b_mode);
1029
1030 if (o_sha && (!a_sha || !b_sha)) {
1031 /* Case A: Deleted in one */
1032 if ((!a_sha && !b_sha) ||
1033 (sha_eq(a_sha, o_sha) && !b_sha) ||
1034 (!a_sha && sha_eq(b_sha, o_sha))) {
1035 /* Deleted in both or deleted in one and
1036 * unchanged in the other */
1037 if (a_sha)
1038 output(2, "Removed %s", path);
1039 /* do not touch working file if it did not exist */
1040 remove_file(1, path, !a_sha);
1041 } else {
1042 /* Deleted in one and changed in the other */
1043 clean_merge = 0;
1044 if (!a_sha) {
1045 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1046 "and modified in %s. Version %s of %s left in tree.",
1047 path, branch1,
1048 branch2, branch2, path);
1049 update_file(0, b_sha, b_mode, path);
1050 } else {
1051 output(1, "CONFLICT (delete/modify): %s deleted in %s "
1052 "and modified in %s. Version %s of %s left in tree.",
1053 path, branch2,
1054 branch1, branch1, path);
1055 update_file(0, a_sha, a_mode, path);
1056 }
1057 }
1058
1059 } else if ((!o_sha && a_sha && !b_sha) ||
1060 (!o_sha && !a_sha && b_sha)) {
1061 /* Case B: Added in one. */
1062 const char *add_branch;
1063 const char *other_branch;
1064 unsigned mode;
1065 const unsigned char *sha;
1066 const char *conf;
1067
1068 if (a_sha) {
1069 add_branch = branch1;
1070 other_branch = branch2;
1071 mode = a_mode;
1072 sha = a_sha;
1073 conf = "file/directory";
1074 } else {
1075 add_branch = branch2;
1076 other_branch = branch1;
1077 mode = b_mode;
1078 sha = b_sha;
1079 conf = "directory/file";
1080 }
1081 if (path_list_has_path(¤t_directory_set, path)) {
1082 const char *new_path = unique_path(path, add_branch);
1083 clean_merge = 0;
1084 output(1, "CONFLICT (%s): There is a directory with name %s in %s. "
1085 "Added %s as %s",
1086 conf, path, other_branch, path, new_path);
1087 remove_file(0, path, 0);
1088 update_file(0, sha, mode, new_path);
1089 } else {
1090 output(2, "Added %s", path);
1091 update_file(1, sha, mode, path);
1092 }
1093 } else if (a_sha && b_sha) {
1094 /* Case C: Added in both (check for same permissions) and */
1095 /* case D: Modified in both, but differently. */
1096 const char *reason = "content";
1097 struct merge_file_info mfi;
1098 struct diff_filespec o, a, b;
1099
1100 if (!o_sha) {
1101 reason = "add/add";
1102 o_sha = (unsigned char *)null_sha1;
1103 }
1104 output(2, "Auto-merged %s", path);
1105 o.path = a.path = b.path = (char *)path;
1106 hashcpy(o.sha1, o_sha);
1107 o.mode = o_mode;
1108 hashcpy(a.sha1, a_sha);
1109 a.mode = a_mode;
1110 hashcpy(b.sha1, b_sha);
1111 b.mode = b_mode;
1112
1113 mfi = merge_file(&o, &a, &b,
1114 branch1, branch2);
1115
1116 clean_merge = mfi.clean;
1117 if (mfi.clean)
1118 update_file(1, mfi.sha, mfi.mode, path);
1119 else if (S_ISGITLINK(mfi.mode))
1120 output(1, "CONFLICT (submodule): Merge conflict in %s "
1121 "- needs %s", path, sha1_to_hex(b.sha1));
1122 else {
1123 output(1, "CONFLICT (%s): Merge conflict in %s",
1124 reason, path);
1125
1126 if (index_only)
1127 update_file(0, mfi.sha, mfi.mode, path);
1128 else
1129 update_file_flags(mfi.sha, mfi.mode, path,
1130 0 /* update_cache */, 1 /* update_working_directory */);
1131 }
1132 } else if (!o_sha && !a_sha && !b_sha) {
1133 /*
1134 * this entry was deleted altogether. a_mode == 0 means
1135 * we had that path and want to actively remove it.
1136 */
1137 remove_file(1, path, !a_mode);
1138 } else
1139 die("Fatal merge failure, shouldn't happen.");
1140
1141 return clean_merge;
1142}
1143
1144static int merge_trees(struct tree *head,
1145 struct tree *merge,
1146 struct tree *common,
1147 const char *branch1,
1148 const char *branch2,
1149 struct tree **result)
1150{
1151 int code, clean;
1152
1153 if (subtree_merge) {
1154 merge = shift_tree_object(head, merge);
1155 common = shift_tree_object(head, common);
1156 }
1157
1158 if (sha_eq(common->object.sha1, merge->object.sha1)) {
1159 output(0, "Already uptodate!");
1160 *result = head;
1161 return 1;
1162 }
1163
1164 code = git_merge_trees(index_only, common, head, merge);
1165
1166 if (code != 0)
1167 die("merging of trees %s and %s failed",
1168 sha1_to_hex(head->object.sha1),
1169 sha1_to_hex(merge->object.sha1));
1170
1171 if (unmerged_index()) {
1172 struct path_list *entries, *re_head, *re_merge;
1173 int i;
1174 path_list_clear(¤t_file_set, 1);
1175 path_list_clear(¤t_directory_set, 1);
1176 get_files_dirs(head);
1177 get_files_dirs(merge);
1178
1179 entries = get_unmerged();
1180 re_head = get_renames(head, common, head, merge, entries);
1181 re_merge = get_renames(merge, common, head, merge, entries);
1182 clean = process_renames(re_head, re_merge,
1183 branch1, branch2);
1184 for (i = 0; i < entries->nr; i++) {
1185 const char *path = entries->items[i].path;
1186 struct stage_data *e = entries->items[i].util;
1187 if (!e->processed
1188 && !process_entry(path, e, branch1, branch2))
1189 clean = 0;
1190 }
1191
1192 path_list_clear(re_merge, 0);
1193 path_list_clear(re_head, 0);
1194 path_list_clear(entries, 1);
1195
1196 }
1197 else
1198 clean = 1;
1199
1200 if (index_only)
1201 *result = git_write_tree();
1202
1203 return clean;
1204}
1205
1206static struct commit_list *reverse_commit_list(struct commit_list *list)
1207{
1208 struct commit_list *next = NULL, *current, *backup;
1209 for (current = list; current; current = backup) {
1210 backup = current->next;
1211 current->next = next;
1212 next = current;
1213 }
1214 return next;
1215}
1216
1217/*
1218 * Merge the commits h1 and h2, return the resulting virtual
1219 * commit object and a flag indicating the cleanness of the merge.
1220 */
1221static int merge(struct commit *h1,
1222 struct commit *h2,
1223 const char *branch1,
1224 const char *branch2,
1225 struct commit_list *ca,
1226 struct commit **result)
1227{
1228 struct commit_list *iter;
1229 struct commit *merged_common_ancestors;
1230 struct tree *mrtree = mrtree;
1231 int clean;
1232
1233 if (show(4)) {
1234 output(4, "Merging:");
1235 output_commit_title(h1);
1236 output_commit_title(h2);
1237 }
1238
1239 if (!ca) {
1240 ca = get_merge_bases(h1, h2, 1);
1241 ca = reverse_commit_list(ca);
1242 }
1243
1244 if (show(5)) {
1245 output(5, "found %u common ancestor(s):", commit_list_count(ca));
1246 for (iter = ca; iter; iter = iter->next)
1247 output_commit_title(iter->item);
1248 }
1249
1250 merged_common_ancestors = pop_commit(&ca);
1251 if (merged_common_ancestors == NULL) {
1252 /* if there is no common ancestor, make an empty tree */
1253 struct tree *tree = xcalloc(1, sizeof(struct tree));
1254
1255 tree->object.parsed = 1;
1256 tree->object.type = OBJ_TREE;
1257 pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1);
1258 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1259 }
1260
1261 for (iter = ca; iter; iter = iter->next) {
1262 call_depth++;
1263 /*
1264 * When the merge fails, the result contains files
1265 * with conflict markers. The cleanness flag is
1266 * ignored, it was never actually used, as result of
1267 * merge_trees has always overwritten it: the committed
1268 * "conflicts" were already resolved.
1269 */
1270 discard_cache();
1271 merge(merged_common_ancestors, iter->item,
1272 "Temporary merge branch 1",
1273 "Temporary merge branch 2",
1274 NULL,
1275 &merged_common_ancestors);
1276 call_depth--;
1277
1278 if (!merged_common_ancestors)
1279 die("merge returned no commit");
1280 }
1281
1282 discard_cache();
1283 if (!call_depth) {
1284 read_cache();
1285 index_only = 0;
1286 } else
1287 index_only = 1;
1288
1289 clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree,
1290 branch1, branch2, &mrtree);
1291
1292 if (index_only) {
1293 *result = make_virtual_commit(mrtree, "merged tree");
1294 commit_list_insert(h1, &(*result)->parents);
1295 commit_list_insert(h2, &(*result)->parents->next);
1296 }
1297 flush_output();
1298 return clean;
1299}
1300
1301static const char *better_branch_name(const char *branch)
1302{
1303 static char githead_env[8 + 40 + 1];
1304 char *name;
1305
1306 if (strlen(branch) != 40)
1307 return branch;
1308 sprintf(githead_env, "GITHEAD_%s", branch);
1309 name = getenv(githead_env);
1310 return name ? name : branch;
1311}
1312
1313static struct commit *get_ref(const char *ref)
1314{
1315 unsigned char sha1[20];
1316 struct object *object;
1317
1318 if (get_sha1(ref, sha1))
1319 die("Could not resolve ref '%s'", ref);
1320 object = deref_tag(parse_object(sha1), ref, strlen(ref));
1321 if (!object)
1322 return NULL;
1323 if (object->type == OBJ_TREE)
1324 return make_virtual_commit((struct tree*)object,
1325 better_branch_name(ref));
1326 if (object->type != OBJ_COMMIT)
1327 return NULL;
1328 if (parse_commit((struct commit *)object))
1329 die("Could not parse commit '%s'", sha1_to_hex(object->sha1));
1330 return (struct commit *)object;
1331}
1332
1333static int merge_config(const char *var, const char *value)
1334{
1335 if (!strcasecmp(var, "merge.verbosity")) {
1336 verbosity = git_config_int(var, value);
1337 return 0;
1338 }
1339 if (!strcasecmp(var, "diff.renamelimit")) {
1340 rename_limit = git_config_int(var, value);
1341 return 0;
1342 }
1343 return git_default_config(var, value);
1344}
1345
1346int main(int argc, char *argv[])
1347{
1348 static const char *bases[20];
1349 static unsigned bases_count = 0;
1350 int i, clean;
1351 const char *branch1, *branch2;
1352 struct commit *result, *h1, *h2;
1353 struct commit_list *ca = NULL;
1354 struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
1355 int index_fd;
1356
1357 if (argv[0]) {
1358 int namelen = strlen(argv[0]);
1359 if (8 < namelen &&
1360 !strcmp(argv[0] + namelen - 8, "-subtree"))
1361 subtree_merge = 1;
1362 }
1363
1364 git_config(merge_config);
1365 if (getenv("GIT_MERGE_VERBOSITY"))
1366 verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
1367
1368 if (argc < 4)
1369 die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]);
1370
1371 for (i = 1; i < argc; ++i) {
1372 if (!strcmp(argv[i], "--"))
1373 break;
1374 if (bases_count < sizeof(bases)/sizeof(*bases))
1375 bases[bases_count++] = argv[i];
1376 }
1377 if (argc - i != 3) /* "--" "<head>" "<remote>" */
1378 die("Not handling anything other than two heads merge.");
1379 if (verbosity >= 5)
1380 buffer_output = 0;
1381
1382 branch1 = argv[++i];
1383 branch2 = argv[++i];
1384
1385 h1 = get_ref(branch1);
1386 h2 = get_ref(branch2);
1387
1388 branch1 = better_branch_name(branch1);
1389 branch2 = better_branch_name(branch2);
1390
1391 if (show(3))
1392 printf("Merging %s with %s\n", branch1, branch2);
1393
1394 index_fd = hold_locked_index(lock, 1);
1395
1396 for (i = 0; i < bases_count; i++) {
1397 struct commit *ancestor = get_ref(bases[i]);
1398 ca = commit_list_insert(ancestor, &ca);
1399 }
1400 clean = merge(h1, h2, branch1, branch2, ca, &result);
1401
1402 if (active_cache_changed &&
1403 (write_cache(index_fd, active_cache, active_nr) ||
1404 commit_locked_index(lock)))
1405 die ("unable to write %s", get_index_file());
1406
1407 return clean ? 0: 1;
1408}