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