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