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