Code

6e13b8ed5b7988f6379003242654a34b3ded6da6
[git.git] / merge-recursive.c
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 <stdarg.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <sys/wait.h>
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <time.h>
13 #include "cache.h"
14 #include "cache-tree.h"
15 #include "commit.h"
16 #include "blob.h"
17 #include "tree-walk.h"
18 #include "diff.h"
19 #include "diffcore.h"
20 #include "run-command.h"
21 #include "tag.h"
22 #include "unpack-trees.h"
23 #include "path-list.h"
24 #include "xdiff-interface.h"
26 /*
27  * A virtual commit has
28  * - (const char *)commit->util set to the name, and
29  * - *(int *)commit->object.sha1 set to the virtual id.
30  */
32 static unsigned commit_list_count(const struct commit_list *l)
33 {
34         unsigned c = 0;
35         for (; l; l = l->next )
36                 c++;
37         return c;
38 }
40 static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
41 {
42         struct commit *commit = xcalloc(1, sizeof(struct commit));
43         static unsigned virtual_id = 1;
44         commit->tree = tree;
45         commit->util = (void*)comment;
46         *(int*)commit->object.sha1 = virtual_id++;
47         /* avoid warnings */
48         commit->object.parsed = 1;
49         return commit;
50 }
52 /*
53  * Since we use get_tree_entry(), which does not put the read object into
54  * the object pool, we cannot rely on a == b.
55  */
56 static int sha_eq(const unsigned char *a, const unsigned char *b)
57 {
58         if (!a && !b)
59                 return 2;
60         return a && b && hashcmp(a, b) == 0;
61 }
63 /*
64  * Since we want to write the index eventually, we cannot reuse the index
65  * for these (temporary) data.
66  */
67 struct stage_data
68 {
69         struct
70         {
71                 unsigned mode;
72                 unsigned char sha[20];
73         } stages[4];
74         unsigned processed:1;
75 };
77 static struct path_list current_file_set = {NULL, 0, 0, 1};
78 static struct path_list current_directory_set = {NULL, 0, 0, 1};
80 static int output_indent = 0;
82 static void output(const char *fmt, ...)
83 {
84         va_list args;
85         int i;
86         for (i = output_indent; i--;)
87                 fputs("  ", stdout);
88         va_start(args, fmt);
89         vfprintf(stdout, fmt, args);
90         va_end(args);
91         fputc('\n', stdout);
92 }
94 static void output_commit_title(struct commit *commit)
95 {
96         int i;
97         for (i = output_indent; i--;)
98                 fputs("  ", stdout);
99         if (commit->util)
100                 printf("virtual %s\n", (char *)commit->util);
101         else {
102                 printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
103                 if (parse_commit(commit) != 0)
104                         printf("(bad commit)\n");
105                 else {
106                         const char *s;
107                         int len;
108                         for (s = commit->buffer; *s; s++)
109                                 if (*s == '\n' && s[1] == '\n') {
110                                         s += 2;
111                                         break;
112                                 }
113                         for (len = 0; s[len] && '\n' != s[len]; len++)
114                                 ; /* do nothing */
115                         printf("%.*s\n", len, s);
116                 }
117         }
120 static const char *current_index_file = NULL;
121 static const char *original_index_file;
122 static const char *temporary_index_file;
123 static int cache_dirty = 0;
125 static int flush_cache(void)
127         /* flush temporary index */
128         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
129         int fd = hold_lock_file_for_update(lock, current_index_file, 1);
130         if (write_cache(fd, active_cache, active_nr) ||
131                         close(fd) || commit_lock_file(lock))
132                 die ("unable to write %s", current_index_file);
133         discard_cache();
134         cache_dirty = 0;
135         return 0;
138 static void setup_index(int temp)
140         current_index_file = temp ? temporary_index_file: original_index_file;
141         if (cache_dirty) {
142                 discard_cache();
143                 cache_dirty = 0;
144         }
145         unlink(temporary_index_file);
146         discard_cache();
149 static struct cache_entry *make_cache_entry(unsigned int mode,
150                 const unsigned char *sha1, const char *path, int stage, int refresh)
152         int size, len;
153         struct cache_entry *ce;
155         if (!verify_path(path))
156                 return NULL;
158         len = strlen(path);
159         size = cache_entry_size(len);
160         ce = xcalloc(1, size);
162         hashcpy(ce->sha1, sha1);
163         memcpy(ce->name, path, len);
164         ce->ce_flags = create_ce_flags(len, stage);
165         ce->ce_mode = create_ce_mode(mode);
167         if (refresh)
168                 return refresh_cache_entry(ce, 0);
170         return ce;
173 static int add_cacheinfo(unsigned int mode, const unsigned char *sha1,
174                 const char *path, int stage, int refresh, int options)
176         struct cache_entry *ce;
177         if (!cache_dirty)
178                 read_cache_from(current_index_file);
179         cache_dirty++;
180         ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh);
181         if (!ce)
182                 return error("cache_addinfo failed: %s", strerror(cache_errno));
183         return add_cache_entry(ce, options);
186 /*
187  * This is a global variable which is used in a number of places but
188  * only written to in the 'merge' function.
189  *
190  * index_only == 1    => Don't leave any non-stage 0 entries in the cache and
191  *                       don't update the working directory.
192  *               0    => Leave unmerged entries in the cache and update
193  *                       the working directory.
194  */
195 static int index_only = 0;
197 static int git_read_tree(struct tree *tree)
199         int rc;
200         struct object_list *trees = NULL;
201         struct unpack_trees_options opts;
203         if (cache_dirty)
204                 die("read-tree with dirty cache");
206         memset(&opts, 0, sizeof(opts));
207         object_list_append(&tree->object, &trees);
208         rc = unpack_trees(trees, &opts);
209         cache_tree_free(&active_cache_tree);
211         if (rc == 0)
212                 cache_dirty = 1;
214         return rc;
217 static int git_merge_trees(int index_only,
218                            struct tree *common,
219                            struct tree *head,
220                            struct tree *merge)
222         int rc;
223         struct object_list *trees = NULL;
224         struct unpack_trees_options opts;
226         if (!cache_dirty) {
227                 read_cache_from(current_index_file);
228                 cache_dirty = 1;
229         }
231         memset(&opts, 0, sizeof(opts));
232         if (index_only)
233                 opts.index_only = 1;
234         else
235                 opts.update = 1;
236         opts.merge = 1;
237         opts.head_idx = 2;
238         opts.fn = threeway_merge;
240         object_list_append(&common->object, &trees);
241         object_list_append(&head->object, &trees);
242         object_list_append(&merge->object, &trees);
244         rc = unpack_trees(trees, &opts);
245         cache_tree_free(&active_cache_tree);
247         cache_dirty = 1;
249         return rc;
252 static struct tree *git_write_tree(void)
254         struct tree *result = NULL;
256         if (cache_dirty) {
257                 unsigned i;
258                 for (i = 0; i < active_nr; i++) {
259                         struct cache_entry *ce = active_cache[i];
260                         if (ce_stage(ce))
261                                 return NULL;
262                 }
263         } else
264                 read_cache_from(current_index_file);
266         if (!active_cache_tree)
267                 active_cache_tree = cache_tree();
269         if (!cache_tree_fully_valid(active_cache_tree) &&
270                         cache_tree_update(active_cache_tree,
271                                 active_cache, active_nr, 0, 0) < 0)
272                 die("error building trees");
274         result = lookup_tree(active_cache_tree->sha1);
276         flush_cache();
277         cache_dirty = 0;
279         return result;
282 static int save_files_dirs(const unsigned char *sha1,
283                 const char *base, int baselen, const char *path,
284                 unsigned int mode, int stage)
286         int len = strlen(path);
287         char *newpath = xmalloc(baselen + len + 1);
288         memcpy(newpath, base, baselen);
289         memcpy(newpath + baselen, path, len);
290         newpath[baselen + len] = '\0';
292         if (S_ISDIR(mode))
293                 path_list_insert(newpath, &current_directory_set);
294         else
295                 path_list_insert(newpath, &current_file_set);
296         free(newpath);
298         return READ_TREE_RECURSIVE;
301 static int get_files_dirs(struct tree *tree)
303         int n;
304         if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs) != 0)
305                 return 0;
306         n = current_file_set.nr + current_directory_set.nr;
307         return n;
310 /*
311  * Returns a index_entry instance which doesn't have to correspond to
312  * a real cache entry in Git's index.
313  */
314 static struct stage_data *insert_stage_data(const char *path,
315                 struct tree *o, struct tree *a, struct tree *b,
316                 struct path_list *entries)
318         struct path_list_item *item;
319         struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
320         get_tree_entry(o->object.sha1, path,
321                         e->stages[1].sha, &e->stages[1].mode);
322         get_tree_entry(a->object.sha1, path,
323                         e->stages[2].sha, &e->stages[2].mode);
324         get_tree_entry(b->object.sha1, path,
325                         e->stages[3].sha, &e->stages[3].mode);
326         item = path_list_insert(path, entries);
327         item->util = e;
328         return e;
331 /*
332  * Create a dictionary mapping file names to stage_data objects. The
333  * dictionary contains one entry for every path with a non-zero stage entry.
334  */
335 static struct path_list *get_unmerged(void)
337         struct path_list *unmerged = xcalloc(1, sizeof(struct path_list));
338         int i;
340         unmerged->strdup_paths = 1;
341         if (!cache_dirty) {
342                 read_cache_from(current_index_file);
343                 cache_dirty++;
344         }
345         for (i = 0; i < active_nr; i++) {
346                 struct path_list_item *item;
347                 struct stage_data *e;
348                 struct cache_entry *ce = active_cache[i];
349                 if (!ce_stage(ce))
350                         continue;
352                 item = path_list_lookup(ce->name, unmerged);
353                 if (!item) {
354                         item = path_list_insert(ce->name, unmerged);
355                         item->util = xcalloc(1, sizeof(struct stage_data));
356                 }
357                 e = item->util;
358                 e->stages[ce_stage(ce)].mode = ntohl(ce->ce_mode);
359                 hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1);
360         }
362         return unmerged;
365 struct rename
367         struct diff_filepair *pair;
368         struct stage_data *src_entry;
369         struct stage_data *dst_entry;
370         unsigned processed:1;
371 };
373 /*
374  * Get information of all renames which occured between 'o_tree' and
375  * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
376  * 'b_tree') to be able to associate the correct cache entries with
377  * the rename information. 'tree' is always equal to either a_tree or b_tree.
378  */
379 static struct path_list *get_renames(struct tree *tree,
380                                         struct tree *o_tree,
381                                         struct tree *a_tree,
382                                         struct tree *b_tree,
383                                         struct path_list *entries)
385         int i;
386         struct path_list *renames;
387         struct diff_options opts;
389         renames = xcalloc(1, sizeof(struct path_list));
390         diff_setup(&opts);
391         opts.recursive = 1;
392         opts.detect_rename = DIFF_DETECT_RENAME;
393         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
394         if (diff_setup_done(&opts) < 0)
395                 die("diff setup failed");
396         diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts);
397         diffcore_std(&opts);
398         for (i = 0; i < diff_queued_diff.nr; ++i) {
399                 struct path_list_item *item;
400                 struct rename *re;
401                 struct diff_filepair *pair = diff_queued_diff.queue[i];
402                 if (pair->status != 'R') {
403                         diff_free_filepair(pair);
404                         continue;
405                 }
406                 re = xmalloc(sizeof(*re));
407                 re->processed = 0;
408                 re->pair = pair;
409                 item = path_list_lookup(re->pair->one->path, entries);
410                 if (!item)
411                         re->src_entry = insert_stage_data(re->pair->one->path,
412                                         o_tree, a_tree, b_tree, entries);
413                 else
414                         re->src_entry = item->util;
416                 item = path_list_lookup(re->pair->two->path, entries);
417                 if (!item)
418                         re->dst_entry = insert_stage_data(re->pair->two->path,
419                                         o_tree, a_tree, b_tree, entries);
420                 else
421                         re->dst_entry = item->util;
422                 item = path_list_insert(pair->one->path, renames);
423                 item->util = re;
424         }
425         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
426         diff_queued_diff.nr = 0;
427         diff_flush(&opts);
428         return renames;
431 static int update_stages(const char *path, struct diff_filespec *o,
432                          struct diff_filespec *a, struct diff_filespec *b,
433                          int clear)
435         int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
436         if (clear)
437                 if (remove_file_from_cache(path))
438                         return -1;
439         if (o)
440                 if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options))
441                         return -1;
442         if (a)
443                 if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options))
444                         return -1;
445         if (b)
446                 if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options))
447                         return -1;
448         return 0;
451 static int remove_path(const char *name)
453         int ret, len;
454         char *slash, *dirs;
456         ret = unlink(name);
457         if (ret)
458                 return ret;
459         len = strlen(name);
460         dirs = xmalloc(len+1);
461         memcpy(dirs, name, len);
462         dirs[len] = '\0';
463         while ((slash = strrchr(name, '/'))) {
464                 *slash = '\0';
465                 len = slash - name;
466                 if (rmdir(name) != 0)
467                         break;
468         }
469         free(dirs);
470         return ret;
473 static int remove_file(int clean, const char *path, int no_wd)
475         int update_cache = index_only || clean;
476         int update_working_directory = !index_only && !no_wd;
478         if (update_cache) {
479                 if (!cache_dirty)
480                         read_cache_from(current_index_file);
481                 cache_dirty++;
482                 if (remove_file_from_cache(path))
483                         return -1;
484         }
485         if (update_working_directory) {
486                 unlink(path);
487                 if (errno != ENOENT || errno != EISDIR)
488                         return -1;
489                 remove_path(path);
490         }
491         return 0;
494 static char *unique_path(const char *path, const char *branch)
496         char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1);
497         int suffix = 0;
498         struct stat st;
499         char *p = newpath + strlen(path);
500         strcpy(newpath, path);
501         *(p++) = '~';
502         strcpy(p, branch);
503         for (; *p; ++p)
504                 if ('/' == *p)
505                         *p = '_';
506         while (path_list_has_path(&current_file_set, newpath) ||
507                path_list_has_path(&current_directory_set, newpath) ||
508                lstat(newpath, &st) == 0)
509                 sprintf(p, "_%d", suffix++);
511         path_list_insert(newpath, &current_file_set);
512         return newpath;
515 static int mkdir_p(const char *path, unsigned long mode)
517         /* path points to cache entries, so xstrdup before messing with it */
518         char *buf = xstrdup(path);
519         int result = safe_create_leading_directories(buf);
520         free(buf);
521         return result;
524 static void flush_buffer(int fd, const char *buf, unsigned long size)
526         while (size > 0) {
527                 long ret = xwrite(fd, buf, size);
528                 if (ret < 0) {
529                         /* Ignore epipe */
530                         if (errno == EPIPE)
531                                 break;
532                         die("merge-recursive: %s", strerror(errno));
533                 } else if (!ret) {
534                         die("merge-recursive: disk full?");
535                 }
536                 size -= ret;
537                 buf += ret;
538         }
541 static void update_file_flags(const unsigned char *sha,
542                               unsigned mode,
543                               const char *path,
544                               int update_cache,
545                               int update_wd)
547         if (index_only)
548                 update_wd = 0;
550         if (update_wd) {
551                 char type[20];
552                 void *buf;
553                 unsigned long size;
555                 buf = read_sha1_file(sha, type, &size);
556                 if (!buf)
557                         die("cannot read object %s '%s'", sha1_to_hex(sha), path);
558                 if (strcmp(type, blob_type) != 0)
559                         die("blob expected for %s '%s'", sha1_to_hex(sha), path);
561                 if (S_ISREG(mode)) {
562                         int fd;
563                         if (mkdir_p(path, 0777))
564                                 die("failed to create path %s: %s", path, strerror(errno));
565                         unlink(path);
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 = xmalloc(size + 1);
577                         memcpy(lnk, buf, size);
578                         lnk[size] = '\0';
579                         mkdir_p(path, 0777);
580                         unlink(lnk);
581                         symlink(lnk, path);
582                 } else
583                         die("do not know what to do with %06o %s '%s'",
584                             mode, sha1_to_hex(sha), path);
585         }
586         if (update_cache)
587                 add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
590 static void update_file(int clean,
591                         const unsigned char *sha,
592                         unsigned mode,
593                         const char *path)
595         update_file_flags(sha, mode, path, index_only || clean, !index_only);
598 /* Low level file merging, update and removal */
600 struct merge_file_info
602         unsigned char sha[20];
603         unsigned mode;
604         unsigned clean:1,
605                  merge:1;
606 };
608 static void fill_mm(const unsigned char *sha1, mmfile_t *mm)
610         unsigned long size;
611         char type[20];
613         mm->ptr = read_sha1_file(sha1, type, &size);
614         if (!mm->ptr || strcmp(type, blob_type))
615                 die("unable to read blob object %s", sha1_to_hex(sha1));
616         mm->size = size;
619 static struct merge_file_info merge_file(struct diff_filespec *o,
620                 struct diff_filespec *a, struct diff_filespec *b,
621                 const char *branch1, const char *branch2)
623         struct merge_file_info result;
624         result.merge = 0;
625         result.clean = 1;
627         if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
628                 result.clean = 0;
629                 if (S_ISREG(a->mode)) {
630                         result.mode = a->mode;
631                         hashcpy(result.sha, a->sha1);
632                 } else {
633                         result.mode = b->mode;
634                         hashcpy(result.sha, b->sha1);
635                 }
636         } else {
637                 if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1))
638                         result.merge = 1;
640                 result.mode = a->mode == o->mode ? b->mode: a->mode;
642                 if (sha_eq(a->sha1, o->sha1))
643                         hashcpy(result.sha, b->sha1);
644                 else if (sha_eq(b->sha1, o->sha1))
645                         hashcpy(result.sha, a->sha1);
646                 else if (S_ISREG(a->mode)) {
647                         mmfile_t orig, src1, src2;
648                         mmbuffer_t result_buf;
649                         xpparam_t xpp;
650                         char *name1, *name2;
651                         int merge_status;
653                         name1 = xstrdup(mkpath("%s/%s", branch1, a->path));
654                         name2 = xstrdup(mkpath("%s/%s", branch2, b->path));
656                         fill_mm(o->sha1, &orig);
657                         fill_mm(a->sha1, &src1);
658                         fill_mm(b->sha1, &src2);
660                         memset(&xpp, 0, sizeof(xpp));
661                         merge_status = xdl_merge(&orig,
662                                                  &src1, name1,
663                                                  &src2, name2,
664                                                  &xpp, XDL_MERGE_ZEALOUS,
665                                                  &result_buf);
666                         free(name1);
667                         free(name2);
668                         free(orig.ptr);
669                         free(src1.ptr);
670                         free(src2.ptr);
672                         if ((merge_status < 0) || !result_buf.ptr)
673                                 die("Failed to execute internal merge");
675                         if (write_sha1_file(result_buf.ptr, result_buf.size,
676                                             blob_type, result.sha))
677                                 die("Unable to add %s to database",
678                                     a->path);
680                         free(result_buf.ptr);
681                         result.clean = (merge_status == 0);
682                 } else {
683                         if (!(S_ISLNK(a->mode) || S_ISLNK(b->mode)))
684                                 die("cannot merge modes?");
686                         hashcpy(result.sha, a->sha1);
688                         if (!sha_eq(a->sha1, b->sha1))
689                                 result.clean = 0;
690                 }
691         }
693         return result;
696 static void conflict_rename_rename(struct rename *ren1,
697                                    const char *branch1,
698                                    struct rename *ren2,
699                                    const char *branch2)
701         char *del[2];
702         int delp = 0;
703         const char *ren1_dst = ren1->pair->two->path;
704         const char *ren2_dst = ren2->pair->two->path;
705         const char *dst_name1 = ren1_dst;
706         const char *dst_name2 = ren2_dst;
707         if (path_list_has_path(&current_directory_set, ren1_dst)) {
708                 dst_name1 = del[delp++] = unique_path(ren1_dst, branch1);
709                 output("%s is a directory in %s adding as %s instead",
710                        ren1_dst, branch2, dst_name1);
711                 remove_file(0, ren1_dst, 0);
712         }
713         if (path_list_has_path(&current_directory_set, ren2_dst)) {
714                 dst_name2 = del[delp++] = unique_path(ren2_dst, branch2);
715                 output("%s is a directory in %s adding as %s instead",
716                        ren2_dst, branch1, dst_name2);
717                 remove_file(0, ren2_dst, 0);
718         }
719         update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1);
720         update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1);
721         while (delp--)
722                 free(del[delp]);
725 static void conflict_rename_dir(struct rename *ren1,
726                                 const char *branch1)
728         char *new_path = unique_path(ren1->pair->two->path, branch1);
729         output("Renaming %s to %s instead", ren1->pair->one->path, new_path);
730         remove_file(0, ren1->pair->two->path, 0);
731         update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path);
732         free(new_path);
735 static void conflict_rename_rename_2(struct rename *ren1,
736                                      const char *branch1,
737                                      struct rename *ren2,
738                                      const char *branch2)
740         char *new_path1 = unique_path(ren1->pair->two->path, branch1);
741         char *new_path2 = unique_path(ren2->pair->two->path, branch2);
742         output("Renaming %s to %s and %s to %s instead",
743                ren1->pair->one->path, new_path1,
744                ren2->pair->one->path, new_path2);
745         remove_file(0, ren1->pair->two->path, 0);
746         update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1);
747         update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2);
748         free(new_path2);
749         free(new_path1);
752 static int process_renames(struct path_list *a_renames,
753                            struct path_list *b_renames,
754                            const char *a_branch,
755                            const char *b_branch)
757         int clean_merge = 1, i, j;
758         struct path_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0};
759         const struct rename *sre;
761         for (i = 0; i < a_renames->nr; i++) {
762                 sre = a_renames->items[i].util;
763                 path_list_insert(sre->pair->two->path, &a_by_dst)->util
764                         = sre->dst_entry;
765         }
766         for (i = 0; i < b_renames->nr; i++) {
767                 sre = b_renames->items[i].util;
768                 path_list_insert(sre->pair->two->path, &b_by_dst)->util
769                         = sre->dst_entry;
770         }
772         for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
773                 int compare;
774                 char *src;
775                 struct path_list *renames1, *renames2, *renames2Dst;
776                 struct rename *ren1 = NULL, *ren2 = NULL;
777                 const char *branch1, *branch2;
778                 const char *ren1_src, *ren1_dst;
780                 if (i >= a_renames->nr) {
781                         compare = 1;
782                         ren2 = b_renames->items[j++].util;
783                 } else if (j >= b_renames->nr) {
784                         compare = -1;
785                         ren1 = a_renames->items[i++].util;
786                 } else {
787                         compare = strcmp(a_renames->items[i].path,
788                                         b_renames->items[j].path);
789                         if (compare <= 0)
790                                 ren1 = a_renames->items[i++].util;
791                         if (compare >= 0)
792                                 ren2 = b_renames->items[j++].util;
793                 }
795                 /* TODO: refactor, so that 1/2 are not needed */
796                 if (ren1) {
797                         renames1 = a_renames;
798                         renames2 = b_renames;
799                         renames2Dst = &b_by_dst;
800                         branch1 = a_branch;
801                         branch2 = b_branch;
802                 } else {
803                         struct rename *tmp;
804                         renames1 = b_renames;
805                         renames2 = a_renames;
806                         renames2Dst = &a_by_dst;
807                         branch1 = b_branch;
808                         branch2 = a_branch;
809                         tmp = ren2;
810                         ren2 = ren1;
811                         ren1 = tmp;
812                 }
813                 src = ren1->pair->one->path;
815                 ren1->dst_entry->processed = 1;
816                 ren1->src_entry->processed = 1;
818                 if (ren1->processed)
819                         continue;
820                 ren1->processed = 1;
822                 ren1_src = ren1->pair->one->path;
823                 ren1_dst = ren1->pair->two->path;
825                 if (ren2) {
826                         const char *ren2_src = ren2->pair->one->path;
827                         const char *ren2_dst = ren2->pair->two->path;
828                         /* Renamed in 1 and renamed in 2 */
829                         if (strcmp(ren1_src, ren2_src) != 0)
830                                 die("ren1.src != ren2.src");
831                         ren2->dst_entry->processed = 1;
832                         ren2->processed = 1;
833                         if (strcmp(ren1_dst, ren2_dst) != 0) {
834                                 clean_merge = 0;
835                                 output("CONFLICT (rename/rename): "
836                                        "Rename %s->%s in branch %s "
837                                        "rename %s->%s in %s",
838                                        src, ren1_dst, branch1,
839                                        src, ren2_dst, branch2);
840                                 conflict_rename_rename(ren1, branch1, ren2, branch2);
841                         } else {
842                                 struct merge_file_info mfi;
843                                 remove_file(1, ren1_src, 1);
844                                 mfi = merge_file(ren1->pair->one,
845                                                  ren1->pair->two,
846                                                  ren2->pair->two,
847                                                  branch1,
848                                                  branch2);
849                                 if (mfi.merge || !mfi.clean)
850                                         output("Renaming %s->%s", src, ren1_dst);
852                                 if (mfi.merge)
853                                         output("Auto-merging %s", ren1_dst);
855                                 if (!mfi.clean) {
856                                         output("CONFLICT (content): merge conflict in %s",
857                                                ren1_dst);
858                                         clean_merge = 0;
860                                         if (!index_only)
861                                                 update_stages(ren1_dst,
862                                                               ren1->pair->one,
863                                                               ren1->pair->two,
864                                                               ren2->pair->two,
865                                                               1 /* clear */);
866                                 }
867                                 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
868                         }
869                 } else {
870                         /* Renamed in 1, maybe changed in 2 */
871                         struct path_list_item *item;
872                         /* we only use sha1 and mode of these */
873                         struct diff_filespec src_other, dst_other;
874                         int try_merge, stage = a_renames == renames1 ? 3: 2;
876                         remove_file(1, ren1_src, 1);
878                         hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha);
879                         src_other.mode = ren1->src_entry->stages[stage].mode;
880                         hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha);
881                         dst_other.mode = ren1->dst_entry->stages[stage].mode;
883                         try_merge = 0;
885                         if (path_list_has_path(&current_directory_set, ren1_dst)) {
886                                 clean_merge = 0;
887                                 output("CONFLICT (rename/directory): Rename %s->%s in %s "
888                                        " directory %s added in %s",
889                                        ren1_src, ren1_dst, branch1,
890                                        ren1_dst, branch2);
891                                 conflict_rename_dir(ren1, branch1);
892                         } else if (sha_eq(src_other.sha1, null_sha1)) {
893                                 clean_merge = 0;
894                                 output("CONFLICT (rename/delete): Rename %s->%s in %s "
895                                        "and deleted in %s",
896                                        ren1_src, ren1_dst, branch1,
897                                        branch2);
898                                 update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst);
899                         } else if (!sha_eq(dst_other.sha1, null_sha1)) {
900                                 const char *new_path;
901                                 clean_merge = 0;
902                                 try_merge = 1;
903                                 output("CONFLICT (rename/add): Rename %s->%s in %s. "
904                                        "%s added in %s",
905                                        ren1_src, ren1_dst, branch1,
906                                        ren1_dst, branch2);
907                                 new_path = unique_path(ren1_dst, branch2);
908                                 output("Adding as %s instead", new_path);
909                                 update_file(0, dst_other.sha1, dst_other.mode, new_path);
910                         } else if ((item = path_list_lookup(ren1_dst, renames2Dst))) {
911                                 ren2 = item->util;
912                                 clean_merge = 0;
913                                 ren2->processed = 1;
914                                 output("CONFLICT (rename/rename): Rename %s->%s in %s. "
915                                        "Rename %s->%s in %s",
916                                        ren1_src, ren1_dst, branch1,
917                                        ren2->pair->one->path, ren2->pair->two->path, branch2);
918                                 conflict_rename_rename_2(ren1, branch1, ren2, branch2);
919                         } else
920                                 try_merge = 1;
922                         if (try_merge) {
923                                 struct diff_filespec *o, *a, *b;
924                                 struct merge_file_info mfi;
925                                 src_other.path = (char *)ren1_src;
927                                 o = ren1->pair->one;
928                                 if (a_renames == renames1) {
929                                         a = ren1->pair->two;
930                                         b = &src_other;
931                                 } else {
932                                         b = ren1->pair->two;
933                                         a = &src_other;
934                                 }
935                                 mfi = merge_file(o, a, b,
936                                                 a_branch, b_branch);
938                                 if (mfi.merge || !mfi.clean)
939                                         output("Renaming %s => %s", ren1_src, ren1_dst);
940                                 if (mfi.merge)
941                                         output("Auto-merging %s", ren1_dst);
942                                 if (!mfi.clean) {
943                                         output("CONFLICT (rename/modify): Merge conflict in %s",
944                                                ren1_dst);
945                                         clean_merge = 0;
947                                         if (!index_only)
948                                                 update_stages(ren1_dst,
949                                                                 o, a, b, 1);
950                                 }
951                                 update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst);
952                         }
953                 }
954         }
955         path_list_clear(&a_by_dst, 0);
956         path_list_clear(&b_by_dst, 0);
958         if (cache_dirty)
959                 flush_cache();
960         return clean_merge;
963 static unsigned char *has_sha(const unsigned char *sha)
965         return is_null_sha1(sha) ? NULL: (unsigned char *)sha;
968 /* Per entry merge function */
969 static int process_entry(const char *path, struct stage_data *entry,
970                          const char *branch1,
971                          const char *branch2)
973         /*
974         printf("processing entry, clean cache: %s\n", index_only ? "yes": "no");
975         print_index_entry("\tpath: ", entry);
976         */
977         int clean_merge = 1;
978         unsigned char *o_sha = has_sha(entry->stages[1].sha);
979         unsigned char *a_sha = has_sha(entry->stages[2].sha);
980         unsigned char *b_sha = has_sha(entry->stages[3].sha);
981         unsigned o_mode = entry->stages[1].mode;
982         unsigned a_mode = entry->stages[2].mode;
983         unsigned b_mode = entry->stages[3].mode;
985         if (o_sha && (!a_sha || !b_sha)) {
986                 /* Case A: Deleted in one */
987                 if ((!a_sha && !b_sha) ||
988                     (sha_eq(a_sha, o_sha) && !b_sha) ||
989                     (!a_sha && sha_eq(b_sha, o_sha))) {
990                         /* Deleted in both or deleted in one and
991                          * unchanged in the other */
992                         if (a_sha)
993                                 output("Removing %s", path);
994                         /* do not touch working file if it did not exist */
995                         remove_file(1, path, !a_sha);
996                 } else {
997                         /* Deleted in one and changed in the other */
998                         clean_merge = 0;
999                         if (!a_sha) {
1000                                 output("CONFLICT (delete/modify): %s deleted in %s "
1001                                        "and modified in %s. Version %s of %s left in tree.",
1002                                        path, branch1,
1003                                        branch2, branch2, path);
1004                                 update_file(0, b_sha, b_mode, path);
1005                         } else {
1006                                 output("CONFLICT (delete/modify): %s deleted in %s "
1007                                        "and modified in %s. Version %s of %s left in tree.",
1008                                        path, branch2,
1009                                        branch1, branch1, path);
1010                                 update_file(0, a_sha, a_mode, path);
1011                         }
1012                 }
1014         } else if ((!o_sha && a_sha && !b_sha) ||
1015                    (!o_sha && !a_sha && b_sha)) {
1016                 /* Case B: Added in one. */
1017                 const char *add_branch;
1018                 const char *other_branch;
1019                 unsigned mode;
1020                 const unsigned char *sha;
1021                 const char *conf;
1023                 if (a_sha) {
1024                         add_branch = branch1;
1025                         other_branch = branch2;
1026                         mode = a_mode;
1027                         sha = a_sha;
1028                         conf = "file/directory";
1029                 } else {
1030                         add_branch = branch2;
1031                         other_branch = branch1;
1032                         mode = b_mode;
1033                         sha = b_sha;
1034                         conf = "directory/file";
1035                 }
1036                 if (path_list_has_path(&current_directory_set, path)) {
1037                         const char *new_path = unique_path(path, add_branch);
1038                         clean_merge = 0;
1039                         output("CONFLICT (%s): There is a directory with name %s in %s. "
1040                                "Adding %s as %s",
1041                                conf, path, other_branch, path, new_path);
1042                         remove_file(0, path, 0);
1043                         update_file(0, sha, mode, new_path);
1044                 } else {
1045                         output("Adding %s", path);
1046                         update_file(1, sha, mode, path);
1047                 }
1048         } else if (!o_sha && a_sha && b_sha) {
1049                 /* Case C: Added in both (check for same permissions). */
1050                 if (sha_eq(a_sha, b_sha)) {
1051                         if (a_mode != b_mode) {
1052                                 clean_merge = 0;
1053                                 output("CONFLICT: File %s added identically in both branches, "
1054                                        "but permissions conflict %06o->%06o",
1055                                        path, a_mode, b_mode);
1056                                 output("CONFLICT: adding with permission: %06o", a_mode);
1057                                 update_file(0, a_sha, a_mode, path);
1058                         } else {
1059                                 /* This case is handled by git-read-tree */
1060                                 assert(0 && "This case must be handled by git-read-tree");
1061                         }
1062                 } else {
1063                         const char *new_path1, *new_path2;
1064                         clean_merge = 0;
1065                         new_path1 = unique_path(path, branch1);
1066                         new_path2 = unique_path(path, branch2);
1067                         output("CONFLICT (add/add): File %s added non-identically "
1068                                "in both branches. Adding as %s and %s instead.",
1069                                path, new_path1, new_path2);
1070                         remove_file(0, path, 0);
1071                         update_file(0, a_sha, a_mode, new_path1);
1072                         update_file(0, b_sha, b_mode, new_path2);
1073                 }
1075         } else if (o_sha && a_sha && b_sha) {
1076                 /* case D: Modified in both, but differently. */
1077                 struct merge_file_info mfi;
1078                 struct diff_filespec o, a, b;
1080                 output("Auto-merging %s", path);
1081                 o.path = a.path = b.path = (char *)path;
1082                 hashcpy(o.sha1, o_sha);
1083                 o.mode = o_mode;
1084                 hashcpy(a.sha1, a_sha);
1085                 a.mode = a_mode;
1086                 hashcpy(b.sha1, b_sha);
1087                 b.mode = b_mode;
1089                 mfi = merge_file(&o, &a, &b,
1090                                  branch1, branch2);
1092                 if (mfi.clean)
1093                         update_file(1, mfi.sha, mfi.mode, path);
1094                 else {
1095                         clean_merge = 0;
1096                         output("CONFLICT (content): Merge conflict in %s", path);
1098                         if (index_only)
1099                                 update_file(0, mfi.sha, mfi.mode, path);
1100                         else
1101                                 update_file_flags(mfi.sha, mfi.mode, path,
1102                                               0 /* update_cache */, 1 /* update_working_directory */);
1103                 }
1104         } else
1105                 die("Fatal merge failure, shouldn't happen.");
1107         if (cache_dirty)
1108                 flush_cache();
1110         return clean_merge;
1113 static int merge_trees(struct tree *head,
1114                        struct tree *merge,
1115                        struct tree *common,
1116                        const char *branch1,
1117                        const char *branch2,
1118                        struct tree **result)
1120         int code, clean;
1121         if (sha_eq(common->object.sha1, merge->object.sha1)) {
1122                 output("Already uptodate!");
1123                 *result = head;
1124                 return 1;
1125         }
1127         code = git_merge_trees(index_only, common, head, merge);
1129         if (code != 0)
1130                 die("merging of trees %s and %s failed",
1131                     sha1_to_hex(head->object.sha1),
1132                     sha1_to_hex(merge->object.sha1));
1134         *result = git_write_tree();
1136         if (!*result) {
1137                 struct path_list *entries, *re_head, *re_merge;
1138                 int i;
1139                 path_list_clear(&current_file_set, 1);
1140                 path_list_clear(&current_directory_set, 1);
1141                 get_files_dirs(head);
1142                 get_files_dirs(merge);
1144                 entries = get_unmerged();
1145                 re_head  = get_renames(head, common, head, merge, entries);
1146                 re_merge = get_renames(merge, common, head, merge, entries);
1147                 clean = process_renames(re_head, re_merge,
1148                                 branch1, branch2);
1149                 for (i = 0; i < entries->nr; i++) {
1150                         const char *path = entries->items[i].path;
1151                         struct stage_data *e = entries->items[i].util;
1152                         if (e->processed)
1153                                 continue;
1154                         if (!process_entry(path, e, branch1, branch2))
1155                                 clean = 0;
1156                 }
1158                 path_list_clear(re_merge, 0);
1159                 path_list_clear(re_head, 0);
1160                 path_list_clear(entries, 1);
1162                 if (clean || index_only)
1163                         *result = git_write_tree();
1164                 else
1165                         *result = NULL;
1166         } else {
1167                 clean = 1;
1168                 printf("merging of trees %s and %s resulted in %s\n",
1169                        sha1_to_hex(head->object.sha1),
1170                        sha1_to_hex(merge->object.sha1),
1171                        sha1_to_hex((*result)->object.sha1));
1172         }
1174         return clean;
1177 static struct commit_list *reverse_commit_list(struct commit_list *list)
1179         struct commit_list *next = NULL, *current, *backup;
1180         for (current = list; current; current = backup) {
1181                 backup = current->next;
1182                 current->next = next;
1183                 next = current;
1184         }
1185         return next;
1188 /*
1189  * Merge the commits h1 and h2, return the resulting virtual
1190  * commit object and a flag indicating the cleaness of the merge.
1191  */
1192 static int merge(struct commit *h1,
1193                  struct commit *h2,
1194                  const char *branch1,
1195                  const char *branch2,
1196                  int call_depth /* =0 */,
1197                  struct commit *ancestor /* =None */,
1198                  struct commit **result)
1200         struct commit_list *ca = NULL, *iter;
1201         struct commit *merged_common_ancestors;
1202         struct tree *mrtree;
1203         int clean;
1205         output("Merging:");
1206         output_commit_title(h1);
1207         output_commit_title(h2);
1209         if (ancestor)
1210                 commit_list_insert(ancestor, &ca);
1211         else
1212                 ca = reverse_commit_list(get_merge_bases(h1, h2, 1));
1214         output("found %u common ancestor(s):", commit_list_count(ca));
1215         for (iter = ca; iter; iter = iter->next)
1216                 output_commit_title(iter->item);
1218         merged_common_ancestors = pop_commit(&ca);
1219         if (merged_common_ancestors == NULL) {
1220                 /* if there is no common ancestor, make an empty tree */
1221                 struct tree *tree = xcalloc(1, sizeof(struct tree));
1223                 tree->object.parsed = 1;
1224                 tree->object.type = OBJ_TREE;
1225                 hash_sha1_file(NULL, 0, tree_type, tree->object.sha1);
1226                 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
1227         }
1229         for (iter = ca; iter; iter = iter->next) {
1230                 output_indent = call_depth + 1;
1231                 /*
1232                  * When the merge fails, the result contains files
1233                  * with conflict markers. The cleanness flag is
1234                  * ignored, it was never acutally used, as result of
1235                  * merge_trees has always overwritten it: the commited
1236                  * "conflicts" were already resolved.
1237                  */
1238                 merge(merged_common_ancestors, iter->item,
1239                       "Temporary merge branch 1",
1240                       "Temporary merge branch 2",
1241                       call_depth + 1,
1242                       NULL,
1243                       &merged_common_ancestors);
1244                 output_indent = call_depth;
1246                 if (!merged_common_ancestors)
1247                         die("merge returned no commit");
1248         }
1250         if (call_depth == 0) {
1251                 setup_index(0 /* $GIT_DIR/index */);
1252                 index_only = 0;
1253         } else {
1254                 setup_index(1 /* temporary index */);
1255                 git_read_tree(h1->tree);
1256                 index_only = 1;
1257         }
1259         clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree,
1260                             branch1, branch2, &mrtree);
1262         if (!ancestor && (clean || index_only)) {
1263                 *result = make_virtual_commit(mrtree, "merged tree");
1264                 commit_list_insert(h1, &(*result)->parents);
1265                 commit_list_insert(h2, &(*result)->parents->next);
1266         } else
1267                 *result = NULL;
1269         return clean;
1272 static struct commit *get_ref(const char *ref)
1274         unsigned char sha1[20];
1275         struct object *object;
1277         if (get_sha1(ref, sha1))
1278                 die("Could not resolve ref '%s'", ref);
1279         object = deref_tag(parse_object(sha1), ref, strlen(ref));
1280         if (object->type != OBJ_COMMIT)
1281                 return NULL;
1282         if (parse_commit((struct commit *)object))
1283                 die("Could not parse commit '%s'", sha1_to_hex(object->sha1));
1284         return (struct commit *)object;
1287 int main(int argc, char *argv[])
1289         static const char *bases[2];
1290         static unsigned bases_count = 0;
1291         int i, clean;
1292         const char *branch1, *branch2;
1293         struct commit *result, *h1, *h2;
1295         git_config(git_default_config); /* core.filemode */
1296         original_index_file = getenv("GIT_INDEX_FILE");
1298         if (!original_index_file)
1299                 original_index_file = xstrdup(git_path("index"));
1301         temporary_index_file = xstrdup(git_path("mrg-rcrsv-tmp-idx"));
1303         if (argc < 4)
1304                 die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]);
1306         for (i = 1; i < argc; ++i) {
1307                 if (!strcmp(argv[i], "--"))
1308                         break;
1309                 if (bases_count < sizeof(bases)/sizeof(*bases))
1310                         bases[bases_count++] = argv[i];
1311         }
1312         if (argc - i != 3) /* "--" "<head>" "<remote>" */
1313                 die("Not handling anything other than two heads merge.");
1315         branch1 = argv[++i];
1316         branch2 = argv[++i];
1317         printf("Merging %s with %s\n", branch1, branch2);
1319         h1 = get_ref(branch1);
1320         h2 = get_ref(branch2);
1322         if (bases_count == 1) {
1323                 struct commit *ancestor = get_ref(bases[0]);
1324                 clean = merge(h1, h2, branch1, branch2, 0, ancestor, &result);
1325         } else
1326                 clean = merge(h1, h2, branch1, branch2, 0, NULL, &result);
1328         if (cache_dirty)
1329                 flush_cache();
1331         return clean ? 0: 1;
1334 /*
1335 vim: sw=8 noet
1336 */