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