Merge branch 'js/am-3-merge-recursive-direct'
[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 "advice.h"
8 #include "lockfile.h"
9 #include "cache-tree.h"
10 #include "commit.h"
11 #include "blob.h"
12 #include "builtin.h"
13 #include "tree-walk.h"
14 #include "diff.h"
15 #include "diffcore.h"
16 #include "tag.h"
17 #include "unpack-trees.h"
18 #include "string-list.h"
19 #include "xdiff-interface.h"
20 #include "ll-merge.h"
21 #include "attr.h"
22 #include "merge-recursive.h"
23 #include "dir.h"
24 #include "submodule.h"
25
26 static void flush_output(struct merge_options *o)
27 {
28         if (o->buffer_output < 2 && o->obuf.len) {
29                 fputs(o->obuf.buf, stdout);
30                 strbuf_reset(&o->obuf);
31         }
32 }
33
34 static int err(struct merge_options *o, const char *err, ...)
35 {
36         va_list params;
37
38         if (o->buffer_output < 2)
39                 flush_output(o);
40         else {
41                 strbuf_complete(&o->obuf, '\n');
42                 strbuf_addstr(&o->obuf, "error: ");
43         }
44         va_start(params, err);
45         strbuf_vaddf(&o->obuf, err, params);
46         va_end(params);
47         if (o->buffer_output > 1)
48                 strbuf_addch(&o->obuf, '\n');
49         else {
50                 error("%s", o->obuf.buf);
51                 strbuf_reset(&o->obuf);
52         }
53
54         return -1;
55 }
56
57 static struct tree *shift_tree_object(struct tree *one, struct tree *two,
58                                       const char *subtree_shift)
59 {
60         struct object_id shifted;
61
62         if (!*subtree_shift) {
63                 shift_tree(&one->object.oid, &two->object.oid, &shifted, 0);
64         } else {
65                 shift_tree_by(&one->object.oid, &two->object.oid, &shifted,
66                               subtree_shift);
67         }
68         if (!oidcmp(&two->object.oid, &shifted))
69                 return two;
70         return lookup_tree(shifted.hash);
71 }
72
73 static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
74 {
75         struct commit *commit = alloc_commit_node();
76         struct merge_remote_desc *desc = xmalloc(sizeof(*desc));
77
78         desc->name = comment;
79         desc->obj = (struct object *)commit;
80         commit->tree = tree;
81         commit->util = desc;
82         commit->object.parsed = 1;
83         return commit;
84 }
85
86 /*
87  * Since we use get_tree_entry(), which does not put the read object into
88  * the object pool, we cannot rely on a == b.
89  */
90 static int oid_eq(const struct object_id *a, const struct object_id *b)
91 {
92         if (!a && !b)
93                 return 2;
94         return a && b && oidcmp(a, b) == 0;
95 }
96
97 enum rename_type {
98         RENAME_NORMAL = 0,
99         RENAME_DELETE,
100         RENAME_ONE_FILE_TO_ONE,
101         RENAME_ONE_FILE_TO_TWO,
102         RENAME_TWO_FILES_TO_ONE
103 };
104
105 struct rename_conflict_info {
106         enum rename_type rename_type;
107         struct diff_filepair *pair1;
108         struct diff_filepair *pair2;
109         const char *branch1;
110         const char *branch2;
111         struct stage_data *dst_entry1;
112         struct stage_data *dst_entry2;
113         struct diff_filespec ren1_other;
114         struct diff_filespec ren2_other;
115 };
116
117 /*
118  * Since we want to write the index eventually, we cannot reuse the index
119  * for these (temporary) data.
120  */
121 struct stage_data {
122         struct {
123                 unsigned mode;
124                 struct object_id oid;
125         } stages[4];
126         struct rename_conflict_info *rename_conflict_info;
127         unsigned processed:1;
128 };
129
130 static inline void setup_rename_conflict_info(enum rename_type rename_type,
131                                               struct diff_filepair *pair1,
132                                               struct diff_filepair *pair2,
133                                               const char *branch1,
134                                               const char *branch2,
135                                               struct stage_data *dst_entry1,
136                                               struct stage_data *dst_entry2,
137                                               struct merge_options *o,
138                                               struct stage_data *src_entry1,
139                                               struct stage_data *src_entry2)
140 {
141         struct rename_conflict_info *ci = xcalloc(1, sizeof(struct rename_conflict_info));
142         ci->rename_type = rename_type;
143         ci->pair1 = pair1;
144         ci->branch1 = branch1;
145         ci->branch2 = branch2;
146
147         ci->dst_entry1 = dst_entry1;
148         dst_entry1->rename_conflict_info = ci;
149         dst_entry1->processed = 0;
150
151         assert(!pair2 == !dst_entry2);
152         if (dst_entry2) {
153                 ci->dst_entry2 = dst_entry2;
154                 ci->pair2 = pair2;
155                 dst_entry2->rename_conflict_info = ci;
156         }
157
158         if (rename_type == RENAME_TWO_FILES_TO_ONE) {
159                 /*
160                  * For each rename, there could have been
161                  * modifications on the side of history where that
162                  * file was not renamed.
163                  */
164                 int ostage1 = o->branch1 == branch1 ? 3 : 2;
165                 int ostage2 = ostage1 ^ 1;
166
167                 ci->ren1_other.path = pair1->one->path;
168                 oidcpy(&ci->ren1_other.oid, &src_entry1->stages[ostage1].oid);
169                 ci->ren1_other.mode = src_entry1->stages[ostage1].mode;
170
171                 ci->ren2_other.path = pair2->one->path;
172                 oidcpy(&ci->ren2_other.oid, &src_entry2->stages[ostage2].oid);
173                 ci->ren2_other.mode = src_entry2->stages[ostage2].mode;
174         }
175 }
176
177 static int show(struct merge_options *o, int v)
178 {
179         return (!o->call_depth && o->verbosity >= v) || o->verbosity >= 5;
180 }
181
182 __attribute__((format (printf, 3, 4)))
183 static void output(struct merge_options *o, int v, const char *fmt, ...)
184 {
185         va_list ap;
186
187         if (!show(o, v))
188                 return;
189
190         strbuf_addchars(&o->obuf, ' ', o->call_depth * 2);
191
192         va_start(ap, fmt);
193         strbuf_vaddf(&o->obuf, fmt, ap);
194         va_end(ap);
195
196         strbuf_addch(&o->obuf, '\n');
197         if (!o->buffer_output)
198                 flush_output(o);
199 }
200
201 static void output_commit_title(struct merge_options *o, struct commit *commit)
202 {
203         strbuf_addchars(&o->obuf, ' ', o->call_depth * 2);
204         if (commit->util)
205                 strbuf_addf(&o->obuf, "virtual %s\n",
206                         merge_remote_util(commit)->name);
207         else {
208                 strbuf_addf(&o->obuf, "%s ",
209                         find_unique_abbrev(commit->object.oid.hash,
210                                 DEFAULT_ABBREV));
211                 if (parse_commit(commit) != 0)
212                         strbuf_addf(&o->obuf, _("(bad commit)\n"));
213                 else {
214                         const char *title;
215                         const char *msg = get_commit_buffer(commit, NULL);
216                         int len = find_commit_subject(msg, &title);
217                         if (len)
218                                 strbuf_addf(&o->obuf, "%.*s\n", len, title);
219                         unuse_commit_buffer(commit, msg);
220                 }
221         }
222         flush_output(o);
223 }
224
225 static int add_cacheinfo(struct merge_options *o,
226                 unsigned int mode, const struct object_id *oid,
227                 const char *path, int stage, int refresh, int options)
228 {
229         struct cache_entry *ce;
230         int ret;
231
232         ce = make_cache_entry(mode, oid ? oid->hash : null_sha1, path, stage, 0);
233         if (!ce)
234                 return err(o, _("addinfo_cache failed for path '%s'"), path);
235
236         ret = add_cache_entry(ce, options);
237         if (refresh) {
238                 struct cache_entry *nce;
239
240                 nce = refresh_cache_entry(ce, CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING);
241                 if (nce != ce)
242                         ret = add_cache_entry(nce, options);
243         }
244         return ret;
245 }
246
247 static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
248 {
249         parse_tree(tree);
250         init_tree_desc(desc, tree->buffer, tree->size);
251 }
252
253 static int git_merge_trees(int index_only,
254                            struct tree *common,
255                            struct tree *head,
256                            struct tree *merge)
257 {
258         int rc;
259         struct tree_desc t[3];
260         struct unpack_trees_options opts;
261
262         memset(&opts, 0, sizeof(opts));
263         if (index_only)
264                 opts.index_only = 1;
265         else
266                 opts.update = 1;
267         opts.merge = 1;
268         opts.head_idx = 2;
269         opts.fn = threeway_merge;
270         opts.src_index = &the_index;
271         opts.dst_index = &the_index;
272         setup_unpack_trees_porcelain(&opts, "merge");
273
274         init_tree_desc_from_tree(t+0, common);
275         init_tree_desc_from_tree(t+1, head);
276         init_tree_desc_from_tree(t+2, merge);
277
278         rc = unpack_trees(3, t, &opts);
279         cache_tree_free(&active_cache_tree);
280         return rc;
281 }
282
283 struct tree *write_tree_from_memory(struct merge_options *o)
284 {
285         struct tree *result = NULL;
286
287         if (unmerged_cache()) {
288                 int i;
289                 fprintf(stderr, "BUG: There are unmerged index entries:\n");
290                 for (i = 0; i < active_nr; i++) {
291                         const struct cache_entry *ce = active_cache[i];
292                         if (ce_stage(ce))
293                                 fprintf(stderr, "BUG: %d %.*s\n", ce_stage(ce),
294                                         (int)ce_namelen(ce), ce->name);
295                 }
296                 die("BUG: unmerged index entries in merge-recursive.c");
297         }
298
299         if (!active_cache_tree)
300                 active_cache_tree = cache_tree();
301
302         if (!cache_tree_fully_valid(active_cache_tree) &&
303             cache_tree_update(&the_index, 0) < 0) {
304                 err(o, _("error building trees"));
305                 return NULL;
306         }
307
308         result = lookup_tree(active_cache_tree->sha1);
309
310         return result;
311 }
312
313 static int save_files_dirs(const unsigned char *sha1,
314                 struct strbuf *base, const char *path,
315                 unsigned int mode, int stage, void *context)
316 {
317         int baselen = base->len;
318         struct merge_options *o = context;
319
320         strbuf_addstr(base, path);
321
322         if (S_ISDIR(mode))
323                 string_list_insert(&o->current_directory_set, base->buf);
324         else
325                 string_list_insert(&o->current_file_set, base->buf);
326
327         strbuf_setlen(base, baselen);
328         return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
329 }
330
331 static int get_files_dirs(struct merge_options *o, struct tree *tree)
332 {
333         int n;
334         struct pathspec match_all;
335         memset(&match_all, 0, sizeof(match_all));
336         if (read_tree_recursive(tree, "", 0, 0, &match_all, save_files_dirs, o))
337                 return 0;
338         n = o->current_file_set.nr + o->current_directory_set.nr;
339         return n;
340 }
341
342 /*
343  * Returns an index_entry instance which doesn't have to correspond to
344  * a real cache entry in Git's index.
345  */
346 static struct stage_data *insert_stage_data(const char *path,
347                 struct tree *o, struct tree *a, struct tree *b,
348                 struct string_list *entries)
349 {
350         struct string_list_item *item;
351         struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
352         get_tree_entry(o->object.oid.hash, path,
353                         e->stages[1].oid.hash, &e->stages[1].mode);
354         get_tree_entry(a->object.oid.hash, path,
355                         e->stages[2].oid.hash, &e->stages[2].mode);
356         get_tree_entry(b->object.oid.hash, path,
357                         e->stages[3].oid.hash, &e->stages[3].mode);
358         item = string_list_insert(entries, path);
359         item->util = e;
360         return e;
361 }
362
363 /*
364  * Create a dictionary mapping file names to stage_data objects. The
365  * dictionary contains one entry for every path with a non-zero stage entry.
366  */
367 static struct string_list *get_unmerged(void)
368 {
369         struct string_list *unmerged = xcalloc(1, sizeof(struct string_list));
370         int i;
371
372         unmerged->strdup_strings = 1;
373
374         for (i = 0; i < active_nr; i++) {
375                 struct string_list_item *item;
376                 struct stage_data *e;
377                 const struct cache_entry *ce = active_cache[i];
378                 if (!ce_stage(ce))
379                         continue;
380
381                 item = string_list_lookup(unmerged, ce->name);
382                 if (!item) {
383                         item = string_list_insert(unmerged, ce->name);
384                         item->util = xcalloc(1, sizeof(struct stage_data));
385                 }
386                 e = item->util;
387                 e->stages[ce_stage(ce)].mode = ce->ce_mode;
388                 hashcpy(e->stages[ce_stage(ce)].oid.hash, ce->sha1);
389         }
390
391         return unmerged;
392 }
393
394 static int string_list_df_name_compare(const void *a, const void *b)
395 {
396         const struct string_list_item *one = a;
397         const struct string_list_item *two = b;
398         int onelen = strlen(one->string);
399         int twolen = strlen(two->string);
400         /*
401          * Here we only care that entries for D/F conflicts are
402          * adjacent, in particular with the file of the D/F conflict
403          * appearing before files below the corresponding directory.
404          * The order of the rest of the list is irrelevant for us.
405          *
406          * To achieve this, we sort with df_name_compare and provide
407          * the mode S_IFDIR so that D/F conflicts will sort correctly.
408          * We use the mode S_IFDIR for everything else for simplicity,
409          * since in other cases any changes in their order due to
410          * sorting cause no problems for us.
411          */
412         int cmp = df_name_compare(one->string, onelen, S_IFDIR,
413                                   two->string, twolen, S_IFDIR);
414         /*
415          * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
416          * that 'foo' comes before 'foo/bar'.
417          */
418         if (cmp)
419                 return cmp;
420         return onelen - twolen;
421 }
422
423 static void record_df_conflict_files(struct merge_options *o,
424                                      struct string_list *entries)
425 {
426         /* If there is a D/F conflict and the file for such a conflict
427          * currently exist in the working tree, we want to allow it to be
428          * removed to make room for the corresponding directory if needed.
429          * The files underneath the directories of such D/F conflicts will
430          * be processed before the corresponding file involved in the D/F
431          * conflict.  If the D/F directory ends up being removed by the
432          * merge, then we won't have to touch the D/F file.  If the D/F
433          * directory needs to be written to the working copy, then the D/F
434          * file will simply be removed (in make_room_for_path()) to make
435          * room for the necessary paths.  Note that if both the directory
436          * and the file need to be present, then the D/F file will be
437          * reinstated with a new unique name at the time it is processed.
438          */
439         struct string_list df_sorted_entries;
440         const char *last_file = NULL;
441         int last_len = 0;
442         int i;
443
444         /*
445          * If we're merging merge-bases, we don't want to bother with
446          * any working directory changes.
447          */
448         if (o->call_depth)
449                 return;
450
451         /* Ensure D/F conflicts are adjacent in the entries list. */
452         memset(&df_sorted_entries, 0, sizeof(struct string_list));
453         for (i = 0; i < entries->nr; i++) {
454                 struct string_list_item *next = &entries->items[i];
455                 string_list_append(&df_sorted_entries, next->string)->util =
456                                    next->util;
457         }
458         qsort(df_sorted_entries.items, entries->nr, sizeof(*entries->items),
459               string_list_df_name_compare);
460
461         string_list_clear(&o->df_conflict_file_set, 1);
462         for (i = 0; i < df_sorted_entries.nr; i++) {
463                 const char *path = df_sorted_entries.items[i].string;
464                 int len = strlen(path);
465                 struct stage_data *e = df_sorted_entries.items[i].util;
466
467                 /*
468                  * Check if last_file & path correspond to a D/F conflict;
469                  * i.e. whether path is last_file+'/'+<something>.
470                  * If so, record that it's okay to remove last_file to make
471                  * room for path and friends if needed.
472                  */
473                 if (last_file &&
474                     len > last_len &&
475                     memcmp(path, last_file, last_len) == 0 &&
476                     path[last_len] == '/') {
477                         string_list_insert(&o->df_conflict_file_set, last_file);
478                 }
479
480                 /*
481                  * Determine whether path could exist as a file in the
482                  * working directory as a possible D/F conflict.  This
483                  * will only occur when it exists in stage 2 as a
484                  * file.
485                  */
486                 if (S_ISREG(e->stages[2].mode) || S_ISLNK(e->stages[2].mode)) {
487                         last_file = path;
488                         last_len = len;
489                 } else {
490                         last_file = NULL;
491                 }
492         }
493         string_list_clear(&df_sorted_entries, 0);
494 }
495
496 struct rename {
497         struct diff_filepair *pair;
498         struct stage_data *src_entry;
499         struct stage_data *dst_entry;
500         unsigned processed:1;
501 };
502
503 /*
504  * Get information of all renames which occurred between 'o_tree' and
505  * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and
506  * 'b_tree') to be able to associate the correct cache entries with
507  * the rename information. 'tree' is always equal to either a_tree or b_tree.
508  */
509 static struct string_list *get_renames(struct merge_options *o,
510                                        struct tree *tree,
511                                        struct tree *o_tree,
512                                        struct tree *a_tree,
513                                        struct tree *b_tree,
514                                        struct string_list *entries)
515 {
516         int i;
517         struct string_list *renames;
518         struct diff_options opts;
519
520         renames = xcalloc(1, sizeof(struct string_list));
521         if (!o->detect_rename)
522                 return renames;
523
524         diff_setup(&opts);
525         DIFF_OPT_SET(&opts, RECURSIVE);
526         DIFF_OPT_CLR(&opts, RENAME_EMPTY);
527         opts.detect_rename = DIFF_DETECT_RENAME;
528         opts.rename_limit = o->merge_rename_limit >= 0 ? o->merge_rename_limit :
529                             o->diff_rename_limit >= 0 ? o->diff_rename_limit :
530                             1000;
531         opts.rename_score = o->rename_score;
532         opts.show_rename_progress = o->show_rename_progress;
533         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
534         diff_setup_done(&opts);
535         diff_tree_sha1(o_tree->object.oid.hash, tree->object.oid.hash, "", &opts);
536         diffcore_std(&opts);
537         if (opts.needed_rename_limit > o->needed_rename_limit)
538                 o->needed_rename_limit = opts.needed_rename_limit;
539         for (i = 0; i < diff_queued_diff.nr; ++i) {
540                 struct string_list_item *item;
541                 struct rename *re;
542                 struct diff_filepair *pair = diff_queued_diff.queue[i];
543                 if (pair->status != 'R') {
544                         diff_free_filepair(pair);
545                         continue;
546                 }
547                 re = xmalloc(sizeof(*re));
548                 re->processed = 0;
549                 re->pair = pair;
550                 item = string_list_lookup(entries, re->pair->one->path);
551                 if (!item)
552                         re->src_entry = insert_stage_data(re->pair->one->path,
553                                         o_tree, a_tree, b_tree, entries);
554                 else
555                         re->src_entry = item->util;
556
557                 item = string_list_lookup(entries, re->pair->two->path);
558                 if (!item)
559                         re->dst_entry = insert_stage_data(re->pair->two->path,
560                                         o_tree, a_tree, b_tree, entries);
561                 else
562                         re->dst_entry = item->util;
563                 item = string_list_insert(renames, pair->one->path);
564                 item->util = re;
565         }
566         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
567         diff_queued_diff.nr = 0;
568         diff_flush(&opts);
569         return renames;
570 }
571
572 static int update_stages(struct merge_options *opt, const char *path,
573                          const struct diff_filespec *o,
574                          const struct diff_filespec *a,
575                          const struct diff_filespec *b)
576 {
577
578         /*
579          * NOTE: It is usually a bad idea to call update_stages on a path
580          * before calling update_file on that same path, since it can
581          * sometimes lead to spurious "refusing to lose untracked file..."
582          * messages from update_file (via make_room_for path via
583          * would_lose_untracked).  Instead, reverse the order of the calls
584          * (executing update_file first and then update_stages).
585          */
586         int clear = 1;
587         int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK;
588         if (clear)
589                 if (remove_file_from_cache(path))
590                         return -1;
591         if (o)
592                 if (add_cacheinfo(opt, o->mode, &o->oid, path, 1, 0, options))
593                         return -1;
594         if (a)
595                 if (add_cacheinfo(opt, a->mode, &a->oid, path, 2, 0, options))
596                         return -1;
597         if (b)
598                 if (add_cacheinfo(opt, b->mode, &b->oid, path, 3, 0, options))
599                         return -1;
600         return 0;
601 }
602
603 static void update_entry(struct stage_data *entry,
604                          struct diff_filespec *o,
605                          struct diff_filespec *a,
606                          struct diff_filespec *b)
607 {
608         entry->processed = 0;
609         entry->stages[1].mode = o->mode;
610         entry->stages[2].mode = a->mode;
611         entry->stages[3].mode = b->mode;
612         oidcpy(&entry->stages[1].oid, &o->oid);
613         oidcpy(&entry->stages[2].oid, &a->oid);
614         oidcpy(&entry->stages[3].oid, &b->oid);
615 }
616
617 static int remove_file(struct merge_options *o, int clean,
618                        const char *path, int no_wd)
619 {
620         int update_cache = o->call_depth || clean;
621         int update_working_directory = !o->call_depth && !no_wd;
622
623         if (update_cache) {
624                 if (remove_file_from_cache(path))
625                         return -1;
626         }
627         if (update_working_directory) {
628                 if (ignore_case) {
629                         struct cache_entry *ce;
630                         ce = cache_file_exists(path, strlen(path), ignore_case);
631                         if (ce && ce_stage(ce) == 0)
632                                 return 0;
633                 }
634                 if (remove_path(path))
635                         return -1;
636         }
637         return 0;
638 }
639
640 /* add a string to a strbuf, but converting "/" to "_" */
641 static void add_flattened_path(struct strbuf *out, const char *s)
642 {
643         size_t i = out->len;
644         strbuf_addstr(out, s);
645         for (; i < out->len; i++)
646                 if (out->buf[i] == '/')
647                         out->buf[i] = '_';
648 }
649
650 static char *unique_path(struct merge_options *o, const char *path, const char *branch)
651 {
652         struct strbuf newpath = STRBUF_INIT;
653         int suffix = 0;
654         size_t base_len;
655
656         strbuf_addf(&newpath, "%s~", path);
657         add_flattened_path(&newpath, branch);
658
659         base_len = newpath.len;
660         while (string_list_has_string(&o->current_file_set, newpath.buf) ||
661                string_list_has_string(&o->current_directory_set, newpath.buf) ||
662                (!o->call_depth && file_exists(newpath.buf))) {
663                 strbuf_setlen(&newpath, base_len);
664                 strbuf_addf(&newpath, "_%d", suffix++);
665         }
666
667         string_list_insert(&o->current_file_set, newpath.buf);
668         return strbuf_detach(&newpath, NULL);
669 }
670
671 static int dir_in_way(const char *path, int check_working_copy)
672 {
673         int pos;
674         struct strbuf dirpath = STRBUF_INIT;
675         struct stat st;
676
677         strbuf_addstr(&dirpath, path);
678         strbuf_addch(&dirpath, '/');
679
680         pos = cache_name_pos(dirpath.buf, dirpath.len);
681
682         if (pos < 0)
683                 pos = -1 - pos;
684         if (pos < active_nr &&
685             !strncmp(dirpath.buf, active_cache[pos]->name, dirpath.len)) {
686                 strbuf_release(&dirpath);
687                 return 1;
688         }
689
690         strbuf_release(&dirpath);
691         return check_working_copy && !lstat(path, &st) && S_ISDIR(st.st_mode);
692 }
693
694 static int was_tracked(const char *path)
695 {
696         int pos = cache_name_pos(path, strlen(path));
697
698         if (0 <= pos)
699                 /* we have been tracking this path */
700                 return 1;
701
702         /*
703          * Look for an unmerged entry for the path,
704          * specifically stage #2, which would indicate
705          * that "our" side before the merge started
706          * had the path tracked (and resulted in a conflict).
707          */
708         for (pos = -1 - pos;
709              pos < active_nr && !strcmp(path, active_cache[pos]->name);
710              pos++)
711                 if (ce_stage(active_cache[pos]) == 2)
712                         return 1;
713         return 0;
714 }
715
716 static int would_lose_untracked(const char *path)
717 {
718         return !was_tracked(path) && file_exists(path);
719 }
720
721 static int make_room_for_path(struct merge_options *o, const char *path)
722 {
723         int status, i;
724         const char *msg = _("failed to create path '%s'%s");
725
726         /* Unlink any D/F conflict files that are in the way */
727         for (i = 0; i < o->df_conflict_file_set.nr; i++) {
728                 const char *df_path = o->df_conflict_file_set.items[i].string;
729                 size_t pathlen = strlen(path);
730                 size_t df_pathlen = strlen(df_path);
731                 if (df_pathlen < pathlen &&
732                     path[df_pathlen] == '/' &&
733                     strncmp(path, df_path, df_pathlen) == 0) {
734                         output(o, 3,
735                                _("Removing %s to make room for subdirectory\n"),
736                                df_path);
737                         unlink(df_path);
738                         unsorted_string_list_delete_item(&o->df_conflict_file_set,
739                                                          i, 0);
740                         break;
741                 }
742         }
743
744         /* Make sure leading directories are created */
745         status = safe_create_leading_directories_const(path);
746         if (status) {
747                 if (status == SCLD_EXISTS)
748                         /* something else exists */
749                         return err(o, msg, path, _(": perhaps a D/F conflict?"));
750                 return err(o, msg, path, "");
751         }
752
753         /*
754          * Do not unlink a file in the work tree if we are not
755          * tracking it.
756          */
757         if (would_lose_untracked(path))
758                 return err(o, _("refusing to lose untracked file at '%s'"),
759                              path);
760
761         /* Successful unlink is good.. */
762         if (!unlink(path))
763                 return 0;
764         /* .. and so is no existing file */
765         if (errno == ENOENT)
766                 return 0;
767         /* .. but not some other error (who really cares what?) */
768         return err(o, msg, path, _(": perhaps a D/F conflict?"));
769 }
770
771 static int update_file_flags(struct merge_options *o,
772                              const struct object_id *oid,
773                              unsigned mode,
774                              const char *path,
775                              int update_cache,
776                              int update_wd)
777 {
778         int ret = 0;
779
780         if (o->call_depth)
781                 update_wd = 0;
782
783         if (update_wd) {
784                 enum object_type type;
785                 void *buf;
786                 unsigned long size;
787
788                 if (S_ISGITLINK(mode)) {
789                         /*
790                          * We may later decide to recursively descend into
791                          * the submodule directory and update its index
792                          * and/or work tree, but we do not do that now.
793                          */
794                         update_wd = 0;
795                         goto update_index;
796                 }
797
798                 buf = read_sha1_file(oid->hash, &type, &size);
799                 if (!buf)
800                         return err(o, _("cannot read object %s '%s'"), oid_to_hex(oid), path);
801                 if (type != OBJ_BLOB) {
802                         ret = err(o, _("blob expected for %s '%s'"), oid_to_hex(oid), path);
803                         goto free_buf;
804                 }
805                 if (S_ISREG(mode)) {
806                         struct strbuf strbuf = STRBUF_INIT;
807                         if (convert_to_working_tree(path, buf, size, &strbuf)) {
808                                 free(buf);
809                                 size = strbuf.len;
810                                 buf = strbuf_detach(&strbuf, NULL);
811                         }
812                 }
813
814                 if (make_room_for_path(o, path) < 0) {
815                         update_wd = 0;
816                         goto free_buf;
817                 }
818                 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
819                         int fd;
820                         if (mode & 0100)
821                                 mode = 0777;
822                         else
823                                 mode = 0666;
824                         fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
825                         if (fd < 0) {
826                                 ret = err(o, _("failed to open '%s': %s"),
827                                           path, strerror(errno));
828                                 goto free_buf;
829                         }
830                         write_in_full(fd, buf, size);
831                         close(fd);
832                 } else if (S_ISLNK(mode)) {
833                         char *lnk = xmemdupz(buf, size);
834                         safe_create_leading_directories_const(path);
835                         unlink(path);
836                         if (symlink(lnk, path))
837                                 ret = err(o, _("failed to symlink '%s': %s"),
838                                         path, strerror(errno));
839                         free(lnk);
840                 } else
841                         ret = err(o,
842                                   _("do not know what to do with %06o %s '%s'"),
843                                   mode, oid_to_hex(oid), path);
844  free_buf:
845                 free(buf);
846         }
847  update_index:
848         if (!ret && update_cache)
849                 add_cacheinfo(o, mode, oid, path, 0, update_wd, ADD_CACHE_OK_TO_ADD);
850         return ret;
851 }
852
853 static int update_file(struct merge_options *o,
854                        int clean,
855                        const struct object_id *oid,
856                        unsigned mode,
857                        const char *path)
858 {
859         return update_file_flags(o, oid, mode, path, o->call_depth || clean, !o->call_depth);
860 }
861
862 /* Low level file merging, update and removal */
863
864 struct merge_file_info {
865         struct object_id oid;
866         unsigned mode;
867         unsigned clean:1,
868                  merge:1;
869 };
870
871 static int merge_3way(struct merge_options *o,
872                       mmbuffer_t *result_buf,
873                       const struct diff_filespec *one,
874                       const struct diff_filespec *a,
875                       const struct diff_filespec *b,
876                       const char *branch1,
877                       const char *branch2)
878 {
879         mmfile_t orig, src1, src2;
880         struct ll_merge_options ll_opts = {0};
881         char *base_name, *name1, *name2;
882         int merge_status;
883
884         ll_opts.renormalize = o->renormalize;
885         ll_opts.xdl_opts = o->xdl_opts;
886
887         if (o->call_depth) {
888                 ll_opts.virtual_ancestor = 1;
889                 ll_opts.variant = 0;
890         } else {
891                 switch (o->recursive_variant) {
892                 case MERGE_RECURSIVE_OURS:
893                         ll_opts.variant = XDL_MERGE_FAVOR_OURS;
894                         break;
895                 case MERGE_RECURSIVE_THEIRS:
896                         ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
897                         break;
898                 default:
899                         ll_opts.variant = 0;
900                         break;
901                 }
902         }
903
904         if (strcmp(a->path, b->path) ||
905             (o->ancestor != NULL && strcmp(a->path, one->path) != 0)) {
906                 base_name = o->ancestor == NULL ? NULL :
907                         mkpathdup("%s:%s", o->ancestor, one->path);
908                 name1 = mkpathdup("%s:%s", branch1, a->path);
909                 name2 = mkpathdup("%s:%s", branch2, b->path);
910         } else {
911                 base_name = o->ancestor == NULL ? NULL :
912                         mkpathdup("%s", o->ancestor);
913                 name1 = mkpathdup("%s", branch1);
914                 name2 = mkpathdup("%s", branch2);
915         }
916
917         read_mmblob(&orig, one->oid.hash);
918         read_mmblob(&src1, a->oid.hash);
919         read_mmblob(&src2, b->oid.hash);
920
921         merge_status = ll_merge(result_buf, a->path, &orig, base_name,
922                                 &src1, name1, &src2, name2, &ll_opts);
923
924         free(base_name);
925         free(name1);
926         free(name2);
927         free(orig.ptr);
928         free(src1.ptr);
929         free(src2.ptr);
930         return merge_status;
931 }
932
933 static int merge_file_1(struct merge_options *o,
934                                            const struct diff_filespec *one,
935                                            const struct diff_filespec *a,
936                                            const struct diff_filespec *b,
937                                            const char *branch1,
938                                            const char *branch2,
939                                            struct merge_file_info *result)
940 {
941         result->merge = 0;
942         result->clean = 1;
943
944         if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
945                 result->clean = 0;
946                 if (S_ISREG(a->mode)) {
947                         result->mode = a->mode;
948                         oidcpy(&result->oid, &a->oid);
949                 } else {
950                         result->mode = b->mode;
951                         oidcpy(&result->oid, &b->oid);
952                 }
953         } else {
954                 if (!oid_eq(&a->oid, &one->oid) && !oid_eq(&b->oid, &one->oid))
955                         result->merge = 1;
956
957                 /*
958                  * Merge modes
959                  */
960                 if (a->mode == b->mode || a->mode == one->mode)
961                         result->mode = b->mode;
962                 else {
963                         result->mode = a->mode;
964                         if (b->mode != one->mode) {
965                                 result->clean = 0;
966                                 result->merge = 1;
967                         }
968                 }
969
970                 if (oid_eq(&a->oid, &b->oid) || oid_eq(&a->oid, &one->oid))
971                         oidcpy(&result->oid, &b->oid);
972                 else if (oid_eq(&b->oid, &one->oid))
973                         oidcpy(&result->oid, &a->oid);
974                 else if (S_ISREG(a->mode)) {
975                         mmbuffer_t result_buf;
976                         int ret = 0, merge_status;
977
978                         merge_status = merge_3way(o, &result_buf, one, a, b,
979                                                   branch1, branch2);
980
981                         if ((merge_status < 0) || !result_buf.ptr)
982                                 ret = err(o, _("Failed to execute internal merge"));
983
984                         if (!ret && write_sha1_file(result_buf.ptr, result_buf.size,
985                                                     blob_type, result->oid.hash))
986                                 ret = err(o, _("Unable to add %s to database"),
987                                           a->path);
988
989                         free(result_buf.ptr);
990                         if (ret)
991                                 return ret;
992                         result->clean = (merge_status == 0);
993                 } else if (S_ISGITLINK(a->mode)) {
994                         result->clean = merge_submodule(result->oid.hash,
995                                                        one->path,
996                                                        one->oid.hash,
997                                                        a->oid.hash,
998                                                        b->oid.hash,
999                                                        !o->call_depth);
1000                 } else if (S_ISLNK(a->mode)) {
1001                         oidcpy(&result->oid, &a->oid);
1002
1003                         if (!oid_eq(&a->oid, &b->oid))
1004                                 result->clean = 0;
1005                 } else
1006                         die("BUG: unsupported object type in the tree");
1007         }
1008
1009         return 0;
1010 }
1011
1012 static int merge_file_special_markers(struct merge_options *o,
1013                            const struct diff_filespec *one,
1014                            const struct diff_filespec *a,
1015                            const struct diff_filespec *b,
1016                            const char *branch1,
1017                            const char *filename1,
1018                            const char *branch2,
1019                            const char *filename2,
1020                            struct merge_file_info *mfi)
1021 {
1022         char *side1 = NULL;
1023         char *side2 = NULL;
1024         int ret;
1025
1026         if (filename1)
1027                 side1 = xstrfmt("%s:%s", branch1, filename1);
1028         if (filename2)
1029                 side2 = xstrfmt("%s:%s", branch2, filename2);
1030
1031         ret = merge_file_1(o, one, a, b,
1032                            side1 ? side1 : branch1,
1033                            side2 ? side2 : branch2, mfi);
1034         free(side1);
1035         free(side2);
1036         return ret;
1037 }
1038
1039 static int merge_file_one(struct merge_options *o,
1040                                          const char *path,
1041                                          const struct object_id *o_oid, int o_mode,
1042                                          const struct object_id *a_oid, int a_mode,
1043                                          const struct object_id *b_oid, int b_mode,
1044                                          const char *branch1,
1045                                          const char *branch2,
1046                                          struct merge_file_info *mfi)
1047 {
1048         struct diff_filespec one, a, b;
1049
1050         one.path = a.path = b.path = (char *)path;
1051         oidcpy(&one.oid, o_oid);
1052         one.mode = o_mode;
1053         oidcpy(&a.oid, a_oid);
1054         a.mode = a_mode;
1055         oidcpy(&b.oid, b_oid);
1056         b.mode = b_mode;
1057         return merge_file_1(o, &one, &a, &b, branch1, branch2, mfi);
1058 }
1059
1060 static int handle_change_delete(struct merge_options *o,
1061                                  const char *path,
1062                                  const struct object_id *o_oid, int o_mode,
1063                                  const struct object_id *a_oid, int a_mode,
1064                                  const struct object_id *b_oid, int b_mode,
1065                                  const char *change, const char *change_past)
1066 {
1067         char *renamed = NULL;
1068         int ret = 0;
1069         if (dir_in_way(path, !o->call_depth)) {
1070                 renamed = unique_path(o, path, a_oid ? o->branch1 : o->branch2);
1071         }
1072
1073         if (o->call_depth) {
1074                 /*
1075                  * We cannot arbitrarily accept either a_sha or b_sha as
1076                  * correct; since there is no true "middle point" between
1077                  * them, simply reuse the base version for virtual merge base.
1078                  */
1079                 ret = remove_file_from_cache(path);
1080                 if (!ret)
1081                         ret = update_file(o, 0, o_oid, o_mode,
1082                                           renamed ? renamed : path);
1083         } else if (!a_oid) {
1084                 if (!renamed) {
1085                         output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1086                                "and %s in %s. Version %s of %s left in tree."),
1087                                change, path, o->branch1, change_past,
1088                                o->branch2, o->branch2, path);
1089                         ret = update_file(o, 0, b_oid, b_mode, path);
1090                 } else {
1091                         output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1092                                "and %s in %s. Version %s of %s left in tree at %s."),
1093                                change, path, o->branch1, change_past,
1094                                o->branch2, o->branch2, path, renamed);
1095                         ret = update_file(o, 0, b_oid, b_mode, renamed);
1096                 }
1097         } else {
1098                 if (!renamed) {
1099                         output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1100                                "and %s in %s. Version %s of %s left in tree."),
1101                                change, path, o->branch2, change_past,
1102                                o->branch1, o->branch1, path);
1103                 } else {
1104                         output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1105                                "and %s in %s. Version %s of %s left in tree at %s."),
1106                                change, path, o->branch2, change_past,
1107                                o->branch1, o->branch1, path, renamed);
1108                         ret = update_file(o, 0, a_oid, a_mode, renamed);
1109                 }
1110                 /*
1111                  * No need to call update_file() on path when !renamed, since
1112                  * that would needlessly touch path.  We could call
1113                  * update_file_flags() with update_cache=0 and update_wd=0,
1114                  * but that's a no-op.
1115                  */
1116         }
1117         free(renamed);
1118
1119         return ret;
1120 }
1121
1122 static int conflict_rename_delete(struct merge_options *o,
1123                                    struct diff_filepair *pair,
1124                                    const char *rename_branch,
1125                                    const char *other_branch)
1126 {
1127         const struct diff_filespec *orig = pair->one;
1128         const struct diff_filespec *dest = pair->two;
1129         const struct object_id *a_oid = NULL;
1130         const struct object_id *b_oid = NULL;
1131         int a_mode = 0;
1132         int b_mode = 0;
1133
1134         if (rename_branch == o->branch1) {
1135                 a_oid = &dest->oid;
1136                 a_mode = dest->mode;
1137         } else {
1138                 b_oid = &dest->oid;
1139                 b_mode = dest->mode;
1140         }
1141
1142         if (handle_change_delete(o,
1143                                  o->call_depth ? orig->path : dest->path,
1144                                  &orig->oid, orig->mode,
1145                                  a_oid, a_mode,
1146                                  b_oid, b_mode,
1147                                  _("rename"), _("renamed")))
1148                 return -1;
1149
1150         if (o->call_depth)
1151                 return remove_file_from_cache(dest->path);
1152         else
1153                 return update_stages(o, dest->path, NULL,
1154                                      rename_branch == o->branch1 ? dest : NULL,
1155                                      rename_branch == o->branch1 ? NULL : dest);
1156 }
1157
1158 static struct diff_filespec *filespec_from_entry(struct diff_filespec *target,
1159                                                  struct stage_data *entry,
1160                                                  int stage)
1161 {
1162         struct object_id *oid = &entry->stages[stage].oid;
1163         unsigned mode = entry->stages[stage].mode;
1164         if (mode == 0 || is_null_oid(oid))
1165                 return NULL;
1166         oidcpy(&target->oid, oid);
1167         target->mode = mode;
1168         return target;
1169 }
1170
1171 static int handle_file(struct merge_options *o,
1172                         struct diff_filespec *rename,
1173                         int stage,
1174                         struct rename_conflict_info *ci)
1175 {
1176         char *dst_name = rename->path;
1177         struct stage_data *dst_entry;
1178         const char *cur_branch, *other_branch;
1179         struct diff_filespec other;
1180         struct diff_filespec *add;
1181         int ret;
1182
1183         if (stage == 2) {
1184                 dst_entry = ci->dst_entry1;
1185                 cur_branch = ci->branch1;
1186                 other_branch = ci->branch2;
1187         } else {
1188                 dst_entry = ci->dst_entry2;
1189                 cur_branch = ci->branch2;
1190                 other_branch = ci->branch1;
1191         }
1192
1193         add = filespec_from_entry(&other, dst_entry, stage ^ 1);
1194         if (add) {
1195                 char *add_name = unique_path(o, rename->path, other_branch);
1196                 if (update_file(o, 0, &add->oid, add->mode, add_name))
1197                         return -1;
1198
1199                 remove_file(o, 0, rename->path, 0);
1200                 dst_name = unique_path(o, rename->path, cur_branch);
1201         } else {
1202                 if (dir_in_way(rename->path, !o->call_depth)) {
1203                         dst_name = unique_path(o, rename->path, cur_branch);
1204                         output(o, 1, _("%s is a directory in %s adding as %s instead"),
1205                                rename->path, other_branch, dst_name);
1206                 }
1207         }
1208         if ((ret = update_file(o, 0, &rename->oid, rename->mode, dst_name)))
1209                 ; /* fall through, do allow dst_name to be released */
1210         else if (stage == 2)
1211                 ret = update_stages(o, rename->path, NULL, rename, add);
1212         else
1213                 ret = update_stages(o, rename->path, NULL, add, rename);
1214
1215         if (dst_name != rename->path)
1216                 free(dst_name);
1217
1218         return ret;
1219 }
1220
1221 static int conflict_rename_rename_1to2(struct merge_options *o,
1222                                         struct rename_conflict_info *ci)
1223 {
1224         /* One file was renamed in both branches, but to different names. */
1225         struct diff_filespec *one = ci->pair1->one;
1226         struct diff_filespec *a = ci->pair1->two;
1227         struct diff_filespec *b = ci->pair2->two;
1228
1229         output(o, 1, _("CONFLICT (rename/rename): "
1230                "Rename \"%s\"->\"%s\" in branch \"%s\" "
1231                "rename \"%s\"->\"%s\" in \"%s\"%s"),
1232                one->path, a->path, ci->branch1,
1233                one->path, b->path, ci->branch2,
1234                o->call_depth ? _(" (left unresolved)") : "");
1235         if (o->call_depth) {
1236                 struct merge_file_info mfi;
1237                 struct diff_filespec other;
1238                 struct diff_filespec *add;
1239                 if (merge_file_one(o, one->path,
1240                                  &one->oid, one->mode,
1241                                  &a->oid, a->mode,
1242                                  &b->oid, b->mode,
1243                                  ci->branch1, ci->branch2, &mfi))
1244                         return -1;
1245
1246                 /*
1247                  * FIXME: For rename/add-source conflicts (if we could detect
1248                  * such), this is wrong.  We should instead find a unique
1249                  * pathname and then either rename the add-source file to that
1250                  * unique path, or use that unique path instead of src here.
1251                  */
1252                 if (update_file(o, 0, &mfi.oid, mfi.mode, one->path))
1253                         return -1;
1254
1255                 /*
1256                  * Above, we put the merged content at the merge-base's
1257                  * path.  Now we usually need to delete both a->path and
1258                  * b->path.  However, the rename on each side of the merge
1259                  * could also be involved in a rename/add conflict.  In
1260                  * such cases, we should keep the added file around,
1261                  * resolving the conflict at that path in its favor.
1262                  */
1263                 add = filespec_from_entry(&other, ci->dst_entry1, 2 ^ 1);
1264                 if (add) {
1265                         if (update_file(o, 0, &add->oid, add->mode, a->path))
1266                                 return -1;
1267                 }
1268                 else
1269                         remove_file_from_cache(a->path);
1270                 add = filespec_from_entry(&other, ci->dst_entry2, 3 ^ 1);
1271                 if (add) {
1272                         if (update_file(o, 0, &add->oid, add->mode, b->path))
1273                                 return -1;
1274                 }
1275                 else
1276                         remove_file_from_cache(b->path);
1277         } else if (handle_file(o, a, 2, ci) || handle_file(o, b, 3, ci))
1278                 return -1;
1279
1280         return 0;
1281 }
1282
1283 static int conflict_rename_rename_2to1(struct merge_options *o,
1284                                         struct rename_conflict_info *ci)
1285 {
1286         /* Two files, a & b, were renamed to the same thing, c. */
1287         struct diff_filespec *a = ci->pair1->one;
1288         struct diff_filespec *b = ci->pair2->one;
1289         struct diff_filespec *c1 = ci->pair1->two;
1290         struct diff_filespec *c2 = ci->pair2->two;
1291         char *path = c1->path; /* == c2->path */
1292         struct merge_file_info mfi_c1;
1293         struct merge_file_info mfi_c2;
1294         int ret;
1295
1296         output(o, 1, _("CONFLICT (rename/rename): "
1297                "Rename %s->%s in %s. "
1298                "Rename %s->%s in %s"),
1299                a->path, c1->path, ci->branch1,
1300                b->path, c2->path, ci->branch2);
1301
1302         remove_file(o, 1, a->path, o->call_depth || would_lose_untracked(a->path));
1303         remove_file(o, 1, b->path, o->call_depth || would_lose_untracked(b->path));
1304
1305         if (merge_file_special_markers(o, a, c1, &ci->ren1_other,
1306                                        o->branch1, c1->path,
1307                                        o->branch2, ci->ren1_other.path, &mfi_c1) ||
1308             merge_file_special_markers(o, b, &ci->ren2_other, c2,
1309                                        o->branch1, ci->ren2_other.path,
1310                                        o->branch2, c2->path, &mfi_c2))
1311                 return -1;
1312
1313         if (o->call_depth) {
1314                 /*
1315                  * If mfi_c1.clean && mfi_c2.clean, then it might make
1316                  * sense to do a two-way merge of those results.  But, I
1317                  * think in all cases, it makes sense to have the virtual
1318                  * merge base just undo the renames; they can be detected
1319                  * again later for the non-recursive merge.
1320                  */
1321                 remove_file(o, 0, path, 0);
1322                 ret = update_file(o, 0, &mfi_c1.oid, mfi_c1.mode, a->path);
1323                 if (!ret)
1324                         ret = update_file(o, 0, &mfi_c2.oid, mfi_c2.mode,
1325                                           b->path);
1326         } else {
1327                 char *new_path1 = unique_path(o, path, ci->branch1);
1328                 char *new_path2 = unique_path(o, path, ci->branch2);
1329                 output(o, 1, _("Renaming %s to %s and %s to %s instead"),
1330                        a->path, new_path1, b->path, new_path2);
1331                 remove_file(o, 0, path, 0);
1332                 ret = update_file(o, 0, &mfi_c1.oid, mfi_c1.mode, new_path1);
1333                 if (!ret)
1334                         ret = update_file(o, 0, &mfi_c2.oid, mfi_c2.mode,
1335                                           new_path2);
1336                 free(new_path2);
1337                 free(new_path1);
1338         }
1339
1340         return ret;
1341 }
1342
1343 static int process_renames(struct merge_options *o,
1344                            struct string_list *a_renames,
1345                            struct string_list *b_renames)
1346 {
1347         int clean_merge = 1, i, j;
1348         struct string_list a_by_dst = STRING_LIST_INIT_NODUP;
1349         struct string_list b_by_dst = STRING_LIST_INIT_NODUP;
1350         const struct rename *sre;
1351
1352         for (i = 0; i < a_renames->nr; i++) {
1353                 sre = a_renames->items[i].util;
1354                 string_list_insert(&a_by_dst, sre->pair->two->path)->util
1355                         = (void *)sre;
1356         }
1357         for (i = 0; i < b_renames->nr; i++) {
1358                 sre = b_renames->items[i].util;
1359                 string_list_insert(&b_by_dst, sre->pair->two->path)->util
1360                         = (void *)sre;
1361         }
1362
1363         for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
1364                 struct string_list *renames1, *renames2Dst;
1365                 struct rename *ren1 = NULL, *ren2 = NULL;
1366                 const char *branch1, *branch2;
1367                 const char *ren1_src, *ren1_dst;
1368                 struct string_list_item *lookup;
1369
1370                 if (i >= a_renames->nr) {
1371                         ren2 = b_renames->items[j++].util;
1372                 } else if (j >= b_renames->nr) {
1373                         ren1 = a_renames->items[i++].util;
1374                 } else {
1375                         int compare = strcmp(a_renames->items[i].string,
1376                                              b_renames->items[j].string);
1377                         if (compare <= 0)
1378                                 ren1 = a_renames->items[i++].util;
1379                         if (compare >= 0)
1380                                 ren2 = b_renames->items[j++].util;
1381                 }
1382
1383                 /* TODO: refactor, so that 1/2 are not needed */
1384                 if (ren1) {
1385                         renames1 = a_renames;
1386                         renames2Dst = &b_by_dst;
1387                         branch1 = o->branch1;
1388                         branch2 = o->branch2;
1389                 } else {
1390                         struct rename *tmp;
1391                         renames1 = b_renames;
1392                         renames2Dst = &a_by_dst;
1393                         branch1 = o->branch2;
1394                         branch2 = o->branch1;
1395                         tmp = ren2;
1396                         ren2 = ren1;
1397                         ren1 = tmp;
1398                 }
1399
1400                 if (ren1->processed)
1401                         continue;
1402                 ren1->processed = 1;
1403                 ren1->dst_entry->processed = 1;
1404                 /* BUG: We should only mark src_entry as processed if we
1405                  * are not dealing with a rename + add-source case.
1406                  */
1407                 ren1->src_entry->processed = 1;
1408
1409                 ren1_src = ren1->pair->one->path;
1410                 ren1_dst = ren1->pair->two->path;
1411
1412                 if (ren2) {
1413                         /* One file renamed on both sides */
1414                         const char *ren2_src = ren2->pair->one->path;
1415                         const char *ren2_dst = ren2->pair->two->path;
1416                         enum rename_type rename_type;
1417                         if (strcmp(ren1_src, ren2_src) != 0)
1418                                 die("BUG: ren1_src != ren2_src");
1419                         ren2->dst_entry->processed = 1;
1420                         ren2->processed = 1;
1421                         if (strcmp(ren1_dst, ren2_dst) != 0) {
1422                                 rename_type = RENAME_ONE_FILE_TO_TWO;
1423                                 clean_merge = 0;
1424                         } else {
1425                                 rename_type = RENAME_ONE_FILE_TO_ONE;
1426                                 /* BUG: We should only remove ren1_src in
1427                                  * the base stage (think of rename +
1428                                  * add-source cases).
1429                                  */
1430                                 remove_file(o, 1, ren1_src, 1);
1431                                 update_entry(ren1->dst_entry,
1432                                              ren1->pair->one,
1433                                              ren1->pair->two,
1434                                              ren2->pair->two);
1435                         }
1436                         setup_rename_conflict_info(rename_type,
1437                                                    ren1->pair,
1438                                                    ren2->pair,
1439                                                    branch1,
1440                                                    branch2,
1441                                                    ren1->dst_entry,
1442                                                    ren2->dst_entry,
1443                                                    o,
1444                                                    NULL,
1445                                                    NULL);
1446                 } else if ((lookup = string_list_lookup(renames2Dst, ren1_dst))) {
1447                         /* Two different files renamed to the same thing */
1448                         char *ren2_dst;
1449                         ren2 = lookup->util;
1450                         ren2_dst = ren2->pair->two->path;
1451                         if (strcmp(ren1_dst, ren2_dst) != 0)
1452                                 die("BUG: ren1_dst != ren2_dst");
1453
1454                         clean_merge = 0;
1455                         ren2->processed = 1;
1456                         /*
1457                          * BUG: We should only mark src_entry as processed
1458                          * if we are not dealing with a rename + add-source
1459                          * case.
1460                          */
1461                         ren2->src_entry->processed = 1;
1462
1463                         setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,
1464                                                    ren1->pair,
1465                                                    ren2->pair,
1466                                                    branch1,
1467                                                    branch2,
1468                                                    ren1->dst_entry,
1469                                                    ren2->dst_entry,
1470                                                    o,
1471                                                    ren1->src_entry,
1472                                                    ren2->src_entry);
1473
1474                 } else {
1475                         /* Renamed in 1, maybe changed in 2 */
1476                         /* we only use sha1 and mode of these */
1477                         struct diff_filespec src_other, dst_other;
1478                         int try_merge;
1479
1480                         /*
1481                          * unpack_trees loads entries from common-commit
1482                          * into stage 1, from head-commit into stage 2, and
1483                          * from merge-commit into stage 3.  We keep track
1484                          * of which side corresponds to the rename.
1485                          */
1486                         int renamed_stage = a_renames == renames1 ? 2 : 3;
1487                         int other_stage =   a_renames == renames1 ? 3 : 2;
1488
1489                         /* BUG: We should only remove ren1_src in the base
1490                          * stage and in other_stage (think of rename +
1491                          * add-source case).
1492                          */
1493                         remove_file(o, 1, ren1_src,
1494                                     renamed_stage == 2 || !was_tracked(ren1_src));
1495
1496                         oidcpy(&src_other.oid,
1497                                &ren1->src_entry->stages[other_stage].oid);
1498                         src_other.mode = ren1->src_entry->stages[other_stage].mode;
1499                         oidcpy(&dst_other.oid,
1500                                &ren1->dst_entry->stages[other_stage].oid);
1501                         dst_other.mode = ren1->dst_entry->stages[other_stage].mode;
1502                         try_merge = 0;
1503
1504                         if (oid_eq(&src_other.oid, &null_oid)) {
1505                                 setup_rename_conflict_info(RENAME_DELETE,
1506                                                            ren1->pair,
1507                                                            NULL,
1508                                                            branch1,
1509                                                            branch2,
1510                                                            ren1->dst_entry,
1511                                                            NULL,
1512                                                            o,
1513                                                            NULL,
1514                                                            NULL);
1515                         } else if ((dst_other.mode == ren1->pair->two->mode) &&
1516                                    oid_eq(&dst_other.oid, &ren1->pair->two->oid)) {
1517                                 /*
1518                                  * Added file on the other side identical to
1519                                  * the file being renamed: clean merge.
1520                                  * Also, there is no need to overwrite the
1521                                  * file already in the working copy, so call
1522                                  * update_file_flags() instead of
1523                                  * update_file().
1524                                  */
1525                                 if (update_file_flags(o,
1526                                                       &ren1->pair->two->oid,
1527                                                       ren1->pair->two->mode,
1528                                                       ren1_dst,
1529                                                       1, /* update_cache */
1530                                                       0  /* update_wd    */))
1531                                         clean_merge = -1;
1532                         } else if (!oid_eq(&dst_other.oid, &null_oid)) {
1533                                 clean_merge = 0;
1534                                 try_merge = 1;
1535                                 output(o, 1, _("CONFLICT (rename/add): Rename %s->%s in %s. "
1536                                        "%s added in %s"),
1537                                        ren1_src, ren1_dst, branch1,
1538                                        ren1_dst, branch2);
1539                                 if (o->call_depth) {
1540                                         struct merge_file_info mfi;
1541                                         if (merge_file_one(o, ren1_dst, &null_oid, 0,
1542                                                            &ren1->pair->two->oid,
1543                                                            ren1->pair->two->mode,
1544                                                            &dst_other.oid,
1545                                                            dst_other.mode,
1546                                                            branch1, branch2, &mfi)) {
1547                                                 clean_merge = -1;
1548                                                 goto cleanup_and_return;
1549                                         }
1550                                         output(o, 1, _("Adding merged %s"), ren1_dst);
1551                                         if (update_file(o, 0, &mfi.oid,
1552                                                         mfi.mode, ren1_dst))
1553                                                 clean_merge = -1;
1554                                         try_merge = 0;
1555                                 } else {
1556                                         char *new_path = unique_path(o, ren1_dst, branch2);
1557                                         output(o, 1, _("Adding as %s instead"), new_path);
1558                                         if (update_file(o, 0, &dst_other.oid,
1559                                                         dst_other.mode, new_path))
1560                                                 clean_merge = -1;
1561                                         free(new_path);
1562                                 }
1563                         } else
1564                                 try_merge = 1;
1565
1566                         if (clean_merge < 0)
1567                                 goto cleanup_and_return;
1568                         if (try_merge) {
1569                                 struct diff_filespec *one, *a, *b;
1570                                 src_other.path = (char *)ren1_src;
1571
1572                                 one = ren1->pair->one;
1573                                 if (a_renames == renames1) {
1574                                         a = ren1->pair->two;
1575                                         b = &src_other;
1576                                 } else {
1577                                         b = ren1->pair->two;
1578                                         a = &src_other;
1579                                 }
1580                                 update_entry(ren1->dst_entry, one, a, b);
1581                                 setup_rename_conflict_info(RENAME_NORMAL,
1582                                                            ren1->pair,
1583                                                            NULL,
1584                                                            branch1,
1585                                                            NULL,
1586                                                            ren1->dst_entry,
1587                                                            NULL,
1588                                                            o,
1589                                                            NULL,
1590                                                            NULL);
1591                         }
1592                 }
1593         }
1594 cleanup_and_return:
1595         string_list_clear(&a_by_dst, 0);
1596         string_list_clear(&b_by_dst, 0);
1597
1598         return clean_merge;
1599 }
1600
1601 static struct object_id *stage_oid(const struct object_id *oid, unsigned mode)
1602 {
1603         return (is_null_oid(oid) || mode == 0) ? NULL: (struct object_id *)oid;
1604 }
1605
1606 static int read_oid_strbuf(struct merge_options *o,
1607         const struct object_id *oid, struct strbuf *dst)
1608 {
1609         void *buf;
1610         enum object_type type;
1611         unsigned long size;
1612         buf = read_sha1_file(oid->hash, &type, &size);
1613         if (!buf)
1614                 return err(o, _("cannot read object %s"), oid_to_hex(oid));
1615         if (type != OBJ_BLOB) {
1616                 free(buf);
1617                 return err(o, _("object %s is not a blob"), oid_to_hex(oid));
1618         }
1619         strbuf_attach(dst, buf, size, size + 1);
1620         return 0;
1621 }
1622
1623 static int blob_unchanged(struct merge_options *opt,
1624                           const struct object_id *o_oid,
1625                           unsigned o_mode,
1626                           const struct object_id *a_oid,
1627                           unsigned a_mode,
1628                           int renormalize, const char *path)
1629 {
1630         struct strbuf o = STRBUF_INIT;
1631         struct strbuf a = STRBUF_INIT;
1632         int ret = 0; /* assume changed for safety */
1633
1634         if (a_mode != o_mode)
1635                 return 0;
1636         if (oid_eq(o_oid, a_oid))
1637                 return 1;
1638         if (!renormalize)
1639                 return 0;
1640
1641         assert(o_oid && a_oid);
1642         if (read_oid_strbuf(opt, o_oid, &o) || read_oid_strbuf(opt, a_oid, &a))
1643                 goto error_return;
1644         /*
1645          * Note: binary | is used so that both renormalizations are
1646          * performed.  Comparison can be skipped if both files are
1647          * unchanged since their sha1s have already been compared.
1648          */
1649         if (renormalize_buffer(path, o.buf, o.len, &o) |
1650             renormalize_buffer(path, a.buf, a.len, &a))
1651                 ret = (o.len == a.len && !memcmp(o.buf, a.buf, o.len));
1652
1653 error_return:
1654         strbuf_release(&o);
1655         strbuf_release(&a);
1656         return ret;
1657 }
1658
1659 static int handle_modify_delete(struct merge_options *o,
1660                                  const char *path,
1661                                  struct object_id *o_oid, int o_mode,
1662                                  struct object_id *a_oid, int a_mode,
1663                                  struct object_id *b_oid, int b_mode)
1664 {
1665         return handle_change_delete(o,
1666                                     path,
1667                                     o_oid, o_mode,
1668                                     a_oid, a_mode,
1669                                     b_oid, b_mode,
1670                                     _("modify"), _("modified"));
1671 }
1672
1673 static int merge_content(struct merge_options *o,
1674                          const char *path,
1675                          struct object_id *o_oid, int o_mode,
1676                          struct object_id *a_oid, int a_mode,
1677                          struct object_id *b_oid, int b_mode,
1678                          struct rename_conflict_info *rename_conflict_info)
1679 {
1680         const char *reason = _("content");
1681         const char *path1 = NULL, *path2 = NULL;
1682         struct merge_file_info mfi;
1683         struct diff_filespec one, a, b;
1684         unsigned df_conflict_remains = 0;
1685
1686         if (!o_oid) {
1687                 reason = _("add/add");
1688                 o_oid = (struct object_id *)&null_oid;
1689         }
1690         one.path = a.path = b.path = (char *)path;
1691         oidcpy(&one.oid, o_oid);
1692         one.mode = o_mode;
1693         oidcpy(&a.oid, a_oid);
1694         a.mode = a_mode;
1695         oidcpy(&b.oid, b_oid);
1696         b.mode = b_mode;
1697
1698         if (rename_conflict_info) {
1699                 struct diff_filepair *pair1 = rename_conflict_info->pair1;
1700
1701                 path1 = (o->branch1 == rename_conflict_info->branch1) ?
1702                         pair1->two->path : pair1->one->path;
1703                 /* If rename_conflict_info->pair2 != NULL, we are in
1704                  * RENAME_ONE_FILE_TO_ONE case.  Otherwise, we have a
1705                  * normal rename.
1706                  */
1707                 path2 = (rename_conflict_info->pair2 ||
1708                          o->branch2 == rename_conflict_info->branch1) ?
1709                         pair1->two->path : pair1->one->path;
1710
1711                 if (dir_in_way(path, !o->call_depth))
1712                         df_conflict_remains = 1;
1713         }
1714         if (merge_file_special_markers(o, &one, &a, &b,
1715                                        o->branch1, path1,
1716                                        o->branch2, path2, &mfi))
1717                 return -1;
1718
1719         if (mfi.clean && !df_conflict_remains &&
1720             oid_eq(&mfi.oid, a_oid) && mfi.mode == a_mode) {
1721                 int path_renamed_outside_HEAD;
1722                 output(o, 3, _("Skipped %s (merged same as existing)"), path);
1723                 /*
1724                  * The content merge resulted in the same file contents we
1725                  * already had.  We can return early if those file contents
1726                  * are recorded at the correct path (which may not be true
1727                  * if the merge involves a rename).
1728                  */
1729                 path_renamed_outside_HEAD = !path2 || !strcmp(path, path2);
1730                 if (!path_renamed_outside_HEAD) {
1731                         add_cacheinfo(o, mfi.mode, &mfi.oid, path,
1732                                       0, (!o->call_depth), 0);
1733                         return mfi.clean;
1734                 }
1735         } else
1736                 output(o, 2, _("Auto-merging %s"), path);
1737
1738         if (!mfi.clean) {
1739                 if (S_ISGITLINK(mfi.mode))
1740                         reason = _("submodule");
1741                 output(o, 1, _("CONFLICT (%s): Merge conflict in %s"),
1742                                 reason, path);
1743                 if (rename_conflict_info && !df_conflict_remains)
1744                         if (update_stages(o, path, &one, &a, &b))
1745                                 return -1;
1746         }
1747
1748         if (df_conflict_remains) {
1749                 char *new_path;
1750                 if (o->call_depth) {
1751                         remove_file_from_cache(path);
1752                 } else {
1753                         if (!mfi.clean) {
1754                                 if (update_stages(o, path, &one, &a, &b))
1755                                         return -1;
1756                         } else {
1757                                 int file_from_stage2 = was_tracked(path);
1758                                 struct diff_filespec merged;
1759                                 oidcpy(&merged.oid, &mfi.oid);
1760                                 merged.mode = mfi.mode;
1761
1762                                 if (update_stages(o, path, NULL,
1763                                                   file_from_stage2 ? &merged : NULL,
1764                                                   file_from_stage2 ? NULL : &merged))
1765                                         return -1;
1766                         }
1767
1768                 }
1769                 new_path = unique_path(o, path, rename_conflict_info->branch1);
1770                 output(o, 1, _("Adding as %s instead"), new_path);
1771                 if (update_file(o, 0, &mfi.oid, mfi.mode, new_path)) {
1772                         free(new_path);
1773                         return -1;
1774                 }
1775                 free(new_path);
1776                 mfi.clean = 0;
1777         } else if (update_file(o, mfi.clean, &mfi.oid, mfi.mode, path))
1778                 return -1;
1779         return mfi.clean;
1780 }
1781
1782 /* Per entry merge function */
1783 static int process_entry(struct merge_options *o,
1784                          const char *path, struct stage_data *entry)
1785 {
1786         int clean_merge = 1;
1787         int normalize = o->renormalize;
1788         unsigned o_mode = entry->stages[1].mode;
1789         unsigned a_mode = entry->stages[2].mode;
1790         unsigned b_mode = entry->stages[3].mode;
1791         struct object_id *o_oid = stage_oid(&entry->stages[1].oid, o_mode);
1792         struct object_id *a_oid = stage_oid(&entry->stages[2].oid, a_mode);
1793         struct object_id *b_oid = stage_oid(&entry->stages[3].oid, b_mode);
1794
1795         entry->processed = 1;
1796         if (entry->rename_conflict_info) {
1797                 struct rename_conflict_info *conflict_info = entry->rename_conflict_info;
1798                 switch (conflict_info->rename_type) {
1799                 case RENAME_NORMAL:
1800                 case RENAME_ONE_FILE_TO_ONE:
1801                         clean_merge = merge_content(o, path,
1802                                                     o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,
1803                                                     conflict_info);
1804                         break;
1805                 case RENAME_DELETE:
1806                         clean_merge = 0;
1807                         if (conflict_rename_delete(o,
1808                                                    conflict_info->pair1,
1809                                                    conflict_info->branch1,
1810                                                    conflict_info->branch2))
1811                                 clean_merge = -1;
1812                         break;
1813                 case RENAME_ONE_FILE_TO_TWO:
1814                         clean_merge = 0;
1815                         if (conflict_rename_rename_1to2(o, conflict_info))
1816                                 clean_merge = -1;
1817                         break;
1818                 case RENAME_TWO_FILES_TO_ONE:
1819                         clean_merge = 0;
1820                         if (conflict_rename_rename_2to1(o, conflict_info))
1821                                 clean_merge = -1;
1822                         break;
1823                 default:
1824                         entry->processed = 0;
1825                         break;
1826                 }
1827         } else if (o_oid && (!a_oid || !b_oid)) {
1828                 /* Case A: Deleted in one */
1829                 if ((!a_oid && !b_oid) ||
1830                     (!b_oid && blob_unchanged(o, o_oid, o_mode, a_oid, a_mode, normalize, path)) ||
1831                     (!a_oid && blob_unchanged(o, o_oid, o_mode, b_oid, b_mode, normalize, path))) {
1832                         /* Deleted in both or deleted in one and
1833                          * unchanged in the other */
1834                         if (a_oid)
1835                                 output(o, 2, _("Removing %s"), path);
1836                         /* do not touch working file if it did not exist */
1837                         remove_file(o, 1, path, !a_oid);
1838                 } else {
1839                         /* Modify/delete; deleted side may have put a directory in the way */
1840                         clean_merge = 0;
1841                         if (handle_modify_delete(o, path, o_oid, o_mode,
1842                                                  a_oid, a_mode, b_oid, b_mode))
1843                                 clean_merge = -1;
1844                 }
1845         } else if ((!o_oid && a_oid && !b_oid) ||
1846                    (!o_oid && !a_oid && b_oid)) {
1847                 /* Case B: Added in one. */
1848                 /* [nothing|directory] -> ([nothing|directory], file) */
1849
1850                 const char *add_branch;
1851                 const char *other_branch;
1852                 unsigned mode;
1853                 const struct object_id *oid;
1854                 const char *conf;
1855
1856                 if (a_oid) {
1857                         add_branch = o->branch1;
1858                         other_branch = o->branch2;
1859                         mode = a_mode;
1860                         oid = a_oid;
1861                         conf = _("file/directory");
1862                 } else {
1863                         add_branch = o->branch2;
1864                         other_branch = o->branch1;
1865                         mode = b_mode;
1866                         oid = b_oid;
1867                         conf = _("directory/file");
1868                 }
1869                 if (dir_in_way(path, !o->call_depth)) {
1870                         char *new_path = unique_path(o, path, add_branch);
1871                         clean_merge = 0;
1872                         output(o, 1, _("CONFLICT (%s): There is a directory with name %s in %s. "
1873                                "Adding %s as %s"),
1874                                conf, path, other_branch, path, new_path);
1875                         if (update_file(o, 0, oid, mode, new_path))
1876                                 clean_merge = -1;
1877                         else if (o->call_depth)
1878                                 remove_file_from_cache(path);
1879                         free(new_path);
1880                 } else {
1881                         output(o, 2, _("Adding %s"), path);
1882                         /* do not overwrite file if already present */
1883                         if (update_file_flags(o, oid, mode, path, 1, !a_oid))
1884                                 clean_merge = -1;
1885                 }
1886         } else if (a_oid && b_oid) {
1887                 /* Case C: Added in both (check for same permissions) and */
1888                 /* case D: Modified in both, but differently. */
1889                 clean_merge = merge_content(o, path,
1890                                             o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,
1891                                             NULL);
1892         } else if (!o_oid && !a_oid && !b_oid) {
1893                 /*
1894                  * this entry was deleted altogether. a_mode == 0 means
1895                  * we had that path and want to actively remove it.
1896                  */
1897                 remove_file(o, 1, path, !a_mode);
1898         } else
1899                 die("BUG: fatal merge failure, shouldn't happen.");
1900
1901         return clean_merge;
1902 }
1903
1904 int merge_trees(struct merge_options *o,
1905                 struct tree *head,
1906                 struct tree *merge,
1907                 struct tree *common,
1908                 struct tree **result)
1909 {
1910         int code, clean;
1911
1912         if (o->subtree_shift) {
1913                 merge = shift_tree_object(head, merge, o->subtree_shift);
1914                 common = shift_tree_object(head, common, o->subtree_shift);
1915         }
1916
1917         if (oid_eq(&common->object.oid, &merge->object.oid)) {
1918                 output(o, 0, _("Already up-to-date!"));
1919                 *result = head;
1920                 return 1;
1921         }
1922
1923         code = git_merge_trees(o->call_depth, common, head, merge);
1924
1925         if (code != 0) {
1926                 if (show(o, 4) || o->call_depth)
1927                         err(o, _("merging of trees %s and %s failed"),
1928                             oid_to_hex(&head->object.oid),
1929                             oid_to_hex(&merge->object.oid));
1930                 return -1;
1931         }
1932
1933         if (unmerged_cache()) {
1934                 struct string_list *entries, *re_head, *re_merge;
1935                 int i;
1936                 string_list_clear(&o->current_file_set, 1);
1937                 string_list_clear(&o->current_directory_set, 1);
1938                 get_files_dirs(o, head);
1939                 get_files_dirs(o, merge);
1940
1941                 entries = get_unmerged();
1942                 record_df_conflict_files(o, entries);
1943                 re_head  = get_renames(o, head, common, head, merge, entries);
1944                 re_merge = get_renames(o, merge, common, head, merge, entries);
1945                 clean = process_renames(o, re_head, re_merge);
1946                 if (clean < 0)
1947                         return clean;
1948                 for (i = entries->nr-1; 0 <= i; i--) {
1949                         const char *path = entries->items[i].string;
1950                         struct stage_data *e = entries->items[i].util;
1951                         if (!e->processed) {
1952                                 int ret = process_entry(o, path, e);
1953                                 if (!ret)
1954                                         clean = 0;
1955                                 else if (ret < 0)
1956                                         return ret;
1957                         }
1958                 }
1959                 for (i = 0; i < entries->nr; i++) {
1960                         struct stage_data *e = entries->items[i].util;
1961                         if (!e->processed)
1962                                 die("BUG: unprocessed path??? %s",
1963                                     entries->items[i].string);
1964                 }
1965
1966                 string_list_clear(re_merge, 0);
1967                 string_list_clear(re_head, 0);
1968                 string_list_clear(entries, 1);
1969
1970                 free(re_merge);
1971                 free(re_head);
1972                 free(entries);
1973         }
1974         else
1975                 clean = 1;
1976
1977         if (o->call_depth && !(*result = write_tree_from_memory(o)))
1978                 return -1;
1979
1980         return clean;
1981 }
1982
1983 static struct commit_list *reverse_commit_list(struct commit_list *list)
1984 {
1985         struct commit_list *next = NULL, *current, *backup;
1986         for (current = list; current; current = backup) {
1987                 backup = current->next;
1988                 current->next = next;
1989                 next = current;
1990         }
1991         return next;
1992 }
1993
1994 /*
1995  * Merge the commits h1 and h2, return the resulting virtual
1996  * commit object and a flag indicating the cleanness of the merge.
1997  */
1998 int merge_recursive(struct merge_options *o,
1999                     struct commit *h1,
2000                     struct commit *h2,
2001                     struct commit_list *ca,
2002                     struct commit **result)
2003 {
2004         struct commit_list *iter;
2005         struct commit *merged_common_ancestors;
2006         struct tree *mrtree = mrtree;
2007         int clean;
2008
2009         if (show(o, 4)) {
2010                 output(o, 4, _("Merging:"));
2011                 output_commit_title(o, h1);
2012                 output_commit_title(o, h2);
2013         }
2014
2015         if (!ca) {
2016                 ca = get_merge_bases(h1, h2);
2017                 ca = reverse_commit_list(ca);
2018         }
2019
2020         if (show(o, 5)) {
2021                 unsigned cnt = commit_list_count(ca);
2022
2023                 output(o, 5, Q_("found %u common ancestor:",
2024                                 "found %u common ancestors:", cnt), cnt);
2025                 for (iter = ca; iter; iter = iter->next)
2026                         output_commit_title(o, iter->item);
2027         }
2028
2029         merged_common_ancestors = pop_commit(&ca);
2030         if (merged_common_ancestors == NULL) {
2031                 /* if there is no common ancestor, use an empty tree */
2032                 struct tree *tree;
2033
2034                 tree = lookup_tree(EMPTY_TREE_SHA1_BIN);
2035                 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
2036         }
2037
2038         for (iter = ca; iter; iter = iter->next) {
2039                 const char *saved_b1, *saved_b2;
2040                 o->call_depth++;
2041                 /*
2042                  * When the merge fails, the result contains files
2043                  * with conflict markers. The cleanness flag is
2044                  * ignored (unless indicating an error), it was never
2045                  * actually used, as result of merge_trees has always
2046                  * overwritten it: the committed "conflicts" were
2047                  * already resolved.
2048                  */
2049                 discard_cache();
2050                 saved_b1 = o->branch1;
2051                 saved_b2 = o->branch2;
2052                 o->branch1 = "Temporary merge branch 1";
2053                 o->branch2 = "Temporary merge branch 2";
2054                 if (merge_recursive(o, merged_common_ancestors, iter->item,
2055                                     NULL, &merged_common_ancestors) < 0)
2056                         return -1;
2057                 o->branch1 = saved_b1;
2058                 o->branch2 = saved_b2;
2059                 o->call_depth--;
2060
2061                 if (!merged_common_ancestors)
2062                         return err(o, _("merge returned no commit"));
2063         }
2064
2065         discard_cache();
2066         if (!o->call_depth)
2067                 read_cache();
2068
2069         o->ancestor = "merged common ancestors";
2070         clean = merge_trees(o, h1->tree, h2->tree, merged_common_ancestors->tree,
2071                             &mrtree);
2072         if (clean < 0) {
2073                 flush_output(o);
2074                 return clean;
2075         }
2076
2077         if (o->call_depth) {
2078                 *result = make_virtual_commit(mrtree, "merged tree");
2079                 commit_list_insert(h1, &(*result)->parents);
2080                 commit_list_insert(h2, &(*result)->parents->next);
2081         }
2082         flush_output(o);
2083         if (!o->call_depth && o->buffer_output < 2)
2084                 strbuf_release(&o->obuf);
2085         if (show(o, 2))
2086                 diff_warn_rename_limit("merge.renamelimit",
2087                                        o->needed_rename_limit, 0);
2088         return clean;
2089 }
2090
2091 static struct commit *get_ref(const struct object_id *oid, const char *name)
2092 {
2093         struct object *object;
2094
2095         object = deref_tag(parse_object(oid->hash), name, strlen(name));
2096         if (!object)
2097                 return NULL;
2098         if (object->type == OBJ_TREE)
2099                 return make_virtual_commit((struct tree*)object, name);
2100         if (object->type != OBJ_COMMIT)
2101                 return NULL;
2102         if (parse_commit((struct commit *)object))
2103                 return NULL;
2104         return (struct commit *)object;
2105 }
2106
2107 int merge_recursive_generic(struct merge_options *o,
2108                             const struct object_id *head,
2109                             const struct object_id *merge,
2110                             int num_base_list,
2111                             const struct object_id **base_list,
2112                             struct commit **result)
2113 {
2114         int clean;
2115         struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
2116         struct commit *head_commit = get_ref(head, o->branch1);
2117         struct commit *next_commit = get_ref(merge, o->branch2);
2118         struct commit_list *ca = NULL;
2119
2120         if (base_list) {
2121                 int i;
2122                 for (i = 0; i < num_base_list; ++i) {
2123                         struct commit *base;
2124                         if (!(base = get_ref(base_list[i], oid_to_hex(base_list[i]))))
2125                                 return err(o, _("Could not parse object '%s'"),
2126                                         oid_to_hex(base_list[i]));
2127                         commit_list_insert(base, &ca);
2128                 }
2129         }
2130
2131         hold_locked_index(lock, 1);
2132         clean = merge_recursive(o, head_commit, next_commit, ca,
2133                         result);
2134         if (clean < 0)
2135                 return clean;
2136
2137         if (active_cache_changed &&
2138             write_locked_index(&the_index, lock, COMMIT_LOCK))
2139                 return err(o, _("Unable to write index."));
2140
2141         return clean ? 0 : 1;
2142 }
2143
2144 static void merge_recursive_config(struct merge_options *o)
2145 {
2146         git_config_get_int("merge.verbosity", &o->verbosity);
2147         git_config_get_int("diff.renamelimit", &o->diff_rename_limit);
2148         git_config_get_int("merge.renamelimit", &o->merge_rename_limit);
2149         git_config(git_xmerge_config, NULL);
2150 }
2151
2152 void init_merge_options(struct merge_options *o)
2153 {
2154         memset(o, 0, sizeof(struct merge_options));
2155         o->verbosity = 2;
2156         o->buffer_output = 1;
2157         o->diff_rename_limit = -1;
2158         o->merge_rename_limit = -1;
2159         o->renormalize = 0;
2160         o->detect_rename = 1;
2161         merge_recursive_config(o);
2162         if (getenv("GIT_MERGE_VERBOSITY"))
2163                 o->verbosity =
2164                         strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10);
2165         if (o->verbosity >= 5)
2166                 o->buffer_output = 0;
2167         strbuf_init(&o->obuf, 0);
2168         string_list_init(&o->current_file_set, 1);
2169         string_list_init(&o->current_directory_set, 1);
2170         string_list_init(&o->df_conflict_file_set, 1);
2171 }
2172
2173 int parse_merge_opt(struct merge_options *o, const char *s)
2174 {
2175         const char *arg;
2176
2177         if (!s || !*s)
2178                 return -1;
2179         if (!strcmp(s, "ours"))
2180                 o->recursive_variant = MERGE_RECURSIVE_OURS;
2181         else if (!strcmp(s, "theirs"))
2182                 o->recursive_variant = MERGE_RECURSIVE_THEIRS;
2183         else if (!strcmp(s, "subtree"))
2184                 o->subtree_shift = "";
2185         else if (skip_prefix(s, "subtree=", &arg))
2186                 o->subtree_shift = arg;
2187         else if (!strcmp(s, "patience"))
2188                 o->xdl_opts = DIFF_WITH_ALG(o, PATIENCE_DIFF);
2189         else if (!strcmp(s, "histogram"))
2190                 o->xdl_opts = DIFF_WITH_ALG(o, HISTOGRAM_DIFF);
2191         else if (skip_prefix(s, "diff-algorithm=", &arg)) {
2192                 long value = parse_algorithm_value(arg);
2193                 if (value < 0)
2194                         return -1;
2195                 /* clear out previous settings */
2196                 DIFF_XDL_CLR(o, NEED_MINIMAL);
2197                 o->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
2198                 o->xdl_opts |= value;
2199         }
2200         else if (!strcmp(s, "ignore-space-change"))
2201                 o->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2202         else if (!strcmp(s, "ignore-all-space"))
2203                 o->xdl_opts |= XDF_IGNORE_WHITESPACE;
2204         else if (!strcmp(s, "ignore-space-at-eol"))
2205                 o->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2206         else if (!strcmp(s, "renormalize"))
2207                 o->renormalize = 1;
2208         else if (!strcmp(s, "no-renormalize"))
2209                 o->renormalize = 0;
2210         else if (!strcmp(s, "no-renames"))
2211                 o->detect_rename = 0;
2212         else if (!strcmp(s, "find-renames")) {
2213                 o->detect_rename = 1;
2214                 o->rename_score = 0;
2215         }
2216         else if (skip_prefix(s, "find-renames=", &arg) ||
2217                  skip_prefix(s, "rename-threshold=", &arg)) {
2218                 if ((o->rename_score = parse_rename_score(&arg)) == -1 || *arg != 0)
2219                         return -1;
2220                 o->detect_rename = 1;
2221         }
2222         else
2223                 return -1;
2224         return 0;
2225 }