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