Merge branch 'nd/repo-clear-keep-the-index'
[git] / merge-recursive.c
1 /*
2  * Recursive Merge algorithm stolen from git-merge-recursive.py by
3  * Fredrik Kuivinen.
4  * The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006
5  */
6 #include "cache.h"
7 #include "config.h"
8 #include "advice.h"
9 #include "lockfile.h"
10 #include "cache-tree.h"
11 #include "commit.h"
12 #include "blob.h"
13 #include "builtin.h"
14 #include "tree-walk.h"
15 #include "diff.h"
16 #include "diffcore.h"
17 #include "tag.h"
18 #include "unpack-trees.h"
19 #include "string-list.h"
20 #include "xdiff-interface.h"
21 #include "ll-merge.h"
22 #include "attr.h"
23 #include "merge-recursive.h"
24 #include "dir.h"
25 #include "submodule.h"
26
27 struct path_hashmap_entry {
28         struct hashmap_entry e;
29         char path[FLEX_ARRAY];
30 };
31
32 static int path_hashmap_cmp(const void *cmp_data,
33                             const void *entry,
34                             const void *entry_or_key,
35                             const void *keydata)
36 {
37         const struct path_hashmap_entry *a = entry;
38         const struct path_hashmap_entry *b = entry_or_key;
39         const char *key = keydata;
40
41         if (ignore_case)
42                 return strcasecmp(a->path, key ? key : b->path);
43         else
44                 return strcmp(a->path, key ? key : b->path);
45 }
46
47 static unsigned int path_hash(const char *path)
48 {
49         return ignore_case ? strihash(path) : strhash(path);
50 }
51
52 static struct dir_rename_entry *dir_rename_find_entry(struct hashmap *hashmap,
53                                                       char *dir)
54 {
55         struct dir_rename_entry key;
56
57         if (dir == NULL)
58                 return NULL;
59         hashmap_entry_init(&key, strhash(dir));
60         key.dir = dir;
61         return hashmap_get(hashmap, &key, NULL);
62 }
63
64 static int dir_rename_cmp(const void *unused_cmp_data,
65                           const void *entry,
66                           const void *entry_or_key,
67                           const void *unused_keydata)
68 {
69         const struct dir_rename_entry *e1 = entry;
70         const struct dir_rename_entry *e2 = entry_or_key;
71
72         return strcmp(e1->dir, e2->dir);
73 }
74
75 static void dir_rename_init(struct hashmap *map)
76 {
77         hashmap_init(map, dir_rename_cmp, NULL, 0);
78 }
79
80 static void dir_rename_entry_init(struct dir_rename_entry *entry,
81                                   char *directory)
82 {
83         hashmap_entry_init(entry, strhash(directory));
84         entry->dir = directory;
85         entry->non_unique_new_dir = 0;
86         strbuf_init(&entry->new_dir, 0);
87         string_list_init(&entry->possible_new_dirs, 0);
88 }
89
90 static struct collision_entry *collision_find_entry(struct hashmap *hashmap,
91                                                     char *target_file)
92 {
93         struct collision_entry key;
94
95         hashmap_entry_init(&key, strhash(target_file));
96         key.target_file = target_file;
97         return hashmap_get(hashmap, &key, NULL);
98 }
99
100 static int collision_cmp(void *unused_cmp_data,
101                          const struct collision_entry *e1,
102                          const struct collision_entry *e2,
103                          const void *unused_keydata)
104 {
105         return strcmp(e1->target_file, e2->target_file);
106 }
107
108 static void collision_init(struct hashmap *map)
109 {
110         hashmap_init(map, (hashmap_cmp_fn) collision_cmp, NULL, 0);
111 }
112
113 static void flush_output(struct merge_options *o)
114 {
115         if (o->buffer_output < 2 && o->obuf.len) {
116                 fputs(o->obuf.buf, stdout);
117                 strbuf_reset(&o->obuf);
118         }
119 }
120
121 static int err(struct merge_options *o, const char *err, ...)
122 {
123         va_list params;
124
125         if (o->buffer_output < 2)
126                 flush_output(o);
127         else {
128                 strbuf_complete(&o->obuf, '\n');
129                 strbuf_addstr(&o->obuf, "error: ");
130         }
131         va_start(params, err);
132         strbuf_vaddf(&o->obuf, err, params);
133         va_end(params);
134         if (o->buffer_output > 1)
135                 strbuf_addch(&o->obuf, '\n');
136         else {
137                 error("%s", o->obuf.buf);
138                 strbuf_reset(&o->obuf);
139         }
140
141         return -1;
142 }
143
144 static struct tree *shift_tree_object(struct tree *one, struct tree *two,
145                                       const char *subtree_shift)
146 {
147         struct object_id shifted;
148
149         if (!*subtree_shift) {
150                 shift_tree(&one->object.oid, &two->object.oid, &shifted, 0);
151         } else {
152                 shift_tree_by(&one->object.oid, &two->object.oid, &shifted,
153                               subtree_shift);
154         }
155         if (!oidcmp(&two->object.oid, &shifted))
156                 return two;
157         return lookup_tree(&shifted);
158 }
159
160 static struct commit *make_virtual_commit(struct tree *tree, const char *comment)
161 {
162         struct commit *commit = alloc_commit_node();
163
164         set_merge_remote_desc(commit, comment, (struct object *)commit);
165         commit->maybe_tree = tree;
166         commit->object.parsed = 1;
167         return commit;
168 }
169
170 /*
171  * Since we use get_tree_entry(), which does not put the read object into
172  * the object pool, we cannot rely on a == b.
173  */
174 static int oid_eq(const struct object_id *a, const struct object_id *b)
175 {
176         if (!a && !b)
177                 return 2;
178         return a && b && oidcmp(a, b) == 0;
179 }
180
181 enum rename_type {
182         RENAME_NORMAL = 0,
183         RENAME_DIR,
184         RENAME_DELETE,
185         RENAME_ONE_FILE_TO_ONE,
186         RENAME_ONE_FILE_TO_TWO,
187         RENAME_TWO_FILES_TO_ONE
188 };
189
190 struct rename_conflict_info {
191         enum rename_type rename_type;
192         struct diff_filepair *pair1;
193         struct diff_filepair *pair2;
194         const char *branch1;
195         const char *branch2;
196         struct stage_data *dst_entry1;
197         struct stage_data *dst_entry2;
198         struct diff_filespec ren1_other;
199         struct diff_filespec ren2_other;
200 };
201
202 /*
203  * Since we want to write the index eventually, we cannot reuse the index
204  * for these (temporary) data.
205  */
206 struct stage_data {
207         struct {
208                 unsigned mode;
209                 struct object_id oid;
210         } stages[4];
211         struct rename_conflict_info *rename_conflict_info;
212         unsigned processed:1;
213 };
214
215 static inline void setup_rename_conflict_info(enum rename_type rename_type,
216                                               struct diff_filepair *pair1,
217                                               struct diff_filepair *pair2,
218                                               const char *branch1,
219                                               const char *branch2,
220                                               struct stage_data *dst_entry1,
221                                               struct stage_data *dst_entry2,
222                                               struct merge_options *o,
223                                               struct stage_data *src_entry1,
224                                               struct stage_data *src_entry2)
225 {
226         struct rename_conflict_info *ci = xcalloc(1, sizeof(struct rename_conflict_info));
227         ci->rename_type = rename_type;
228         ci->pair1 = pair1;
229         ci->branch1 = branch1;
230         ci->branch2 = branch2;
231
232         ci->dst_entry1 = dst_entry1;
233         dst_entry1->rename_conflict_info = ci;
234         dst_entry1->processed = 0;
235
236         assert(!pair2 == !dst_entry2);
237         if (dst_entry2) {
238                 ci->dst_entry2 = dst_entry2;
239                 ci->pair2 = pair2;
240                 dst_entry2->rename_conflict_info = ci;
241         }
242
243         if (rename_type == RENAME_TWO_FILES_TO_ONE) {
244                 /*
245                  * For each rename, there could have been
246                  * modifications on the side of history where that
247                  * file was not renamed.
248                  */
249                 int ostage1 = o->branch1 == branch1 ? 3 : 2;
250                 int ostage2 = ostage1 ^ 1;
251
252                 ci->ren1_other.path = pair1->one->path;
253                 oidcpy(&ci->ren1_other.oid, &src_entry1->stages[ostage1].oid);
254                 ci->ren1_other.mode = src_entry1->stages[ostage1].mode;
255
256                 ci->ren2_other.path = pair2->one->path;
257                 oidcpy(&ci->ren2_other.oid, &src_entry2->stages[ostage2].oid);
258                 ci->ren2_other.mode = src_entry2->stages[ostage2].mode;
259         }
260 }
261
262 static int show(struct merge_options *o, int v)
263 {
264         return (!o->call_depth && o->verbosity >= v) || o->verbosity >= 5;
265 }
266
267 __attribute__((format (printf, 3, 4)))
268 static void output(struct merge_options *o, int v, const char *fmt, ...)
269 {
270         va_list ap;
271
272         if (!show(o, v))
273                 return;
274
275         strbuf_addchars(&o->obuf, ' ', o->call_depth * 2);
276
277         va_start(ap, fmt);
278         strbuf_vaddf(&o->obuf, fmt, ap);
279         va_end(ap);
280
281         strbuf_addch(&o->obuf, '\n');
282         if (!o->buffer_output)
283                 flush_output(o);
284 }
285
286 static void output_commit_title(struct merge_options *o, struct commit *commit)
287 {
288         strbuf_addchars(&o->obuf, ' ', o->call_depth * 2);
289         if (commit->util)
290                 strbuf_addf(&o->obuf, "virtual %s\n",
291                         merge_remote_util(commit)->name);
292         else {
293                 strbuf_add_unique_abbrev(&o->obuf, &commit->object.oid,
294                                          DEFAULT_ABBREV);
295                 strbuf_addch(&o->obuf, ' ');
296                 if (parse_commit(commit) != 0)
297                         strbuf_addstr(&o->obuf, _("(bad commit)\n"));
298                 else {
299                         const char *title;
300                         const char *msg = get_commit_buffer(commit, NULL);
301                         int len = find_commit_subject(msg, &title);
302                         if (len)
303                                 strbuf_addf(&o->obuf, "%.*s\n", len, title);
304                         unuse_commit_buffer(commit, msg);
305                 }
306         }
307         flush_output(o);
308 }
309
310 static int add_cacheinfo(struct merge_options *o,
311                 unsigned int mode, const struct object_id *oid,
312                 const char *path, int stage, int refresh, int options)
313 {
314         struct cache_entry *ce;
315         int ret;
316
317         ce = make_cache_entry(mode, oid ? oid->hash : null_sha1, path, stage, 0);
318         if (!ce)
319                 return err(o, _("add_cacheinfo failed for path '%s'; merge aborting."), path);
320
321         ret = add_cache_entry(ce, options);
322         if (refresh) {
323                 struct cache_entry *nce;
324
325                 nce = refresh_cache_entry(ce, CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING);
326                 if (!nce)
327                         return err(o, _("add_cacheinfo failed to refresh for path '%s'; merge aborting."), path);
328                 if (nce != ce)
329                         ret = add_cache_entry(nce, options);
330         }
331         return ret;
332 }
333
334 static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
335 {
336         parse_tree(tree);
337         init_tree_desc(desc, tree->buffer, tree->size);
338 }
339
340 static int git_merge_trees(struct merge_options *o,
341                            struct tree *common,
342                            struct tree *head,
343                            struct tree *merge)
344 {
345         int rc;
346         struct tree_desc t[3];
347         struct index_state tmp_index = { NULL };
348
349         memset(&o->unpack_opts, 0, sizeof(o->unpack_opts));
350         if (o->call_depth)
351                 o->unpack_opts.index_only = 1;
352         else
353                 o->unpack_opts.update = 1;
354         o->unpack_opts.merge = 1;
355         o->unpack_opts.head_idx = 2;
356         o->unpack_opts.fn = threeway_merge;
357         o->unpack_opts.src_index = &the_index;
358         o->unpack_opts.dst_index = &tmp_index;
359         o->unpack_opts.aggressive = !merge_detect_rename(o);
360         setup_unpack_trees_porcelain(&o->unpack_opts, "merge");
361
362         init_tree_desc_from_tree(t+0, common);
363         init_tree_desc_from_tree(t+1, head);
364         init_tree_desc_from_tree(t+2, merge);
365
366         rc = unpack_trees(3, t, &o->unpack_opts);
367         cache_tree_free(&active_cache_tree);
368
369         /*
370          * Update the_index to match the new results, AFTER saving a copy
371          * in o->orig_index.  Update src_index to point to the saved copy.
372          * (verify_uptodate() checks src_index, and the original index is
373          * the one that had the necessary modification timestamps.)
374          */
375         o->orig_index = the_index;
376         the_index = tmp_index;
377         o->unpack_opts.src_index = &o->orig_index;
378
379         return rc;
380 }
381
382 struct tree *write_tree_from_memory(struct merge_options *o)
383 {
384         struct tree *result = NULL;
385
386         if (unmerged_cache()) {
387                 int i;
388                 fprintf(stderr, "BUG: There are unmerged index entries:\n");
389                 for (i = 0; i < active_nr; i++) {
390                         const struct cache_entry *ce = active_cache[i];
391                         if (ce_stage(ce))
392                                 fprintf(stderr, "BUG: %d %.*s\n", ce_stage(ce),
393                                         (int)ce_namelen(ce), ce->name);
394                 }
395                 die("BUG: unmerged index entries in merge-recursive.c");
396         }
397
398         if (!active_cache_tree)
399                 active_cache_tree = cache_tree();
400
401         if (!cache_tree_fully_valid(active_cache_tree) &&
402             cache_tree_update(&the_index, 0) < 0) {
403                 err(o, _("error building trees"));
404                 return NULL;
405         }
406
407         result = lookup_tree(&active_cache_tree->oid);
408
409         return result;
410 }
411
412 static int save_files_dirs(const struct object_id *oid,
413                 struct strbuf *base, const char *path,
414                 unsigned int mode, int stage, void *context)
415 {
416         struct path_hashmap_entry *entry;
417         int baselen = base->len;
418         struct merge_options *o = context;
419
420         strbuf_addstr(base, path);
421
422         FLEX_ALLOC_MEM(entry, path, base->buf, base->len);
423         hashmap_entry_init(entry, path_hash(entry->path));
424         hashmap_add(&o->current_file_dir_set, entry);
425
426         strbuf_setlen(base, baselen);
427         return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
428 }
429
430 static void get_files_dirs(struct merge_options *o, struct tree *tree)
431 {
432         struct pathspec match_all;
433         memset(&match_all, 0, sizeof(match_all));
434         read_tree_recursive(tree, "", 0, 0, &match_all, save_files_dirs, o);
435 }
436
437 static int get_tree_entry_if_blob(const struct object_id *tree,
438                                   const char *path,
439                                   struct object_id *hashy,
440                                   unsigned int *mode_o)
441 {
442         int ret;
443
444         ret = get_tree_entry(tree, path, hashy, mode_o);
445         if (S_ISDIR(*mode_o)) {
446                 oidcpy(hashy, &null_oid);
447                 *mode_o = 0;
448         }
449         return ret;
450 }
451
452 /*
453  * Returns an index_entry instance which doesn't have to correspond to
454  * a real cache entry in Git's index.
455  */
456 static struct stage_data *insert_stage_data(const char *path,
457                 struct tree *o, struct tree *a, struct tree *b,
458                 struct string_list *entries)
459 {
460         struct string_list_item *item;
461         struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
462         get_tree_entry_if_blob(&o->object.oid, path,
463                                &e->stages[1].oid, &e->stages[1].mode);
464         get_tree_entry_if_blob(&a->object.oid, path,
465                                &e->stages[2].oid, &e->stages[2].mode);
466         get_tree_entry_if_blob(&b->object.oid, path,
467                                &e->stages[3].oid, &e->stages[3].mode);
468         item = string_list_insert(entries, path);
469         item->util = e;
470         return e;
471 }
472
473 /*
474  * Create a dictionary mapping file names to stage_data objects. The
475  * dictionary contains one entry for every path with a non-zero stage entry.
476  */
477 static struct string_list *get_unmerged(void)
478 {
479         struct string_list *unmerged = xcalloc(1, sizeof(struct string_list));
480         int i;
481
482         unmerged->strdup_strings = 1;
483
484         for (i = 0; i < active_nr; i++) {
485                 struct string_list_item *item;
486                 struct stage_data *e;
487                 const struct cache_entry *ce = active_cache[i];
488                 if (!ce_stage(ce))
489                         continue;
490
491                 item = string_list_lookup(unmerged, ce->name);
492                 if (!item) {
493                         item = string_list_insert(unmerged, ce->name);
494                         item->util = xcalloc(1, sizeof(struct stage_data));
495                 }
496                 e = item->util;
497                 e->stages[ce_stage(ce)].mode = ce->ce_mode;
498                 oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid);
499         }
500
501         return unmerged;
502 }
503
504 static int string_list_df_name_compare(const char *one, const char *two)
505 {
506         int onelen = strlen(one);
507         int twolen = strlen(two);
508         /*
509          * Here we only care that entries for D/F conflicts are
510          * adjacent, in particular with the file of the D/F conflict
511          * appearing before files below the corresponding directory.
512          * The order of the rest of the list is irrelevant for us.
513          *
514          * To achieve this, we sort with df_name_compare and provide
515          * the mode S_IFDIR so that D/F conflicts will sort correctly.
516          * We use the mode S_IFDIR for everything else for simplicity,
517          * since in other cases any changes in their order due to
518          * sorting cause no problems for us.
519          */
520         int cmp = df_name_compare(one, onelen, S_IFDIR,
521                                   two, twolen, S_IFDIR);
522         /*
523          * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
524          * that 'foo' comes before 'foo/bar'.
525          */
526         if (cmp)
527                 return cmp;
528         return onelen - twolen;
529 }
530
531 static void record_df_conflict_files(struct merge_options *o,
532                                      struct string_list *entries)
533 {
534         /* If there is a D/F conflict and the file for such a conflict
535          * currently exist in the working tree, we want to allow it to be
536          * removed to make room for the corresponding directory if needed.
537          * The files underneath the directories of such D/F conflicts will
538          * be processed before the corresponding file involved in the D/F
539          * conflict.  If the D/F directory ends up being removed by the
540          * merge, then we won't have to touch the D/F file.  If the D/F
541          * directory needs to be written to the working copy, then the D/F
542          * file will simply be removed (in make_room_for_path()) to make
543          * room for the necessary paths.  Note that if both the directory
544          * and the file need to be present, then the D/F file will be
545          * reinstated with a new unique name at the time it is processed.
546          */
547         struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP;
548         const char *last_file = NULL;
549         int last_len = 0;
550         int i;
551
552         /*
553          * If we're merging merge-bases, we don't want to bother with
554          * any working directory changes.
555          */
556         if (o->call_depth)
557                 return;
558
559         /* Ensure D/F conflicts are adjacent in the entries list. */
560         for (i = 0; i < entries->nr; i++) {
561                 struct string_list_item *next = &entries->items[i];
562                 string_list_append(&df_sorted_entries, next->string)->util =
563                                    next->util;
564         }
565         df_sorted_entries.cmp = string_list_df_name_compare;
566         string_list_sort(&df_sorted_entries);
567
568         string_list_clear(&o->df_conflict_file_set, 1);
569         for (i = 0; i < df_sorted_entries.nr; i++) {
570                 const char *path = df_sorted_entries.items[i].string;
571                 int len = strlen(path);
572                 struct stage_data *e = df_sorted_entries.items[i].util;
573
574                 /*
575                  * Check if last_file & path correspond to a D/F conflict;
576                  * i.e. whether path is last_file+'/'+<something>.
577                  * If so, record that it's okay to remove last_file to make
578                  * room for path and friends if needed.
579                  */
580                 if (last_file &&
581                     len > last_len &&
582                     memcmp(path, last_file, last_len) == 0 &&
583                     path[last_len] == '/') {
584                         string_list_insert(&o->df_conflict_file_set, last_file);
585                 }
586
587                 /*
588                  * Determine whether path could exist as a file in the
589                  * working directory as a possible D/F conflict.  This
590                  * will only occur when it exists in stage 2 as a
591                  * file.
592                  */
593                 if (S_ISREG(e->stages[2].mode) || S_ISLNK(e->stages[2].mode)) {
594                         last_file = path;
595                         last_len = len;
596                 } else {
597                         last_file = NULL;
598                 }
599         }
600         string_list_clear(&df_sorted_entries, 0);
601 }
602
603 struct rename {
604         struct diff_filepair *pair;
605         /*
606          * Purpose of src_entry and dst_entry:
607          *
608          * If 'before' is renamed to 'after' then src_entry will contain
609          * the versions of 'before' from the merge_base, HEAD, and MERGE in
610          * stages 1, 2, and 3; dst_entry will contain the respective
611          * versions of 'after' in corresponding locations.  Thus, we have a
612          * total of six modes and oids, though some will be null.  (Stage 0
613          * is ignored; we're interested in handling conflicts.)
614          *
615          * Since we don't turn on break-rewrites by default, neither
616          * src_entry nor dst_entry can have all three of their stages have
617          * non-null oids, meaning at most four of the six will be non-null.
618          * Also, since this is a rename, both src_entry and dst_entry will
619          * have at least one non-null oid, meaning at least two will be
620          * non-null.  Of the six oids, a typical rename will have three be
621          * non-null.  Only two implies a rename/delete, and four implies a
622          * rename/add.
623          */
624         struct stage_data *src_entry;
625         struct stage_data *dst_entry;
626         unsigned add_turned_into_rename:1;
627         unsigned processed:1;
628 };
629
630 static int update_stages(struct merge_options *opt, const char *path,
631                          const struct diff_filespec *o,
632                          const struct diff_filespec *a,
633                          const struct diff_filespec *b)
634 {
635
636         /*
637          * NOTE: It is usually a bad idea to call update_stages on a path
638          * before calling update_file on that same path, since it can
639          * sometimes lead to spurious "refusing to lose untracked file..."
640          * messages from update_file (via make_room_for path via
641          * would_lose_untracked).  Instead, reverse the order of the calls
642          * (executing update_file first and then update_stages).
643          */
644         int clear = 1;
645         int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK;
646         if (clear)
647                 if (remove_file_from_cache(path))
648                         return -1;
649         if (o)
650                 if (add_cacheinfo(opt, o->mode, &o->oid, path, 1, 0, options))
651                         return -1;
652         if (a)
653                 if (add_cacheinfo(opt, a->mode, &a->oid, path, 2, 0, options))
654                         return -1;
655         if (b)
656                 if (add_cacheinfo(opt, b->mode, &b->oid, path, 3, 0, options))
657                         return -1;
658         return 0;
659 }
660
661 static int update_stages_for_stage_data(struct merge_options *opt,
662                                         const char *path,
663                                         const struct stage_data *stage_data)
664 {
665         struct diff_filespec o, a, b;
666
667         o.mode = stage_data->stages[1].mode;
668         oidcpy(&o.oid, &stage_data->stages[1].oid);
669
670         a.mode = stage_data->stages[2].mode;
671         oidcpy(&a.oid, &stage_data->stages[2].oid);
672
673         b.mode = stage_data->stages[3].mode;
674         oidcpy(&b.oid, &stage_data->stages[3].oid);
675
676         return update_stages(opt, path,
677                              is_null_oid(&o.oid) ? NULL : &o,
678                              is_null_oid(&a.oid) ? NULL : &a,
679                              is_null_oid(&b.oid) ? NULL : &b);
680 }
681
682 static void update_entry(struct stage_data *entry,
683                          struct diff_filespec *o,
684                          struct diff_filespec *a,
685                          struct diff_filespec *b)
686 {
687         entry->processed = 0;
688         entry->stages[1].mode = o->mode;
689         entry->stages[2].mode = a->mode;
690         entry->stages[3].mode = b->mode;
691         oidcpy(&entry->stages[1].oid, &o->oid);
692         oidcpy(&entry->stages[2].oid, &a->oid);
693         oidcpy(&entry->stages[3].oid, &b->oid);
694 }
695
696 static int remove_file(struct merge_options *o, int clean,
697                        const char *path, int no_wd)
698 {
699         int update_cache = o->call_depth || clean;
700         int update_working_directory = !o->call_depth && !no_wd;
701
702         if (update_cache) {
703                 if (remove_file_from_cache(path))
704                         return -1;
705         }
706         if (update_working_directory) {
707                 if (ignore_case) {
708                         struct cache_entry *ce;
709                         ce = cache_file_exists(path, strlen(path), ignore_case);
710                         if (ce && ce_stage(ce) == 0 && strcmp(path, ce->name))
711                                 return 0;
712                 }
713                 if (remove_path(path))
714                         return -1;
715         }
716         return 0;
717 }
718
719 /* add a string to a strbuf, but converting "/" to "_" */
720 static void add_flattened_path(struct strbuf *out, const char *s)
721 {
722         size_t i = out->len;
723         strbuf_addstr(out, s);
724         for (; i < out->len; i++)
725                 if (out->buf[i] == '/')
726                         out->buf[i] = '_';
727 }
728
729 static char *unique_path(struct merge_options *o, const char *path, const char *branch)
730 {
731         struct path_hashmap_entry *entry;
732         struct strbuf newpath = STRBUF_INIT;
733         int suffix = 0;
734         size_t base_len;
735
736         strbuf_addf(&newpath, "%s~", path);
737         add_flattened_path(&newpath, branch);
738
739         base_len = newpath.len;
740         while (hashmap_get_from_hash(&o->current_file_dir_set,
741                                      path_hash(newpath.buf), newpath.buf) ||
742                (!o->call_depth && file_exists(newpath.buf))) {
743                 strbuf_setlen(&newpath, base_len);
744                 strbuf_addf(&newpath, "_%d", suffix++);
745         }
746
747         FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len);
748         hashmap_entry_init(entry, path_hash(entry->path));
749         hashmap_add(&o->current_file_dir_set, entry);
750         return strbuf_detach(&newpath, NULL);
751 }
752
753 /**
754  * Check whether a directory in the index is in the way of an incoming
755  * file.  Return 1 if so.  If check_working_copy is non-zero, also
756  * check the working directory.  If empty_ok is non-zero, also return
757  * 0 in the case where the working-tree dir exists but is empty.
758  */
759 static int dir_in_way(const char *path, int check_working_copy, int empty_ok)
760 {
761         int pos;
762         struct strbuf dirpath = STRBUF_INIT;
763         struct stat st;
764
765         strbuf_addstr(&dirpath, path);
766         strbuf_addch(&dirpath, '/');
767
768         pos = cache_name_pos(dirpath.buf, dirpath.len);
769
770         if (pos < 0)
771                 pos = -1 - pos;
772         if (pos < active_nr &&
773             !strncmp(dirpath.buf, active_cache[pos]->name, dirpath.len)) {
774                 strbuf_release(&dirpath);
775                 return 1;
776         }
777
778         strbuf_release(&dirpath);
779         return check_working_copy && !lstat(path, &st) && S_ISDIR(st.st_mode) &&
780                 !(empty_ok && is_empty_dir(path));
781 }
782
783 /*
784  * Returns whether path was tracked in the index before the merge started,
785  * and its oid and mode match the specified values
786  */
787 static int was_tracked_and_matches(struct merge_options *o, const char *path,
788                                    const struct object_id *oid, unsigned mode)
789 {
790         int pos = index_name_pos(&o->orig_index, path, strlen(path));
791         struct cache_entry *ce;
792
793         if (0 > pos)
794                 /* we were not tracking this path before the merge */
795                 return 0;
796
797         /* See if the file we were tracking before matches */
798         ce = o->orig_index.cache[pos];
799         return (oid_eq(&ce->oid, oid) && ce->ce_mode == mode);
800 }
801
802 /*
803  * Returns whether path was tracked in the index before the merge started
804  */
805 static int was_tracked(struct merge_options *o, const char *path)
806 {
807         int pos = index_name_pos(&o->orig_index, path, strlen(path));
808
809         if (0 <= pos)
810                 /* we were tracking this path before the merge */
811                 return 1;
812
813         return 0;
814 }
815
816 static int would_lose_untracked(const char *path)
817 {
818         /*
819          * This may look like it can be simplified to:
820          *   return !was_tracked(o, path) && file_exists(path)
821          * but it can't.  This function needs to know whether path was in
822          * the working tree due to EITHER having been tracked in the index
823          * before the merge OR having been put into the working copy and
824          * index by unpack_trees().  Due to that either-or requirement, we
825          * check the current index instead of the original one.
826          *
827          * Note that we do not need to worry about merge-recursive itself
828          * updating the index after unpack_trees() and before calling this
829          * function, because we strictly require all code paths in
830          * merge-recursive to update the working tree first and the index
831          * second.  Doing otherwise would break
832          * update_file()/would_lose_untracked(); see every comment in this
833          * file which mentions "update_stages".
834          */
835         int pos = cache_name_pos(path, strlen(path));
836
837         if (pos < 0)
838                 pos = -1 - pos;
839         while (pos < active_nr &&
840                !strcmp(path, active_cache[pos]->name)) {
841                 /*
842                  * If stage #0, it is definitely tracked.
843                  * If it has stage #2 then it was tracked
844                  * before this merge started.  All other
845                  * cases the path was not tracked.
846                  */
847                 switch (ce_stage(active_cache[pos])) {
848                 case 0:
849                 case 2:
850                         return 0;
851                 }
852                 pos++;
853         }
854         return file_exists(path);
855 }
856
857 static int was_dirty(struct merge_options *o, const char *path)
858 {
859         struct cache_entry *ce;
860         int dirty = 1;
861
862         if (o->call_depth || !was_tracked(o, path))
863                 return !dirty;
864
865         ce = index_file_exists(o->unpack_opts.src_index,
866                                path, strlen(path), ignore_case);
867         dirty = verify_uptodate(ce, &o->unpack_opts) != 0;
868         return dirty;
869 }
870
871 static int make_room_for_path(struct merge_options *o, const char *path)
872 {
873         int status, i;
874         const char *msg = _("failed to create path '%s'%s");
875
876         /* Unlink any D/F conflict files that are in the way */
877         for (i = 0; i < o->df_conflict_file_set.nr; i++) {
878                 const char *df_path = o->df_conflict_file_set.items[i].string;
879                 size_t pathlen = strlen(path);
880                 size_t df_pathlen = strlen(df_path);
881                 if (df_pathlen < pathlen &&
882                     path[df_pathlen] == '/' &&
883                     strncmp(path, df_path, df_pathlen) == 0) {
884                         output(o, 3,
885                                _("Removing %s to make room for subdirectory\n"),
886                                df_path);
887                         unlink(df_path);
888                         unsorted_string_list_delete_item(&o->df_conflict_file_set,
889                                                          i, 0);
890                         break;
891                 }
892         }
893
894         /* Make sure leading directories are created */
895         status = safe_create_leading_directories_const(path);
896         if (status) {
897                 if (status == SCLD_EXISTS)
898                         /* something else exists */
899                         return err(o, msg, path, _(": perhaps a D/F conflict?"));
900                 return err(o, msg, path, "");
901         }
902
903         /*
904          * Do not unlink a file in the work tree if we are not
905          * tracking it.
906          */
907         if (would_lose_untracked(path))
908                 return err(o, _("refusing to lose untracked file at '%s'"),
909                              path);
910
911         /* Successful unlink is good.. */
912         if (!unlink(path))
913                 return 0;
914         /* .. and so is no existing file */
915         if (errno == ENOENT)
916                 return 0;
917         /* .. but not some other error (who really cares what?) */
918         return err(o, msg, path, _(": perhaps a D/F conflict?"));
919 }
920
921 static int update_file_flags(struct merge_options *o,
922                              const struct object_id *oid,
923                              unsigned mode,
924                              const char *path,
925                              int update_cache,
926                              int update_wd)
927 {
928         int ret = 0;
929
930         if (o->call_depth)
931                 update_wd = 0;
932
933         if (update_wd) {
934                 enum object_type type;
935                 void *buf;
936                 unsigned long size;
937
938                 if (S_ISGITLINK(mode)) {
939                         /*
940                          * We may later decide to recursively descend into
941                          * the submodule directory and update its index
942                          * and/or work tree, but we do not do that now.
943                          */
944                         update_wd = 0;
945                         goto update_index;
946                 }
947
948                 buf = read_object_file(oid, &type, &size);
949                 if (!buf)
950                         return err(o, _("cannot read object %s '%s'"), oid_to_hex(oid), path);
951                 if (type != OBJ_BLOB) {
952                         ret = err(o, _("blob expected for %s '%s'"), oid_to_hex(oid), path);
953                         goto free_buf;
954                 }
955                 if (S_ISREG(mode)) {
956                         struct strbuf strbuf = STRBUF_INIT;
957                         if (convert_to_working_tree(path, buf, size, &strbuf)) {
958                                 free(buf);
959                                 size = strbuf.len;
960                                 buf = strbuf_detach(&strbuf, NULL);
961                         }
962                 }
963
964                 if (make_room_for_path(o, path) < 0) {
965                         update_wd = 0;
966                         goto free_buf;
967                 }
968                 if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) {
969                         int fd;
970                         if (mode & 0100)
971                                 mode = 0777;
972                         else
973                                 mode = 0666;
974                         fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
975                         if (fd < 0) {
976                                 ret = err(o, _("failed to open '%s': %s"),
977                                           path, strerror(errno));
978                                 goto free_buf;
979                         }
980                         write_in_full(fd, buf, size);
981                         close(fd);
982                 } else if (S_ISLNK(mode)) {
983                         char *lnk = xmemdupz(buf, size);
984                         safe_create_leading_directories_const(path);
985                         unlink(path);
986                         if (symlink(lnk, path))
987                                 ret = err(o, _("failed to symlink '%s': %s"),
988                                         path, strerror(errno));
989                         free(lnk);
990                 } else
991                         ret = err(o,
992                                   _("do not know what to do with %06o %s '%s'"),
993                                   mode, oid_to_hex(oid), path);
994  free_buf:
995                 free(buf);
996         }
997  update_index:
998         if (!ret && update_cache)
999                 if (add_cacheinfo(o, mode, oid, path, 0, update_wd,
1000                                   ADD_CACHE_OK_TO_ADD))
1001                         return -1;
1002         return ret;
1003 }
1004
1005 static int update_file(struct merge_options *o,
1006                        int clean,
1007                        const struct object_id *oid,
1008                        unsigned mode,
1009                        const char *path)
1010 {
1011         return update_file_flags(o, oid, mode, path, o->call_depth || clean, !o->call_depth);
1012 }
1013
1014 /* Low level file merging, update and removal */
1015
1016 struct merge_file_info {
1017         struct object_id oid;
1018         unsigned mode;
1019         unsigned clean:1,
1020                  merge:1;
1021 };
1022
1023 static int merge_3way(struct merge_options *o,
1024                       mmbuffer_t *result_buf,
1025                       const struct diff_filespec *one,
1026                       const struct diff_filespec *a,
1027                       const struct diff_filespec *b,
1028                       const char *branch1,
1029                       const char *branch2)
1030 {
1031         mmfile_t orig, src1, src2;
1032         struct ll_merge_options ll_opts = {0};
1033         char *base_name, *name1, *name2;
1034         int merge_status;
1035
1036         ll_opts.renormalize = o->renormalize;
1037         ll_opts.xdl_opts = o->xdl_opts;
1038
1039         if (o->call_depth) {
1040                 ll_opts.virtual_ancestor = 1;
1041                 ll_opts.variant = 0;
1042         } else {
1043                 switch (o->recursive_variant) {
1044                 case MERGE_RECURSIVE_OURS:
1045                         ll_opts.variant = XDL_MERGE_FAVOR_OURS;
1046                         break;
1047                 case MERGE_RECURSIVE_THEIRS:
1048                         ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
1049                         break;
1050                 default:
1051                         ll_opts.variant = 0;
1052                         break;
1053                 }
1054         }
1055
1056         if (strcmp(a->path, b->path) ||
1057             (o->ancestor != NULL && strcmp(a->path, one->path) != 0)) {
1058                 base_name = o->ancestor == NULL ? NULL :
1059                         mkpathdup("%s:%s", o->ancestor, one->path);
1060                 name1 = mkpathdup("%s:%s", branch1, a->path);
1061                 name2 = mkpathdup("%s:%s", branch2, b->path);
1062         } else {
1063                 base_name = o->ancestor == NULL ? NULL :
1064                         mkpathdup("%s", o->ancestor);
1065                 name1 = mkpathdup("%s", branch1);
1066                 name2 = mkpathdup("%s", branch2);
1067         }
1068
1069         read_mmblob(&orig, &one->oid);
1070         read_mmblob(&src1, &a->oid);
1071         read_mmblob(&src2, &b->oid);
1072
1073         merge_status = ll_merge(result_buf, a->path, &orig, base_name,
1074                                 &src1, name1, &src2, name2, &ll_opts);
1075
1076         free(base_name);
1077         free(name1);
1078         free(name2);
1079         free(orig.ptr);
1080         free(src1.ptr);
1081         free(src2.ptr);
1082         return merge_status;
1083 }
1084
1085 static int merge_file_1(struct merge_options *o,
1086                         const struct diff_filespec *one,
1087                         const struct diff_filespec *a,
1088                         const struct diff_filespec *b,
1089                         const char *filename,
1090                         const char *branch1,
1091                         const char *branch2,
1092                         struct merge_file_info *result)
1093 {
1094         result->merge = 0;
1095         result->clean = 1;
1096
1097         if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
1098                 result->clean = 0;
1099                 if (S_ISREG(a->mode)) {
1100                         result->mode = a->mode;
1101                         oidcpy(&result->oid, &a->oid);
1102                 } else {
1103                         result->mode = b->mode;
1104                         oidcpy(&result->oid, &b->oid);
1105                 }
1106         } else {
1107                 if (!oid_eq(&a->oid, &one->oid) && !oid_eq(&b->oid, &one->oid))
1108                         result->merge = 1;
1109
1110                 /*
1111                  * Merge modes
1112                  */
1113                 if (a->mode == b->mode || a->mode == one->mode)
1114                         result->mode = b->mode;
1115                 else {
1116                         result->mode = a->mode;
1117                         if (b->mode != one->mode) {
1118                                 result->clean = 0;
1119                                 result->merge = 1;
1120                         }
1121                 }
1122
1123                 if (oid_eq(&a->oid, &b->oid) || oid_eq(&a->oid, &one->oid))
1124                         oidcpy(&result->oid, &b->oid);
1125                 else if (oid_eq(&b->oid, &one->oid))
1126                         oidcpy(&result->oid, &a->oid);
1127                 else if (S_ISREG(a->mode)) {
1128                         mmbuffer_t result_buf;
1129                         int ret = 0, merge_status;
1130
1131                         merge_status = merge_3way(o, &result_buf, one, a, b,
1132                                                   branch1, branch2);
1133
1134                         if ((merge_status < 0) || !result_buf.ptr)
1135                                 ret = err(o, _("Failed to execute internal merge"));
1136
1137                         if (!ret &&
1138                             write_object_file(result_buf.ptr, result_buf.size,
1139                                               blob_type, &result->oid))
1140                                 ret = err(o, _("Unable to add %s to database"),
1141                                           a->path);
1142
1143                         free(result_buf.ptr);
1144                         if (ret)
1145                                 return ret;
1146                         result->clean = (merge_status == 0);
1147                 } else if (S_ISGITLINK(a->mode)) {
1148                         result->clean = merge_submodule(&result->oid,
1149                                                        one->path,
1150                                                        &one->oid,
1151                                                        &a->oid,
1152                                                        &b->oid,
1153                                                        !o->call_depth);
1154                 } else if (S_ISLNK(a->mode)) {
1155                         switch (o->recursive_variant) {
1156                         case MERGE_RECURSIVE_NORMAL:
1157                                 oidcpy(&result->oid, &a->oid);
1158                                 if (!oid_eq(&a->oid, &b->oid))
1159                                         result->clean = 0;
1160                                 break;
1161                         case MERGE_RECURSIVE_OURS:
1162                                 oidcpy(&result->oid, &a->oid);
1163                                 break;
1164                         case MERGE_RECURSIVE_THEIRS:
1165                                 oidcpy(&result->oid, &b->oid);
1166                                 break;
1167                         }
1168                 } else
1169                         die("BUG: unsupported object type in the tree");
1170         }
1171
1172         if (result->merge)
1173                 output(o, 2, _("Auto-merging %s"), filename);
1174
1175         return 0;
1176 }
1177
1178 static int merge_file_special_markers(struct merge_options *o,
1179                                       const struct diff_filespec *one,
1180                                       const struct diff_filespec *a,
1181                                       const struct diff_filespec *b,
1182                                       const char *target_filename,
1183                                       const char *branch1,
1184                                       const char *filename1,
1185                                       const char *branch2,
1186                                       const char *filename2,
1187                                       struct merge_file_info *mfi)
1188 {
1189         char *side1 = NULL;
1190         char *side2 = NULL;
1191         int ret;
1192
1193         if (filename1)
1194                 side1 = xstrfmt("%s:%s", branch1, filename1);
1195         if (filename2)
1196                 side2 = xstrfmt("%s:%s", branch2, filename2);
1197
1198         ret = merge_file_1(o, one, a, b, target_filename,
1199                            side1 ? side1 : branch1,
1200                            side2 ? side2 : branch2, mfi);
1201
1202         free(side1);
1203         free(side2);
1204         return ret;
1205 }
1206
1207 static int merge_file_one(struct merge_options *o,
1208                           const char *path,
1209                           const struct object_id *o_oid, int o_mode,
1210                           const struct object_id *a_oid, int a_mode,
1211                           const struct object_id *b_oid, int b_mode,
1212                           const char *branch1,
1213                           const char *branch2,
1214                           struct merge_file_info *mfi)
1215 {
1216         struct diff_filespec one, a, b;
1217
1218         one.path = a.path = b.path = (char *)path;
1219         oidcpy(&one.oid, o_oid);
1220         one.mode = o_mode;
1221         oidcpy(&a.oid, a_oid);
1222         a.mode = a_mode;
1223         oidcpy(&b.oid, b_oid);
1224         b.mode = b_mode;
1225         return merge_file_1(o, &one, &a, &b, path, branch1, branch2, mfi);
1226 }
1227
1228 static int conflict_rename_dir(struct merge_options *o,
1229                                struct diff_filepair *pair,
1230                                const char *rename_branch,
1231                                const char *other_branch)
1232 {
1233         const struct diff_filespec *dest = pair->two;
1234
1235         if (!o->call_depth && would_lose_untracked(dest->path)) {
1236                 char *alt_path = unique_path(o, dest->path, rename_branch);
1237
1238                 output(o, 1, _("Error: Refusing to lose untracked file at %s; "
1239                                "writing to %s instead."),
1240                        dest->path, alt_path);
1241                 /*
1242                  * Write the file in worktree at alt_path, but not in the
1243                  * index.  Instead, write to dest->path for the index but
1244                  * only at the higher appropriate stage.
1245                  */
1246                 if (update_file(o, 0, &dest->oid, dest->mode, alt_path))
1247                         return -1;
1248                 free(alt_path);
1249                 return update_stages(o, dest->path, NULL,
1250                                      rename_branch == o->branch1 ? dest : NULL,
1251                                      rename_branch == o->branch1 ? NULL : dest);
1252         }
1253
1254         /* Update dest->path both in index and in worktree */
1255         if (update_file(o, 1, &dest->oid, dest->mode, dest->path))
1256                 return -1;
1257         return 0;
1258 }
1259
1260 static int handle_change_delete(struct merge_options *o,
1261                                  const char *path, const char *old_path,
1262                                  const struct object_id *o_oid, int o_mode,
1263                                  const struct object_id *changed_oid,
1264                                  int changed_mode,
1265                                  const char *change_branch,
1266                                  const char *delete_branch,
1267                                  const char *change, const char *change_past)
1268 {
1269         char *alt_path = NULL;
1270         const char *update_path = path;
1271         int ret = 0;
1272
1273         if (dir_in_way(path, !o->call_depth, 0) ||
1274             (!o->call_depth && would_lose_untracked(path))) {
1275                 update_path = alt_path = unique_path(o, path, change_branch);
1276         }
1277
1278         if (o->call_depth) {
1279                 /*
1280                  * We cannot arbitrarily accept either a_sha or b_sha as
1281                  * correct; since there is no true "middle point" between
1282                  * them, simply reuse the base version for virtual merge base.
1283                  */
1284                 ret = remove_file_from_cache(path);
1285                 if (!ret)
1286                         ret = update_file(o, 0, o_oid, o_mode, update_path);
1287         } else {
1288                 if (!alt_path) {
1289                         if (!old_path) {
1290                                 output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1291                                        "and %s in %s. Version %s of %s left in tree."),
1292                                        change, path, delete_branch, change_past,
1293                                        change_branch, change_branch, path);
1294                         } else {
1295                                 output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1296                                        "and %s to %s in %s. Version %s of %s left in tree."),
1297                                        change, old_path, delete_branch, change_past, path,
1298                                        change_branch, change_branch, path);
1299                         }
1300                 } else {
1301                         if (!old_path) {
1302                                 output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1303                                        "and %s in %s. Version %s of %s left in tree at %s."),
1304                                        change, path, delete_branch, change_past,
1305                                        change_branch, change_branch, path, alt_path);
1306                         } else {
1307                                 output(o, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1308                                        "and %s to %s in %s. Version %s of %s left in tree at %s."),
1309                                        change, old_path, delete_branch, change_past, path,
1310                                        change_branch, change_branch, path, alt_path);
1311                         }
1312                 }
1313                 /*
1314                  * No need to call update_file() on path when change_branch ==
1315                  * o->branch1 && !alt_path, since that would needlessly touch
1316                  * path.  We could call update_file_flags() with update_cache=0
1317                  * and update_wd=0, but that's a no-op.
1318                  */
1319                 if (change_branch != o->branch1 || alt_path)
1320                         ret = update_file(o, 0, changed_oid, changed_mode, update_path);
1321         }
1322         free(alt_path);
1323
1324         return ret;
1325 }
1326
1327 static int conflict_rename_delete(struct merge_options *o,
1328                                    struct diff_filepair *pair,
1329                                    const char *rename_branch,
1330                                    const char *delete_branch)
1331 {
1332         const struct diff_filespec *orig = pair->one;
1333         const struct diff_filespec *dest = pair->two;
1334
1335         if (handle_change_delete(o,
1336                                  o->call_depth ? orig->path : dest->path,
1337                                  o->call_depth ? NULL : orig->path,
1338                                  &orig->oid, orig->mode,
1339                                  &dest->oid, dest->mode,
1340                                  rename_branch, delete_branch,
1341                                  _("rename"), _("renamed")))
1342                 return -1;
1343
1344         if (o->call_depth)
1345                 return remove_file_from_cache(dest->path);
1346         else
1347                 return update_stages(o, dest->path, NULL,
1348                                      rename_branch == o->branch1 ? dest : NULL,
1349                                      rename_branch == o->branch1 ? NULL : dest);
1350 }
1351
1352 static struct diff_filespec *filespec_from_entry(struct diff_filespec *target,
1353                                                  struct stage_data *entry,
1354                                                  int stage)
1355 {
1356         struct object_id *oid = &entry->stages[stage].oid;
1357         unsigned mode = entry->stages[stage].mode;
1358         if (mode == 0 || is_null_oid(oid))
1359                 return NULL;
1360         oidcpy(&target->oid, oid);
1361         target->mode = mode;
1362         return target;
1363 }
1364
1365 static int handle_file(struct merge_options *o,
1366                         struct diff_filespec *rename,
1367                         int stage,
1368                         struct rename_conflict_info *ci)
1369 {
1370         char *dst_name = rename->path;
1371         struct stage_data *dst_entry;
1372         const char *cur_branch, *other_branch;
1373         struct diff_filespec other;
1374         struct diff_filespec *add;
1375         int ret;
1376
1377         if (stage == 2) {
1378                 dst_entry = ci->dst_entry1;
1379                 cur_branch = ci->branch1;
1380                 other_branch = ci->branch2;
1381         } else {
1382                 dst_entry = ci->dst_entry2;
1383                 cur_branch = ci->branch2;
1384                 other_branch = ci->branch1;
1385         }
1386
1387         add = filespec_from_entry(&other, dst_entry, stage ^ 1);
1388         if (add) {
1389                 int ren_src_was_dirty = was_dirty(o, rename->path);
1390                 char *add_name = unique_path(o, rename->path, other_branch);
1391                 if (update_file(o, 0, &add->oid, add->mode, add_name))
1392                         return -1;
1393
1394                 if (ren_src_was_dirty) {
1395                         output(o, 1, _("Refusing to lose dirty file at %s"),
1396                                rename->path);
1397                 }
1398                 /*
1399                  * Because the double negatives somehow keep confusing me...
1400                  *    1) update_wd iff !ren_src_was_dirty.
1401                  *    2) no_wd iff !update_wd
1402                  *    3) so, no_wd == !!ren_src_was_dirty == ren_src_was_dirty
1403                  */
1404                 remove_file(o, 0, rename->path, ren_src_was_dirty);
1405                 dst_name = unique_path(o, rename->path, cur_branch);
1406         } else {
1407                 if (dir_in_way(rename->path, !o->call_depth, 0)) {
1408                         dst_name = unique_path(o, rename->path, cur_branch);
1409                         output(o, 1, _("%s is a directory in %s adding as %s instead"),
1410                                rename->path, other_branch, dst_name);
1411                 } else if (!o->call_depth &&
1412                            would_lose_untracked(rename->path)) {
1413                         dst_name = unique_path(o, rename->path, cur_branch);
1414                         output(o, 1, _("Refusing to lose untracked file at %s; "
1415                                        "adding as %s instead"),
1416                                rename->path, dst_name);
1417                 }
1418         }
1419         if ((ret = update_file(o, 0, &rename->oid, rename->mode, dst_name)))
1420                 ; /* fall through, do allow dst_name to be released */
1421         else if (stage == 2)
1422                 ret = update_stages(o, rename->path, NULL, rename, add);
1423         else
1424                 ret = update_stages(o, rename->path, NULL, add, rename);
1425
1426         if (dst_name != rename->path)
1427                 free(dst_name);
1428
1429         return ret;
1430 }
1431
1432 static int conflict_rename_rename_1to2(struct merge_options *o,
1433                                         struct rename_conflict_info *ci)
1434 {
1435         /* One file was renamed in both branches, but to different names. */
1436         struct diff_filespec *one = ci->pair1->one;
1437         struct diff_filespec *a = ci->pair1->two;
1438         struct diff_filespec *b = ci->pair2->two;
1439
1440         output(o, 1, _("CONFLICT (rename/rename): "
1441                "Rename \"%s\"->\"%s\" in branch \"%s\" "
1442                "rename \"%s\"->\"%s\" in \"%s\"%s"),
1443                one->path, a->path, ci->branch1,
1444                one->path, b->path, ci->branch2,
1445                o->call_depth ? _(" (left unresolved)") : "");
1446         if (o->call_depth) {
1447                 struct merge_file_info mfi;
1448                 struct diff_filespec other;
1449                 struct diff_filespec *add;
1450                 if (merge_file_one(o, one->path,
1451                                  &one->oid, one->mode,
1452                                  &a->oid, a->mode,
1453                                  &b->oid, b->mode,
1454                                  ci->branch1, ci->branch2, &mfi))
1455                         return -1;
1456
1457                 /*
1458                  * FIXME: For rename/add-source conflicts (if we could detect
1459                  * such), this is wrong.  We should instead find a unique
1460                  * pathname and then either rename the add-source file to that
1461                  * unique path, or use that unique path instead of src here.
1462                  */
1463                 if (update_file(o, 0, &mfi.oid, mfi.mode, one->path))
1464                         return -1;
1465
1466                 /*
1467                  * Above, we put the merged content at the merge-base's
1468                  * path.  Now we usually need to delete both a->path and
1469                  * b->path.  However, the rename on each side of the merge
1470                  * could also be involved in a rename/add conflict.  In
1471                  * such cases, we should keep the added file around,
1472                  * resolving the conflict at that path in its favor.
1473                  */
1474                 add = filespec_from_entry(&other, ci->dst_entry1, 2 ^ 1);
1475                 if (add) {
1476                         if (update_file(o, 0, &add->oid, add->mode, a->path))
1477                                 return -1;
1478                 }
1479                 else
1480                         remove_file_from_cache(a->path);
1481                 add = filespec_from_entry(&other, ci->dst_entry2, 3 ^ 1);
1482                 if (add) {
1483                         if (update_file(o, 0, &add->oid, add->mode, b->path))
1484                                 return -1;
1485                 }
1486                 else
1487                         remove_file_from_cache(b->path);
1488         } else if (handle_file(o, a, 2, ci) || handle_file(o, b, 3, ci))
1489                 return -1;
1490
1491         return 0;
1492 }
1493
1494 static int conflict_rename_rename_2to1(struct merge_options *o,
1495                                         struct rename_conflict_info *ci)
1496 {
1497         /* Two files, a & b, were renamed to the same thing, c. */
1498         struct diff_filespec *a = ci->pair1->one;
1499         struct diff_filespec *b = ci->pair2->one;
1500         struct diff_filespec *c1 = ci->pair1->two;
1501         struct diff_filespec *c2 = ci->pair2->two;
1502         char *path = c1->path; /* == c2->path */
1503         char *path_side_1_desc;
1504         char *path_side_2_desc;
1505         struct merge_file_info mfi_c1;
1506         struct merge_file_info mfi_c2;
1507         int ret;
1508
1509         output(o, 1, _("CONFLICT (rename/rename): "
1510                "Rename %s->%s in %s. "
1511                "Rename %s->%s in %s"),
1512                a->path, c1->path, ci->branch1,
1513                b->path, c2->path, ci->branch2);
1514
1515         remove_file(o, 1, a->path, o->call_depth || would_lose_untracked(a->path));
1516         remove_file(o, 1, b->path, o->call_depth || would_lose_untracked(b->path));
1517
1518         path_side_1_desc = xstrfmt("%s (was %s)", path, a->path);
1519         path_side_2_desc = xstrfmt("%s (was %s)", path, b->path);
1520         if (merge_file_special_markers(o, a, c1, &ci->ren1_other,
1521                                        path_side_1_desc,
1522                                        o->branch1, c1->path,
1523                                        o->branch2, ci->ren1_other.path, &mfi_c1) ||
1524             merge_file_special_markers(o, b, &ci->ren2_other, c2,
1525                                        path_side_2_desc,
1526                                        o->branch1, ci->ren2_other.path,
1527                                        o->branch2, c2->path, &mfi_c2))
1528                 return -1;
1529         free(path_side_1_desc);
1530         free(path_side_2_desc);
1531
1532         if (o->call_depth) {
1533                 /*
1534                  * If mfi_c1.clean && mfi_c2.clean, then it might make
1535                  * sense to do a two-way merge of those results.  But, I
1536                  * think in all cases, it makes sense to have the virtual
1537                  * merge base just undo the renames; they can be detected
1538                  * again later for the non-recursive merge.
1539                  */
1540                 remove_file(o, 0, path, 0);
1541                 ret = update_file(o, 0, &mfi_c1.oid, mfi_c1.mode, a->path);
1542                 if (!ret)
1543                         ret = update_file(o, 0, &mfi_c2.oid, mfi_c2.mode,
1544                                           b->path);
1545         } else {
1546                 char *new_path1 = unique_path(o, path, ci->branch1);
1547                 char *new_path2 = unique_path(o, path, ci->branch2);
1548                 output(o, 1, _("Renaming %s to %s and %s to %s instead"),
1549                        a->path, new_path1, b->path, new_path2);
1550                 if (was_dirty(o, path))
1551                         output(o, 1, _("Refusing to lose dirty file at %s"),
1552                                path);
1553                 else if (would_lose_untracked(path))
1554                         /*
1555                          * Only way we get here is if both renames were from
1556                          * a directory rename AND user had an untracked file
1557                          * at the location where both files end up after the
1558                          * two directory renames.  See testcase 10d of t6043.
1559                          */
1560                         output(o, 1, _("Refusing to lose untracked file at "
1561                                        "%s, even though it's in the way."),
1562                                path);
1563                 else
1564                         remove_file(o, 0, path, 0);
1565                 ret = update_file(o, 0, &mfi_c1.oid, mfi_c1.mode, new_path1);
1566                 if (!ret)
1567                         ret = update_file(o, 0, &mfi_c2.oid, mfi_c2.mode,
1568                                           new_path2);
1569                 /*
1570                  * unpack_trees() actually populates the index for us for
1571                  * "normal" rename/rename(2to1) situtations so that the
1572                  * correct entries are at the higher stages, which would
1573                  * make the call below to update_stages_for_stage_data
1574                  * unnecessary.  However, if either of the renames came
1575                  * from a directory rename, then unpack_trees() will not
1576                  * have gotten the right data loaded into the index, so we
1577                  * need to do so now.  (While it'd be tempting to move this
1578                  * call to update_stages_for_stage_data() to
1579                  * apply_directory_rename_modifications(), that would break
1580                  * our intermediate calls to would_lose_untracked() since
1581                  * those rely on the current in-memory index.  See also the
1582                  * big "NOTE" in update_stages()).
1583                  */
1584                 if (update_stages_for_stage_data(o, path, ci->dst_entry1))
1585                         ret = -1;
1586
1587                 free(new_path2);
1588                 free(new_path1);
1589         }
1590
1591         return ret;
1592 }
1593
1594 /*
1595  * Get the diff_filepairs changed between o_tree and tree.
1596  */
1597 static struct diff_queue_struct *get_diffpairs(struct merge_options *o,
1598                                                struct tree *o_tree,
1599                                                struct tree *tree)
1600 {
1601         struct diff_queue_struct *ret;
1602         struct diff_options opts;
1603
1604         diff_setup(&opts);
1605         opts.flags.recursive = 1;
1606         opts.flags.rename_empty = 0;
1607         opts.detect_rename = merge_detect_rename(o);
1608         /*
1609          * We do not have logic to handle the detection of copies.  In
1610          * fact, it may not even make sense to add such logic: would we
1611          * really want a change to a base file to be propagated through
1612          * multiple other files by a merge?
1613          */
1614         if (opts.detect_rename > DIFF_DETECT_RENAME)
1615                 opts.detect_rename = DIFF_DETECT_RENAME;
1616         opts.rename_limit = o->merge_rename_limit >= 0 ? o->merge_rename_limit :
1617                             o->diff_rename_limit >= 0 ? o->diff_rename_limit :
1618                             1000;
1619         opts.rename_score = o->rename_score;
1620         opts.show_rename_progress = o->show_rename_progress;
1621         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1622         diff_setup_done(&opts);
1623         diff_tree_oid(&o_tree->object.oid, &tree->object.oid, "", &opts);
1624         diffcore_std(&opts);
1625         if (opts.needed_rename_limit > o->needed_rename_limit)
1626                 o->needed_rename_limit = opts.needed_rename_limit;
1627
1628         ret = xmalloc(sizeof(*ret));
1629         *ret = diff_queued_diff;
1630
1631         opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1632         diff_queued_diff.nr = 0;
1633         diff_queued_diff.queue = NULL;
1634         diff_flush(&opts);
1635         return ret;
1636 }
1637
1638 static int tree_has_path(struct tree *tree, const char *path)
1639 {
1640         struct object_id hashy;
1641         unsigned int mode_o;
1642
1643         return !get_tree_entry(&tree->object.oid, path,
1644                                &hashy, &mode_o);
1645 }
1646
1647 /*
1648  * Return a new string that replaces the beginning portion (which matches
1649  * entry->dir), with entry->new_dir.  In perl-speak:
1650  *   new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);
1651  * NOTE:
1652  *   Caller must ensure that old_path starts with entry->dir + '/'.
1653  */
1654 static char *apply_dir_rename(struct dir_rename_entry *entry,
1655                               const char *old_path)
1656 {
1657         struct strbuf new_path = STRBUF_INIT;
1658         int oldlen, newlen;
1659
1660         if (entry->non_unique_new_dir)
1661                 return NULL;
1662
1663         oldlen = strlen(entry->dir);
1664         newlen = entry->new_dir.len + (strlen(old_path) - oldlen) + 1;
1665         strbuf_grow(&new_path, newlen);
1666         strbuf_addbuf(&new_path, &entry->new_dir);
1667         strbuf_addstr(&new_path, &old_path[oldlen]);
1668
1669         return strbuf_detach(&new_path, NULL);
1670 }
1671
1672 static void get_renamed_dir_portion(const char *old_path, const char *new_path,
1673                                     char **old_dir, char **new_dir)
1674 {
1675         char *end_of_old, *end_of_new;
1676         int old_len, new_len;
1677
1678         *old_dir = NULL;
1679         *new_dir = NULL;
1680
1681         /*
1682          * For
1683          *    "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
1684          * the "e/foo.c" part is the same, we just want to know that
1685          *    "a/b/c/d" was renamed to "a/b/some/thing/else"
1686          * so, for this example, this function returns "a/b/c/d" in
1687          * *old_dir and "a/b/some/thing/else" in *new_dir.
1688          *
1689          * Also, if the basename of the file changed, we don't care.  We
1690          * want to know which portion of the directory, if any, changed.
1691          */
1692         end_of_old = strrchr(old_path, '/');
1693         end_of_new = strrchr(new_path, '/');
1694
1695         if (end_of_old == NULL || end_of_new == NULL)
1696                 return;
1697         while (*--end_of_new == *--end_of_old &&
1698                end_of_old != old_path &&
1699                end_of_new != new_path)
1700                 ; /* Do nothing; all in the while loop */
1701         /*
1702          * We've found the first non-matching character in the directory
1703          * paths.  That means the current directory we were comparing
1704          * represents the rename.  Move end_of_old and end_of_new back
1705          * to the full directory name.
1706          */
1707         if (*end_of_old == '/')
1708                 end_of_old++;
1709         if (*end_of_old != '/')
1710                 end_of_new++;
1711         end_of_old = strchr(end_of_old, '/');
1712         end_of_new = strchr(end_of_new, '/');
1713
1714         /*
1715          * It may have been the case that old_path and new_path were the same
1716          * directory all along.  Don't claim a rename if they're the same.
1717          */
1718         old_len = end_of_old - old_path;
1719         new_len = end_of_new - new_path;
1720
1721         if (old_len != new_len || strncmp(old_path, new_path, old_len)) {
1722                 *old_dir = xstrndup(old_path, old_len);
1723                 *new_dir = xstrndup(new_path, new_len);
1724         }
1725 }
1726
1727 static void remove_hashmap_entries(struct hashmap *dir_renames,
1728                                    struct string_list *items_to_remove)
1729 {
1730         int i;
1731         struct dir_rename_entry *entry;
1732
1733         for (i = 0; i < items_to_remove->nr; i++) {
1734                 entry = items_to_remove->items[i].util;
1735                 hashmap_remove(dir_renames, entry, NULL);
1736         }
1737         string_list_clear(items_to_remove, 0);
1738 }
1739
1740 /*
1741  * See if there is a directory rename for path, and if there are any file
1742  * level conflicts for the renamed location.  If there is a rename and
1743  * there are no conflicts, return the new name.  Otherwise, return NULL.
1744  */
1745 static char *handle_path_level_conflicts(struct merge_options *o,
1746                                          const char *path,
1747                                          struct dir_rename_entry *entry,
1748                                          struct hashmap *collisions,
1749                                          struct tree *tree)
1750 {
1751         char *new_path = NULL;
1752         struct collision_entry *collision_ent;
1753         int clean = 1;
1754         struct strbuf collision_paths = STRBUF_INIT;
1755
1756         /*
1757          * entry has the mapping of old directory name to new directory name
1758          * that we want to apply to path.
1759          */
1760         new_path = apply_dir_rename(entry, path);
1761
1762         if (!new_path) {
1763                 /* This should only happen when entry->non_unique_new_dir set */
1764                 if (!entry->non_unique_new_dir)
1765                         BUG("entry->non_unqiue_dir not set and !new_path");
1766                 output(o, 1, _("CONFLICT (directory rename split): "
1767                                "Unclear where to place %s because directory "
1768                                "%s was renamed to multiple other directories, "
1769                                "with no destination getting a majority of the "
1770                                "files."),
1771                        path, entry->dir);
1772                 clean = 0;
1773                 return NULL;
1774         }
1775
1776         /*
1777          * The caller needs to have ensured that it has pre-populated
1778          * collisions with all paths that map to new_path.  Do a quick check
1779          * to ensure that's the case.
1780          */
1781         collision_ent = collision_find_entry(collisions, new_path);
1782         if (collision_ent == NULL)
1783                 BUG("collision_ent is NULL");
1784
1785         /*
1786          * Check for one-sided add/add/.../add conflicts, i.e.
1787          * where implicit renames from the other side doing
1788          * directory rename(s) can affect this side of history
1789          * to put multiple paths into the same location.  Warn
1790          * and bail on directory renames for such paths.
1791          */
1792         if (collision_ent->reported_already) {
1793                 clean = 0;
1794         } else if (tree_has_path(tree, new_path)) {
1795                 collision_ent->reported_already = 1;
1796                 strbuf_add_separated_string_list(&collision_paths, ", ",
1797                                                  &collision_ent->source_files);
1798                 output(o, 1, _("CONFLICT (implicit dir rename): Existing "
1799                                "file/dir at %s in the way of implicit "
1800                                "directory rename(s) putting the following "
1801                                "path(s) there: %s."),
1802                        new_path, collision_paths.buf);
1803                 clean = 0;
1804         } else if (collision_ent->source_files.nr > 1) {
1805                 collision_ent->reported_already = 1;
1806                 strbuf_add_separated_string_list(&collision_paths, ", ",
1807                                                  &collision_ent->source_files);
1808                 output(o, 1, _("CONFLICT (implicit dir rename): Cannot map "
1809                                "more than one path to %s; implicit directory "
1810                                "renames tried to put these paths there: %s"),
1811                        new_path, collision_paths.buf);
1812                 clean = 0;
1813         }
1814
1815         /* Free memory we no longer need */
1816         strbuf_release(&collision_paths);
1817         if (!clean && new_path) {
1818                 free(new_path);
1819                 return NULL;
1820         }
1821
1822         return new_path;
1823 }
1824
1825 /*
1826  * There are a couple things we want to do at the directory level:
1827  *   1. Check for both sides renaming to the same thing, in order to avoid
1828  *      implicit renaming of files that should be left in place.  (See
1829  *      testcase 6b in t6043 for details.)
1830  *   2. Prune directory renames if there are still files left in the
1831  *      the original directory.  These represent a partial directory rename,
1832  *      i.e. a rename where only some of the files within the directory
1833  *      were renamed elsewhere.  (Technically, this could be done earlier
1834  *      in get_directory_renames(), except that would prevent us from
1835  *      doing the previous check and thus failing testcase 6b.)
1836  *   3. Check for rename/rename(1to2) conflicts (at the directory level).
1837  *      In the future, we could potentially record this info as well and
1838  *      omit reporting rename/rename(1to2) conflicts for each path within
1839  *      the affected directories, thus cleaning up the merge output.
1840  *   NOTE: We do NOT check for rename/rename(2to1) conflicts at the
1841  *         directory level, because merging directories is fine.  If it
1842  *         causes conflicts for files within those merged directories, then
1843  *         that should be detected at the individual path level.
1844  */
1845 static void handle_directory_level_conflicts(struct merge_options *o,
1846                                              struct hashmap *dir_re_head,
1847                                              struct tree *head,
1848                                              struct hashmap *dir_re_merge,
1849                                              struct tree *merge)
1850 {
1851         struct hashmap_iter iter;
1852         struct dir_rename_entry *head_ent;
1853         struct dir_rename_entry *merge_ent;
1854
1855         struct string_list remove_from_head = STRING_LIST_INIT_NODUP;
1856         struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;
1857
1858         hashmap_iter_init(dir_re_head, &iter);
1859         while ((head_ent = hashmap_iter_next(&iter))) {
1860                 merge_ent = dir_rename_find_entry(dir_re_merge, head_ent->dir);
1861                 if (merge_ent &&
1862                     !head_ent->non_unique_new_dir &&
1863                     !merge_ent->non_unique_new_dir &&
1864                     !strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {
1865                         /* 1. Renamed identically; remove it from both sides */
1866                         string_list_append(&remove_from_head,
1867                                            head_ent->dir)->util = head_ent;
1868                         strbuf_release(&head_ent->new_dir);
1869                         string_list_append(&remove_from_merge,
1870                                            merge_ent->dir)->util = merge_ent;
1871                         strbuf_release(&merge_ent->new_dir);
1872                 } else if (tree_has_path(head, head_ent->dir)) {
1873                         /* 2. This wasn't a directory rename after all */
1874                         string_list_append(&remove_from_head,
1875                                            head_ent->dir)->util = head_ent;
1876                         strbuf_release(&head_ent->new_dir);
1877                 }
1878         }
1879
1880         remove_hashmap_entries(dir_re_head, &remove_from_head);
1881         remove_hashmap_entries(dir_re_merge, &remove_from_merge);
1882
1883         hashmap_iter_init(dir_re_merge, &iter);
1884         while ((merge_ent = hashmap_iter_next(&iter))) {
1885                 head_ent = dir_rename_find_entry(dir_re_head, merge_ent->dir);
1886                 if (tree_has_path(merge, merge_ent->dir)) {
1887                         /* 2. This wasn't a directory rename after all */
1888                         string_list_append(&remove_from_merge,
1889                                            merge_ent->dir)->util = merge_ent;
1890                 } else if (head_ent &&
1891                            !head_ent->non_unique_new_dir &&
1892                            !merge_ent->non_unique_new_dir) {
1893                         /* 3. rename/rename(1to2) */
1894                         /*
1895                          * We can assume it's not rename/rename(1to1) because
1896                          * that was case (1), already checked above.  So we
1897                          * know that head_ent->new_dir and merge_ent->new_dir
1898                          * are different strings.
1899                          */
1900                         output(o, 1, _("CONFLICT (rename/rename): "
1901                                        "Rename directory %s->%s in %s. "
1902                                        "Rename directory %s->%s in %s"),
1903                                head_ent->dir, head_ent->new_dir.buf, o->branch1,
1904                                head_ent->dir, merge_ent->new_dir.buf, o->branch2);
1905                         string_list_append(&remove_from_head,
1906                                            head_ent->dir)->util = head_ent;
1907                         strbuf_release(&head_ent->new_dir);
1908                         string_list_append(&remove_from_merge,
1909                                            merge_ent->dir)->util = merge_ent;
1910                         strbuf_release(&merge_ent->new_dir);
1911                 }
1912         }
1913
1914         remove_hashmap_entries(dir_re_head, &remove_from_head);
1915         remove_hashmap_entries(dir_re_merge, &remove_from_merge);
1916 }
1917
1918 static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs,
1919                                              struct tree *tree)
1920 {
1921         struct hashmap *dir_renames;
1922         struct hashmap_iter iter;
1923         struct dir_rename_entry *entry;
1924         int i;
1925
1926         /*
1927          * Typically, we think of a directory rename as all files from a
1928          * certain directory being moved to a target directory.  However,
1929          * what if someone first moved two files from the original
1930          * directory in one commit, and then renamed the directory
1931          * somewhere else in a later commit?  At merge time, we just know
1932          * that files from the original directory went to two different
1933          * places, and that the bulk of them ended up in the same place.
1934          * We want each directory rename to represent where the bulk of the
1935          * files from that directory end up; this function exists to find
1936          * where the bulk of the files went.
1937          *
1938          * The first loop below simply iterates through the list of file
1939          * renames, finding out how often each directory rename pair
1940          * possibility occurs.
1941          */
1942         dir_renames = xmalloc(sizeof(*dir_renames));
1943         dir_rename_init(dir_renames);
1944         for (i = 0; i < pairs->nr; ++i) {
1945                 struct string_list_item *item;
1946                 int *count;
1947                 struct diff_filepair *pair = pairs->queue[i];
1948                 char *old_dir, *new_dir;
1949
1950                 /* File not part of directory rename if it wasn't renamed */
1951                 if (pair->status != 'R')
1952                         continue;
1953
1954                 get_renamed_dir_portion(pair->one->path, pair->two->path,
1955                                         &old_dir,        &new_dir);
1956                 if (!old_dir)
1957                         /* Directory didn't change at all; ignore this one. */
1958                         continue;
1959
1960                 entry = dir_rename_find_entry(dir_renames, old_dir);
1961                 if (!entry) {
1962                         entry = xmalloc(sizeof(*entry));
1963                         dir_rename_entry_init(entry, old_dir);
1964                         hashmap_put(dir_renames, entry);
1965                 } else {
1966                         free(old_dir);
1967                 }
1968                 item = string_list_lookup(&entry->possible_new_dirs, new_dir);
1969                 if (!item) {
1970                         item = string_list_insert(&entry->possible_new_dirs,
1971                                                   new_dir);
1972                         item->util = xcalloc(1, sizeof(int));
1973                 } else {
1974                         free(new_dir);
1975                 }
1976                 count = item->util;
1977                 *count += 1;
1978         }
1979
1980         /*
1981          * For each directory with files moved out of it, we find out which
1982          * target directory received the most files so we can declare it to
1983          * be the "winning" target location for the directory rename.  This
1984          * winner gets recorded in new_dir.  If there is no winner
1985          * (multiple target directories received the same number of files),
1986          * we set non_unique_new_dir.  Once we've determined the winner (or
1987          * that there is no winner), we no longer need possible_new_dirs.
1988          */
1989         hashmap_iter_init(dir_renames, &iter);
1990         while ((entry = hashmap_iter_next(&iter))) {
1991                 int max = 0;
1992                 int bad_max = 0;
1993                 char *best = NULL;
1994
1995                 for (i = 0; i < entry->possible_new_dirs.nr; i++) {
1996                         int *count = entry->possible_new_dirs.items[i].util;
1997
1998                         if (*count == max)
1999                                 bad_max = max;
2000                         else if (*count > max) {
2001                                 max = *count;
2002                                 best = entry->possible_new_dirs.items[i].string;
2003                         }
2004                 }
2005                 if (bad_max == max)
2006                         entry->non_unique_new_dir = 1;
2007                 else {
2008                         assert(entry->new_dir.len == 0);
2009                         strbuf_addstr(&entry->new_dir, best);
2010                 }
2011                 /*
2012                  * The relevant directory sub-portion of the original full
2013                  * filepaths were xstrndup'ed before inserting into
2014                  * possible_new_dirs, and instead of manually iterating the
2015                  * list and free'ing each, just lie and tell
2016                  * possible_new_dirs that it did the strdup'ing so that it
2017                  * will free them for us.
2018                  */
2019                 entry->possible_new_dirs.strdup_strings = 1;
2020                 string_list_clear(&entry->possible_new_dirs, 1);
2021         }
2022
2023         return dir_renames;
2024 }
2025
2026 static struct dir_rename_entry *check_dir_renamed(const char *path,
2027                                                   struct hashmap *dir_renames)
2028 {
2029         char temp[PATH_MAX];
2030         char *end;
2031         struct dir_rename_entry *entry;
2032
2033         strcpy(temp, path);
2034         while ((end = strrchr(temp, '/'))) {
2035                 *end = '\0';
2036                 entry = dir_rename_find_entry(dir_renames, temp);
2037                 if (entry)
2038                         return entry;
2039         }
2040         return NULL;
2041 }
2042
2043 static void compute_collisions(struct hashmap *collisions,
2044                                struct hashmap *dir_renames,
2045                                struct diff_queue_struct *pairs)
2046 {
2047         int i;
2048
2049         /*
2050          * Multiple files can be mapped to the same path due to directory
2051          * renames done by the other side of history.  Since that other
2052          * side of history could have merged multiple directories into one,
2053          * if our side of history added the same file basename to each of
2054          * those directories, then all N of them would get implicitly
2055          * renamed by the directory rename detection into the same path,
2056          * and we'd get an add/add/.../add conflict, and all those adds
2057          * from *this* side of history.  This is not representable in the
2058          * index, and users aren't going to easily be able to make sense of
2059          * it.  So we need to provide a good warning about what's
2060          * happening, and fall back to no-directory-rename detection
2061          * behavior for those paths.
2062          *
2063          * See testcases 9e and all of section 5 from t6043 for examples.
2064          */
2065         collision_init(collisions);
2066
2067         for (i = 0; i < pairs->nr; ++i) {
2068                 struct dir_rename_entry *dir_rename_ent;
2069                 struct collision_entry *collision_ent;
2070                 char *new_path;
2071                 struct diff_filepair *pair = pairs->queue[i];
2072
2073                 if (pair->status != 'A' && pair->status != 'R')
2074                         continue;
2075                 dir_rename_ent = check_dir_renamed(pair->two->path,
2076                                                    dir_renames);
2077                 if (!dir_rename_ent)
2078                         continue;
2079
2080                 new_path = apply_dir_rename(dir_rename_ent, pair->two->path);
2081                 if (!new_path)
2082                         /*
2083                          * dir_rename_ent->non_unique_new_path is true, which
2084                          * means there is no directory rename for us to use,
2085                          * which means it won't cause us any additional
2086                          * collisions.
2087                          */
2088                         continue;
2089                 collision_ent = collision_find_entry(collisions, new_path);
2090                 if (!collision_ent) {
2091                         collision_ent = xcalloc(1,
2092                                                 sizeof(struct collision_entry));
2093                         hashmap_entry_init(collision_ent, strhash(new_path));
2094                         hashmap_put(collisions, collision_ent);
2095                         collision_ent->target_file = new_path;
2096                 } else {
2097                         free(new_path);
2098                 }
2099                 string_list_insert(&collision_ent->source_files,
2100                                    pair->two->path);
2101         }
2102 }
2103
2104 static char *check_for_directory_rename(struct merge_options *o,
2105                                         const char *path,
2106                                         struct tree *tree,
2107                                         struct hashmap *dir_renames,
2108                                         struct hashmap *dir_rename_exclusions,
2109                                         struct hashmap *collisions,
2110                                         int *clean_merge)
2111 {
2112         char *new_path = NULL;
2113         struct dir_rename_entry *entry = check_dir_renamed(path, dir_renames);
2114         struct dir_rename_entry *oentry = NULL;
2115
2116         if (!entry)
2117                 return new_path;
2118
2119         /*
2120          * This next part is a little weird.  We do not want to do an
2121          * implicit rename into a directory we renamed on our side, because
2122          * that will result in a spurious rename/rename(1to2) conflict.  An
2123          * example:
2124          *   Base commit: dumbdir/afile, otherdir/bfile
2125          *   Side 1:      smrtdir/afile, otherdir/bfile
2126          *   Side 2:      dumbdir/afile, dumbdir/bfile
2127          * Here, while working on Side 1, we could notice that otherdir was
2128          * renamed/merged to dumbdir, and change the diff_filepair for
2129          * otherdir/bfile into a rename into dumbdir/bfile.  However, Side
2130          * 2 will notice the rename from dumbdir to smrtdir, and do the
2131          * transitive rename to move it from dumbdir/bfile to
2132          * smrtdir/bfile.  That gives us bfile in dumbdir vs being in
2133          * smrtdir, a rename/rename(1to2) conflict.  We really just want
2134          * the file to end up in smrtdir.  And the way to achieve that is
2135          * to not let Side1 do the rename to dumbdir, since we know that is
2136          * the source of one of our directory renames.
2137          *
2138          * That's why oentry and dir_rename_exclusions is here.
2139          *
2140          * As it turns out, this also prevents N-way transient rename
2141          * confusion; See testcases 9c and 9d of t6043.
2142          */
2143         oentry = dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);
2144         if (oentry) {
2145                 output(o, 1, _("WARNING: Avoiding applying %s -> %s rename "
2146                                "to %s, because %s itself was renamed."),
2147                        entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);
2148         } else {
2149                 new_path = handle_path_level_conflicts(o, path, entry,
2150                                                        collisions, tree);
2151                 *clean_merge &= (new_path != NULL);
2152         }
2153
2154         return new_path;
2155 }
2156
2157 static void apply_directory_rename_modifications(struct merge_options *o,
2158                                                  struct diff_filepair *pair,
2159                                                  char *new_path,
2160                                                  struct rename *re,
2161                                                  struct tree *tree,
2162                                                  struct tree *o_tree,
2163                                                  struct tree *a_tree,
2164                                                  struct tree *b_tree,
2165                                                  struct string_list *entries,
2166                                                  int *clean)
2167 {
2168         struct string_list_item *item;
2169         int stage = (tree == a_tree ? 2 : 3);
2170         int update_wd;
2171
2172         /*
2173          * In all cases where we can do directory rename detection,
2174          * unpack_trees() will have read pair->two->path into the
2175          * index and the working copy.  We need to remove it so that
2176          * we can instead place it at new_path.  It is guaranteed to
2177          * not be untracked (unpack_trees() would have errored out
2178          * saying the file would have been overwritten), but it might
2179          * be dirty, though.
2180          */
2181         update_wd = !was_dirty(o, pair->two->path);
2182         if (!update_wd)
2183                 output(o, 1, _("Refusing to lose dirty file at %s"),
2184                        pair->two->path);
2185         remove_file(o, 1, pair->two->path, !update_wd);
2186
2187         /* Find or create a new re->dst_entry */
2188         item = string_list_lookup(entries, new_path);
2189         if (item) {
2190                 /*
2191                  * Since we're renaming on this side of history, and it's
2192                  * due to a directory rename on the other side of history
2193                  * (which we only allow when the directory in question no
2194                  * longer exists on the other side of history), the
2195                  * original entry for re->dst_entry is no longer
2196                  * necessary...
2197                  */
2198                 re->dst_entry->processed = 1;
2199
2200                 /*
2201                  * ...because we'll be using this new one.
2202                  */
2203                 re->dst_entry = item->util;
2204         } else {
2205                 /*
2206                  * re->dst_entry is for the before-dir-rename path, and we
2207                  * need it to hold information for the after-dir-rename
2208                  * path.  Before creating a new entry, we need to mark the
2209                  * old one as unnecessary (...unless it is shared by
2210                  * src_entry, i.e. this didn't use to be a rename, in which
2211                  * case we can just allow the normal processing to happen
2212                  * for it).
2213                  */
2214                 if (pair->status == 'R')
2215                         re->dst_entry->processed = 1;
2216
2217                 re->dst_entry = insert_stage_data(new_path,
2218                                                   o_tree, a_tree, b_tree,
2219                                                   entries);
2220                 item = string_list_insert(entries, new_path);
2221                 item->util = re->dst_entry;
2222         }
2223
2224         /*
2225          * Update the stage_data with the information about the path we are
2226          * moving into place.  That slot will be empty and available for us
2227          * to write to because of the collision checks in
2228          * handle_path_level_conflicts().  In other words,
2229          * re->dst_entry->stages[stage].oid will be the null_oid, so it's
2230          * open for us to write to.
2231          *
2232          * It may be tempting to actually update the index at this point as
2233          * well, using update_stages_for_stage_data(), but as per the big
2234          * "NOTE" in update_stages(), doing so will modify the current
2235          * in-memory index which will break calls to would_lose_untracked()
2236          * that we need to make.  Instead, we need to just make sure that
2237          * the various conflict_rename_*() functions update the index
2238          * explicitly rather than relying on unpack_trees() to have done it.
2239          */
2240         get_tree_entry(&tree->object.oid,
2241                        pair->two->path,
2242                        &re->dst_entry->stages[stage].oid,
2243                        &re->dst_entry->stages[stage].mode);
2244
2245         /* Update pair status */
2246         if (pair->status == 'A') {
2247                 /*
2248                  * Recording rename information for this add makes it look
2249                  * like a rename/delete conflict.  Make sure we can
2250                  * correctly handle this as an add that was moved to a new
2251                  * directory instead of reporting a rename/delete conflict.
2252                  */
2253                 re->add_turned_into_rename = 1;
2254         }
2255         /*
2256          * We don't actually look at pair->status again, but it seems
2257          * pedagogically correct to adjust it.
2258          */
2259         pair->status = 'R';
2260
2261         /*
2262          * Finally, record the new location.
2263          */
2264         pair->two->path = new_path;
2265 }
2266
2267 /*
2268  * Get information of all renames which occurred in 'pairs', making use of
2269  * any implicit directory renames inferred from the other side of history.
2270  * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')
2271  * to be able to associate the correct cache entries with the rename
2272  * information; tree is always equal to either a_tree or b_tree.
2273  */
2274 static struct string_list *get_renames(struct merge_options *o,
2275                                        struct diff_queue_struct *pairs,
2276                                        struct hashmap *dir_renames,
2277                                        struct hashmap *dir_rename_exclusions,
2278                                        struct tree *tree,
2279                                        struct tree *o_tree,
2280                                        struct tree *a_tree,
2281                                        struct tree *b_tree,
2282                                        struct string_list *entries,
2283                                        int *clean_merge)
2284 {
2285         int i;
2286         struct hashmap collisions;
2287         struct hashmap_iter iter;
2288         struct collision_entry *e;
2289         struct string_list *renames;
2290
2291         compute_collisions(&collisions, dir_renames, pairs);
2292         renames = xcalloc(1, sizeof(struct string_list));
2293
2294         for (i = 0; i < pairs->nr; ++i) {
2295                 struct string_list_item *item;
2296                 struct rename *re;
2297                 struct diff_filepair *pair = pairs->queue[i];
2298                 char *new_path; /* non-NULL only with directory renames */
2299
2300                 if (pair->status != 'A' && pair->status != 'R') {
2301                         diff_free_filepair(pair);
2302                         continue;
2303                 }
2304                 new_path = check_for_directory_rename(o, pair->two->path, tree,
2305                                                       dir_renames,
2306                                                       dir_rename_exclusions,
2307                                                       &collisions,
2308                                                       clean_merge);
2309                 if (pair->status != 'R' && !new_path) {
2310                         diff_free_filepair(pair);
2311                         continue;
2312                 }
2313
2314                 re = xmalloc(sizeof(*re));
2315                 re->processed = 0;
2316                 re->add_turned_into_rename = 0;
2317                 re->pair = pair;
2318                 item = string_list_lookup(entries, re->pair->one->path);
2319                 if (!item)
2320                         re->src_entry = insert_stage_data(re->pair->one->path,
2321                                         o_tree, a_tree, b_tree, entries);
2322                 else
2323                         re->src_entry = item->util;
2324
2325                 item = string_list_lookup(entries, re->pair->two->path);
2326                 if (!item)
2327                         re->dst_entry = insert_stage_data(re->pair->two->path,
2328                                         o_tree, a_tree, b_tree, entries);
2329                 else
2330                         re->dst_entry = item->util;
2331                 item = string_list_insert(renames, pair->one->path);
2332                 item->util = re;
2333                 if (new_path)
2334                         apply_directory_rename_modifications(o, pair, new_path,
2335                                                              re, tree, o_tree,
2336                                                              a_tree, b_tree,
2337                                                              entries,
2338                                                              clean_merge);
2339         }
2340
2341         hashmap_iter_init(&collisions, &iter);
2342         while ((e = hashmap_iter_next(&iter))) {
2343                 free(e->target_file);
2344                 string_list_clear(&e->source_files, 0);
2345         }
2346         hashmap_free(&collisions, 1);
2347         return renames;
2348 }
2349
2350 static int process_renames(struct merge_options *o,
2351                            struct string_list *a_renames,
2352                            struct string_list *b_renames)
2353 {
2354         int clean_merge = 1, i, j;
2355         struct string_list a_by_dst = STRING_LIST_INIT_NODUP;
2356         struct string_list b_by_dst = STRING_LIST_INIT_NODUP;
2357         const struct rename *sre;
2358
2359         for (i = 0; i < a_renames->nr; i++) {
2360                 sre = a_renames->items[i].util;
2361                 string_list_insert(&a_by_dst, sre->pair->two->path)->util
2362                         = (void *)sre;
2363         }
2364         for (i = 0; i < b_renames->nr; i++) {
2365                 sre = b_renames->items[i].util;
2366                 string_list_insert(&b_by_dst, sre->pair->two->path)->util
2367                         = (void *)sre;
2368         }
2369
2370         for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
2371                 struct string_list *renames1, *renames2Dst;
2372                 struct rename *ren1 = NULL, *ren2 = NULL;
2373                 const char *branch1, *branch2;
2374                 const char *ren1_src, *ren1_dst;
2375                 struct string_list_item *lookup;
2376
2377                 if (i >= a_renames->nr) {
2378                         ren2 = b_renames->items[j++].util;
2379                 } else if (j >= b_renames->nr) {
2380                         ren1 = a_renames->items[i++].util;
2381                 } else {
2382                         int compare = strcmp(a_renames->items[i].string,
2383                                              b_renames->items[j].string);
2384                         if (compare <= 0)
2385                                 ren1 = a_renames->items[i++].util;
2386                         if (compare >= 0)
2387                                 ren2 = b_renames->items[j++].util;
2388                 }
2389
2390                 /* TODO: refactor, so that 1/2 are not needed */
2391                 if (ren1) {
2392                         renames1 = a_renames;
2393                         renames2Dst = &b_by_dst;
2394                         branch1 = o->branch1;
2395                         branch2 = o->branch2;
2396                 } else {
2397                         renames1 = b_renames;
2398                         renames2Dst = &a_by_dst;
2399                         branch1 = o->branch2;
2400                         branch2 = o->branch1;
2401                         SWAP(ren2, ren1);
2402                 }
2403
2404                 if (ren1->processed)
2405                         continue;
2406                 ren1->processed = 1;
2407                 ren1->dst_entry->processed = 1;
2408                 /* BUG: We should only mark src_entry as processed if we
2409                  * are not dealing with a rename + add-source case.
2410                  */
2411                 ren1->src_entry->processed = 1;
2412
2413                 ren1_src = ren1->pair->one->path;
2414                 ren1_dst = ren1->pair->two->path;
2415
2416                 if (ren2) {
2417                         /* One file renamed on both sides */
2418                         const char *ren2_src = ren2->pair->one->path;
2419                         const char *ren2_dst = ren2->pair->two->path;
2420                         enum rename_type rename_type;
2421                         if (strcmp(ren1_src, ren2_src) != 0)
2422                                 die("BUG: ren1_src != ren2_src");
2423                         ren2->dst_entry->processed = 1;
2424                         ren2->processed = 1;
2425                         if (strcmp(ren1_dst, ren2_dst) != 0) {
2426                                 rename_type = RENAME_ONE_FILE_TO_TWO;
2427                                 clean_merge = 0;
2428                         } else {
2429                                 rename_type = RENAME_ONE_FILE_TO_ONE;
2430                                 /* BUG: We should only remove ren1_src in
2431                                  * the base stage (think of rename +
2432                                  * add-source cases).
2433                                  */
2434                                 remove_file(o, 1, ren1_src, 1);
2435                                 update_entry(ren1->dst_entry,
2436                                              ren1->pair->one,
2437                                              ren1->pair->two,
2438                                              ren2->pair->two);
2439                         }
2440                         setup_rename_conflict_info(rename_type,
2441                                                    ren1->pair,
2442                                                    ren2->pair,
2443                                                    branch1,
2444                                                    branch2,
2445                                                    ren1->dst_entry,
2446                                                    ren2->dst_entry,
2447                                                    o,
2448                                                    NULL,
2449                                                    NULL);
2450                 } else if ((lookup = string_list_lookup(renames2Dst, ren1_dst))) {
2451                         /* Two different files renamed to the same thing */
2452                         char *ren2_dst;
2453                         ren2 = lookup->util;
2454                         ren2_dst = ren2->pair->two->path;
2455                         if (strcmp(ren1_dst, ren2_dst) != 0)
2456                                 die("BUG: ren1_dst != ren2_dst");
2457
2458                         clean_merge = 0;
2459                         ren2->processed = 1;
2460                         /*
2461                          * BUG: We should only mark src_entry as processed
2462                          * if we are not dealing with a rename + add-source
2463                          * case.
2464                          */
2465                         ren2->src_entry->processed = 1;
2466
2467                         setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,
2468                                                    ren1->pair,
2469                                                    ren2->pair,
2470                                                    branch1,
2471                                                    branch2,
2472                                                    ren1->dst_entry,
2473                                                    ren2->dst_entry,
2474                                                    o,
2475                                                    ren1->src_entry,
2476                                                    ren2->src_entry);
2477
2478                 } else {
2479                         /* Renamed in 1, maybe changed in 2 */
2480                         /* we only use sha1 and mode of these */
2481                         struct diff_filespec src_other, dst_other;
2482                         int try_merge;
2483
2484                         /*
2485                          * unpack_trees loads entries from common-commit
2486                          * into stage 1, from head-commit into stage 2, and
2487                          * from merge-commit into stage 3.  We keep track
2488                          * of which side corresponds to the rename.
2489                          */
2490                         int renamed_stage = a_renames == renames1 ? 2 : 3;
2491                         int other_stage =   a_renames == renames1 ? 3 : 2;
2492
2493                         /* BUG: We should only remove ren1_src in the base
2494                          * stage and in other_stage (think of rename +
2495                          * add-source case).
2496                          */
2497                         remove_file(o, 1, ren1_src,
2498                                     renamed_stage == 2 || !was_tracked(o, ren1_src));
2499
2500                         oidcpy(&src_other.oid,
2501                                &ren1->src_entry->stages[other_stage].oid);
2502                         src_other.mode = ren1->src_entry->stages[other_stage].mode;
2503                         oidcpy(&dst_other.oid,
2504                                &ren1->dst_entry->stages[other_stage].oid);
2505                         dst_other.mode = ren1->dst_entry->stages[other_stage].mode;
2506                         try_merge = 0;
2507
2508                         if (oid_eq(&src_other.oid, &null_oid) &&
2509                             ren1->add_turned_into_rename) {
2510                                 setup_rename_conflict_info(RENAME_DIR,
2511                                                            ren1->pair,
2512                                                            NULL,
2513                                                            branch1,
2514                                                            branch2,
2515                                                            ren1->dst_entry,
2516                                                            NULL,
2517                                                            o,
2518                                                            NULL,
2519                                                            NULL);
2520                         } else if (oid_eq(&src_other.oid, &null_oid)) {
2521                                 setup_rename_conflict_info(RENAME_DELETE,
2522                                                            ren1->pair,
2523                                                            NULL,
2524                                                            branch1,
2525                                                            branch2,
2526                                                            ren1->dst_entry,
2527                                                            NULL,
2528                                                            o,
2529                                                            NULL,
2530                                                            NULL);
2531                         } else if ((dst_other.mode == ren1->pair->two->mode) &&
2532                                    oid_eq(&dst_other.oid, &ren1->pair->two->oid)) {
2533                                 /*
2534                                  * Added file on the other side identical to
2535                                  * the file being renamed: clean merge.
2536                                  * Also, there is no need to overwrite the
2537                                  * file already in the working copy, so call
2538                                  * update_file_flags() instead of
2539                                  * update_file().
2540                                  */
2541                                 if (update_file_flags(o,
2542                                                       &ren1->pair->two->oid,
2543                                                       ren1->pair->two->mode,
2544                                                       ren1_dst,
2545                                                       1, /* update_cache */
2546                                                       0  /* update_wd    */))
2547                                         clean_merge = -1;
2548                         } else if (!oid_eq(&dst_other.oid, &null_oid)) {
2549                                 clean_merge = 0;
2550                                 try_merge = 1;
2551                                 output(o, 1, _("CONFLICT (rename/add): Rename %s->%s in %s. "
2552                                        "%s added in %s"),
2553                                        ren1_src, ren1_dst, branch1,
2554                                        ren1_dst, branch2);
2555                                 if (o->call_depth) {
2556                                         struct merge_file_info mfi;
2557                                         if (merge_file_one(o, ren1_dst, &null_oid, 0,
2558                                                            &ren1->pair->two->oid,
2559                                                            ren1->pair->two->mode,
2560                                                            &dst_other.oid,
2561                                                            dst_other.mode,
2562                                                            branch1, branch2, &mfi)) {
2563                                                 clean_merge = -1;
2564                                                 goto cleanup_and_return;
2565                                         }
2566                                         output(o, 1, _("Adding merged %s"), ren1_dst);
2567                                         if (update_file(o, 0, &mfi.oid,
2568                                                         mfi.mode, ren1_dst))
2569                                                 clean_merge = -1;
2570                                         try_merge = 0;
2571                                 } else {
2572                                         char *new_path = unique_path(o, ren1_dst, branch2);
2573                                         output(o, 1, _("Adding as %s instead"), new_path);
2574                                         if (update_file(o, 0, &dst_other.oid,
2575                                                         dst_other.mode, new_path))
2576                                                 clean_merge = -1;
2577                                         free(new_path);
2578                                 }
2579                         } else
2580                                 try_merge = 1;
2581
2582                         if (clean_merge < 0)
2583                                 goto cleanup_and_return;
2584                         if (try_merge) {
2585                                 struct diff_filespec *one, *a, *b;
2586                                 src_other.path = (char *)ren1_src;
2587
2588                                 one = ren1->pair->one;
2589                                 if (a_renames == renames1) {
2590                                         a = ren1->pair->two;
2591                                         b = &src_other;
2592                                 } else {
2593                                         b = ren1->pair->two;
2594                                         a = &src_other;
2595                                 }
2596                                 update_entry(ren1->dst_entry, one, a, b);
2597                                 setup_rename_conflict_info(RENAME_NORMAL,
2598                                                            ren1->pair,
2599                                                            NULL,
2600                                                            branch1,
2601                                                            NULL,
2602                                                            ren1->dst_entry,
2603                                                            NULL,
2604                                                            o,
2605                                                            NULL,
2606                                                            NULL);
2607                         }
2608                 }
2609         }
2610 cleanup_and_return:
2611         string_list_clear(&a_by_dst, 0);
2612         string_list_clear(&b_by_dst, 0);
2613
2614         return clean_merge;
2615 }
2616
2617 struct rename_info {
2618         struct string_list *head_renames;
2619         struct string_list *merge_renames;
2620 };
2621
2622 static void initial_cleanup_rename(struct diff_queue_struct *pairs,
2623                                    struct hashmap *dir_renames)
2624 {
2625         struct hashmap_iter iter;
2626         struct dir_rename_entry *e;
2627
2628         hashmap_iter_init(dir_renames, &iter);
2629         while ((e = hashmap_iter_next(&iter))) {
2630                 free(e->dir);
2631                 strbuf_release(&e->new_dir);
2632                 /* possible_new_dirs already cleared in get_directory_renames */
2633         }
2634         hashmap_free(dir_renames, 1);
2635         free(dir_renames);
2636
2637         free(pairs->queue);
2638         free(pairs);
2639 }
2640
2641 static int handle_renames(struct merge_options *o,
2642                           struct tree *common,
2643                           struct tree *head,
2644                           struct tree *merge,
2645                           struct string_list *entries,
2646                           struct rename_info *ri)
2647 {
2648         struct diff_queue_struct *head_pairs, *merge_pairs;
2649         struct hashmap *dir_re_head, *dir_re_merge;
2650         int clean = 1;
2651
2652         ri->head_renames = NULL;
2653         ri->merge_renames = NULL;
2654
2655         if (!merge_detect_rename(o))
2656                 return 1;
2657
2658         head_pairs = get_diffpairs(o, common, head);
2659         merge_pairs = get_diffpairs(o, common, merge);
2660
2661         dir_re_head = get_directory_renames(head_pairs, head);
2662         dir_re_merge = get_directory_renames(merge_pairs, merge);
2663
2664         handle_directory_level_conflicts(o,
2665                                          dir_re_head, head,
2666                                          dir_re_merge, merge);
2667
2668         ri->head_renames  = get_renames(o, head_pairs,
2669                                         dir_re_merge, dir_re_head, head,
2670                                         common, head, merge, entries,
2671                                         &clean);
2672         if (clean < 0)
2673                 goto cleanup;
2674         ri->merge_renames = get_renames(o, merge_pairs,
2675                                         dir_re_head, dir_re_merge, merge,
2676                                         common, head, merge, entries,
2677                                         &clean);
2678         if (clean < 0)
2679                 goto cleanup;
2680         clean &= process_renames(o, ri->head_renames, ri->merge_renames);
2681
2682 cleanup:
2683         /*
2684          * Some cleanup is deferred until cleanup_renames() because the
2685          * data structures are still needed and referenced in
2686          * process_entry().  But there are a few things we can free now.
2687          */
2688         initial_cleanup_rename(head_pairs, dir_re_head);
2689         initial_cleanup_rename(merge_pairs, dir_re_merge);
2690
2691         return clean;
2692 }
2693
2694 static void final_cleanup_rename(struct string_list *rename)
2695 {
2696         const struct rename *re;
2697         int i;
2698
2699         if (rename == NULL)
2700                 return;
2701
2702         for (i = 0; i < rename->nr; i++) {
2703                 re = rename->items[i].util;
2704                 diff_free_filepair(re->pair);
2705         }
2706         string_list_clear(rename, 1);
2707         free(rename);
2708 }
2709
2710 static void final_cleanup_renames(struct rename_info *re_info)
2711 {
2712         final_cleanup_rename(re_info->head_renames);
2713         final_cleanup_rename(re_info->merge_renames);
2714 }
2715
2716 static struct object_id *stage_oid(const struct object_id *oid, unsigned mode)
2717 {
2718         return (is_null_oid(oid) || mode == 0) ? NULL: (struct object_id *)oid;
2719 }
2720
2721 static int read_oid_strbuf(struct merge_options *o,
2722         const struct object_id *oid, struct strbuf *dst)
2723 {
2724         void *buf;
2725         enum object_type type;
2726         unsigned long size;
2727         buf = read_object_file(oid, &type, &size);
2728         if (!buf)
2729                 return err(o, _("cannot read object %s"), oid_to_hex(oid));
2730         if (type != OBJ_BLOB) {
2731                 free(buf);
2732                 return err(o, _("object %s is not a blob"), oid_to_hex(oid));
2733         }
2734         strbuf_attach(dst, buf, size, size + 1);
2735         return 0;
2736 }
2737
2738 static int blob_unchanged(struct merge_options *opt,
2739                           const struct object_id *o_oid,
2740                           unsigned o_mode,
2741                           const struct object_id *a_oid,
2742                           unsigned a_mode,
2743                           int renormalize, const char *path)
2744 {
2745         struct strbuf o = STRBUF_INIT;
2746         struct strbuf a = STRBUF_INIT;
2747         int ret = 0; /* assume changed for safety */
2748
2749         if (a_mode != o_mode)
2750                 return 0;
2751         if (oid_eq(o_oid, a_oid))
2752                 return 1;
2753         if (!renormalize)
2754                 return 0;
2755
2756         assert(o_oid && a_oid);
2757         if (read_oid_strbuf(opt, o_oid, &o) || read_oid_strbuf(opt, a_oid, &a))
2758                 goto error_return;
2759         /*
2760          * Note: binary | is used so that both renormalizations are
2761          * performed.  Comparison can be skipped if both files are
2762          * unchanged since their sha1s have already been compared.
2763          */
2764         if (renormalize_buffer(&the_index, path, o.buf, o.len, &o) |
2765             renormalize_buffer(&the_index, path, a.buf, a.len, &a))
2766                 ret = (o.len == a.len && !memcmp(o.buf, a.buf, o.len));
2767
2768 error_return:
2769         strbuf_release(&o);
2770         strbuf_release(&a);
2771         return ret;
2772 }
2773
2774 static int handle_modify_delete(struct merge_options *o,
2775                                  const char *path,
2776                                  struct object_id *o_oid, int o_mode,
2777                                  struct object_id *a_oid, int a_mode,
2778                                  struct object_id *b_oid, int b_mode)
2779 {
2780         const char *modify_branch, *delete_branch;
2781         struct object_id *changed_oid;
2782         int changed_mode;
2783
2784         if (a_oid) {
2785                 modify_branch = o->branch1;
2786                 delete_branch = o->branch2;
2787                 changed_oid = a_oid;
2788                 changed_mode = a_mode;
2789         } else {
2790                 modify_branch = o->branch2;
2791                 delete_branch = o->branch1;
2792                 changed_oid = b_oid;
2793                 changed_mode = b_mode;
2794         }
2795
2796         return handle_change_delete(o,
2797                                     path, NULL,
2798                                     o_oid, o_mode,
2799                                     changed_oid, changed_mode,
2800                                     modify_branch, delete_branch,
2801                                     _("modify"), _("modified"));
2802 }
2803
2804 static int merge_content(struct merge_options *o,
2805                          const char *path,
2806                          int is_dirty,
2807                          struct object_id *o_oid, int o_mode,
2808                          struct object_id *a_oid, int a_mode,
2809                          struct object_id *b_oid, int b_mode,
2810                          struct rename_conflict_info *rename_conflict_info)
2811 {
2812         const char *reason = _("content");
2813         const char *path1 = NULL, *path2 = NULL;
2814         struct merge_file_info mfi;
2815         struct diff_filespec one, a, b;
2816         unsigned df_conflict_remains = 0;
2817
2818         if (!o_oid) {
2819                 reason = _("add/add");
2820                 o_oid = (struct object_id *)&null_oid;
2821         }
2822         one.path = a.path = b.path = (char *)path;
2823         oidcpy(&one.oid, o_oid);
2824         one.mode = o_mode;
2825         oidcpy(&a.oid, a_oid);
2826         a.mode = a_mode;
2827         oidcpy(&b.oid, b_oid);
2828         b.mode = b_mode;
2829
2830         if (rename_conflict_info) {
2831                 struct diff_filepair *pair1 = rename_conflict_info->pair1;
2832
2833                 path1 = (o->branch1 == rename_conflict_info->branch1) ?
2834                         pair1->two->path : pair1->one->path;
2835                 /* If rename_conflict_info->pair2 != NULL, we are in
2836                  * RENAME_ONE_FILE_TO_ONE case.  Otherwise, we have a
2837                  * normal rename.
2838                  */
2839                 path2 = (rename_conflict_info->pair2 ||
2840                          o->branch2 == rename_conflict_info->branch1) ?
2841                         pair1->two->path : pair1->one->path;
2842
2843                 if (dir_in_way(path, !o->call_depth,
2844                                S_ISGITLINK(pair1->two->mode)))
2845                         df_conflict_remains = 1;
2846         }
2847         if (merge_file_special_markers(o, &one, &a, &b, path,
2848                                        o->branch1, path1,
2849                                        o->branch2, path2, &mfi))
2850                 return -1;
2851
2852         /*
2853          * We can skip updating the working tree file iff:
2854          *   a) The merge is clean
2855          *   b) The merge matches what was in HEAD (content, mode, pathname)
2856          *   c) The target path is usable (i.e. not involved in D/F conflict)
2857          */
2858         if (mfi.clean &&
2859             was_tracked_and_matches(o, path, &mfi.oid, mfi.mode) &&
2860             !df_conflict_remains) {
2861                 output(o, 3, _("Skipped %s (merged same as existing)"), path);
2862                 if (add_cacheinfo(o, mfi.mode, &mfi.oid, path,
2863                                   0, (!o->call_depth && !is_dirty), 0))
2864                         return -1;
2865                 return mfi.clean;
2866         }
2867
2868         if (!mfi.clean) {
2869                 if (S_ISGITLINK(mfi.mode))
2870                         reason = _("submodule");
2871                 output(o, 1, _("CONFLICT (%s): Merge conflict in %s"),
2872                                 reason, path);
2873                 if (rename_conflict_info && !df_conflict_remains)
2874                         if (update_stages(o, path, &one, &a, &b))
2875                                 return -1;
2876         }
2877
2878         if (df_conflict_remains || is_dirty) {
2879                 char *new_path;
2880                 if (o->call_depth) {
2881                         remove_file_from_cache(path);
2882                 } else {
2883                         if (!mfi.clean) {
2884                                 if (update_stages(o, path, &one, &a, &b))
2885                                         return -1;
2886                         } else {
2887                                 int file_from_stage2 = was_tracked(o, path);
2888                                 struct diff_filespec merged;
2889                                 oidcpy(&merged.oid, &mfi.oid);
2890                                 merged.mode = mfi.mode;
2891
2892                                 if (update_stages(o, path, NULL,
2893                                                   file_from_stage2 ? &merged : NULL,
2894                                                   file_from_stage2 ? NULL : &merged))
2895                                         return -1;
2896                         }
2897
2898                 }
2899                 new_path = unique_path(o, path, rename_conflict_info->branch1);
2900                 if (is_dirty) {
2901                         output(o, 1, _("Refusing to lose dirty file at %s"),
2902                                path);
2903                 }
2904                 output(o, 1, _("Adding as %s instead"), new_path);
2905                 if (update_file(o, 0, &mfi.oid, mfi.mode, new_path)) {
2906                         free(new_path);
2907                         return -1;
2908                 }
2909                 free(new_path);
2910                 mfi.clean = 0;
2911         } else if (update_file(o, mfi.clean, &mfi.oid, mfi.mode, path))
2912                 return -1;
2913         return !is_dirty && mfi.clean;
2914 }
2915
2916 static int conflict_rename_normal(struct merge_options *o,
2917                                   const char *path,
2918                                   struct object_id *o_oid, unsigned int o_mode,
2919                                   struct object_id *a_oid, unsigned int a_mode,
2920                                   struct object_id *b_oid, unsigned int b_mode,
2921                                   struct rename_conflict_info *ci)
2922 {
2923         /* Merge the content and write it out */
2924         return merge_content(o, path, was_dirty(o, path),
2925                              o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,
2926                              ci);
2927 }
2928
2929 /* Per entry merge function */
2930 static int process_entry(struct merge_options *o,
2931                          const char *path, struct stage_data *entry)
2932 {
2933         int clean_merge = 1;
2934         int normalize = o->renormalize;
2935         unsigned o_mode = entry->stages[1].mode;
2936         unsigned a_mode = entry->stages[2].mode;
2937         unsigned b_mode = entry->stages[3].mode;
2938         struct object_id *o_oid = stage_oid(&entry->stages[1].oid, o_mode);
2939         struct object_id *a_oid = stage_oid(&entry->stages[2].oid, a_mode);
2940         struct object_id *b_oid = stage_oid(&entry->stages[3].oid, b_mode);
2941
2942         entry->processed = 1;
2943         if (entry->rename_conflict_info) {
2944                 struct rename_conflict_info *conflict_info = entry->rename_conflict_info;
2945                 switch (conflict_info->rename_type) {
2946                 case RENAME_NORMAL:
2947                 case RENAME_ONE_FILE_TO_ONE:
2948                         clean_merge = conflict_rename_normal(o,
2949                                                              path,
2950                                                              o_oid, o_mode,
2951                                                              a_oid, a_mode,
2952                                                              b_oid, b_mode,
2953                                                              conflict_info);
2954                         break;
2955                 case RENAME_DIR:
2956                         clean_merge = 1;
2957                         if (conflict_rename_dir(o,
2958                                                 conflict_info->pair1,
2959                                                 conflict_info->branch1,
2960                                                 conflict_info->branch2))
2961                                 clean_merge = -1;
2962                         break;
2963                 case RENAME_DELETE:
2964                         clean_merge = 0;
2965                         if (conflict_rename_delete(o,
2966                                                    conflict_info->pair1,
2967                                                    conflict_info->branch1,
2968                                                    conflict_info->branch2))
2969                                 clean_merge = -1;
2970                         break;
2971                 case RENAME_ONE_FILE_TO_TWO:
2972                         clean_merge = 0;
2973                         if (conflict_rename_rename_1to2(o, conflict_info))
2974                                 clean_merge = -1;
2975                         break;
2976                 case RENAME_TWO_FILES_TO_ONE:
2977                         clean_merge = 0;
2978                         if (conflict_rename_rename_2to1(o, conflict_info))
2979                                 clean_merge = -1;
2980                         break;
2981                 default:
2982                         entry->processed = 0;
2983                         break;
2984                 }
2985         } else if (o_oid && (!a_oid || !b_oid)) {
2986                 /* Case A: Deleted in one */
2987                 if ((!a_oid && !b_oid) ||
2988                     (!b_oid && blob_unchanged(o, o_oid, o_mode, a_oid, a_mode, normalize, path)) ||
2989                     (!a_oid && blob_unchanged(o, o_oid, o_mode, b_oid, b_mode, normalize, path))) {
2990                         /* Deleted in both or deleted in one and
2991                          * unchanged in the other */
2992                         if (a_oid)
2993                                 output(o, 2, _("Removing %s"), path);
2994                         /* do not touch working file if it did not exist */
2995                         remove_file(o, 1, path, !a_oid);
2996                 } else {
2997                         /* Modify/delete; deleted side may have put a directory in the way */
2998                         clean_merge = 0;
2999                         if (handle_modify_delete(o, path, o_oid, o_mode,
3000                                                  a_oid, a_mode, b_oid, b_mode))
3001                                 clean_merge = -1;
3002                 }
3003         } else if ((!o_oid && a_oid && !b_oid) ||
3004                    (!o_oid && !a_oid && b_oid)) {
3005                 /* Case B: Added in one. */
3006                 /* [nothing|directory] -> ([nothing|directory], file) */
3007
3008                 const char *add_branch;
3009                 const char *other_branch;
3010                 unsigned mode;
3011                 const struct object_id *oid;
3012                 const char *conf;
3013
3014                 if (a_oid) {
3015                         add_branch = o->branch1;
3016                         other_branch = o->branch2;
3017                         mode = a_mode;
3018                         oid = a_oid;
3019                         conf = _("file/directory");
3020                 } else {
3021                         add_branch = o->branch2;
3022                         other_branch = o->branch1;
3023                         mode = b_mode;
3024                         oid = b_oid;
3025                         conf = _("directory/file");
3026                 }
3027                 if (dir_in_way(path,
3028                                !o->call_depth && !S_ISGITLINK(a_mode),
3029                                0)) {
3030                         char *new_path = unique_path(o, path, add_branch);
3031                         clean_merge = 0;
3032                         output(o, 1, _("CONFLICT (%s): There is a directory with name %s in %s. "
3033                                "Adding %s as %s"),
3034                                conf, path, other_branch, path, new_path);
3035                         if (update_file(o, 0, oid, mode, new_path))
3036                                 clean_merge = -1;
3037                         else if (o->call_depth)
3038                                 remove_file_from_cache(path);
3039                         free(new_path);
3040                 } else {
3041                         output(o, 2, _("Adding %s"), path);
3042                         /* do not overwrite file if already present */
3043                         if (update_file_flags(o, oid, mode, path, 1, !a_oid))
3044                                 clean_merge = -1;
3045                 }
3046         } else if (a_oid && b_oid) {
3047                 /* Case C: Added in both (check for same permissions) and */
3048                 /* case D: Modified in both, but differently. */
3049                 int is_dirty = 0; /* unpack_trees would have bailed if dirty */
3050                 clean_merge = merge_content(o, path, is_dirty,
3051                                             o_oid, o_mode, a_oid, a_mode, b_oid, b_mode,
3052                                             NULL);
3053         } else if (!o_oid && !a_oid && !b_oid) {
3054                 /*
3055                  * this entry was deleted altogether. a_mode == 0 means
3056                  * we had that path and want to actively remove it.
3057                  */
3058                 remove_file(o, 1, path, !a_mode);
3059         } else
3060                 die("BUG: fatal merge failure, shouldn't happen.");
3061
3062         return clean_merge;
3063 }
3064
3065 int merge_trees(struct merge_options *o,
3066                 struct tree *head,
3067                 struct tree *merge,
3068                 struct tree *common,
3069                 struct tree **result)
3070 {
3071         int code, clean;
3072
3073         if (o->subtree_shift) {
3074                 merge = shift_tree_object(head, merge, o->subtree_shift);
3075                 common = shift_tree_object(head, common, o->subtree_shift);
3076         }
3077
3078         if (oid_eq(&common->object.oid, &merge->object.oid)) {
3079                 struct strbuf sb = STRBUF_INIT;
3080
3081                 if (!o->call_depth && index_has_changes(&sb)) {
3082                         err(o, _("Dirty index: cannot merge (dirty: %s)"),
3083                             sb.buf);
3084                         return 0;
3085                 }
3086                 output(o, 0, _("Already up to date!"));
3087                 *result = head;
3088                 return 1;
3089         }
3090
3091         code = git_merge_trees(o, common, head, merge);
3092
3093         if (code != 0) {
3094                 if (show(o, 4) || o->call_depth)
3095                         err(o, _("merging of trees %s and %s failed"),
3096                             oid_to_hex(&head->object.oid),
3097                             oid_to_hex(&merge->object.oid));
3098                 return -1;
3099         }
3100
3101         if (unmerged_cache()) {
3102                 struct string_list *entries;
3103                 struct rename_info re_info;
3104                 int i;
3105                 /*
3106                  * Only need the hashmap while processing entries, so
3107                  * initialize it here and free it when we are done running
3108                  * through the entries. Keeping it in the merge_options as
3109                  * opposed to decaring a local hashmap is for convenience
3110                  * so that we don't have to pass it to around.
3111                  */
3112                 hashmap_init(&o->current_file_dir_set, path_hashmap_cmp, NULL, 512);
3113                 get_files_dirs(o, head);
3114                 get_files_dirs(o, merge);
3115
3116                 entries = get_unmerged();
3117                 clean = handle_renames(o, common, head, merge, entries,
3118                                        &re_info);
3119                 record_df_conflict_files(o, entries);
3120                 if (clean < 0)
3121                         goto cleanup;
3122                 for (i = entries->nr-1; 0 <= i; i--) {
3123                         const char *path = entries->items[i].string;
3124                         struct stage_data *e = entries->items[i].util;
3125                         if (!e->processed) {
3126                                 int ret = process_entry(o, path, e);
3127                                 if (!ret)
3128                                         clean = 0;
3129                                 else if (ret < 0) {
3130                                         clean = ret;
3131                                         goto cleanup;
3132                                 }
3133                         }
3134                 }
3135                 for (i = 0; i < entries->nr; i++) {
3136                         struct stage_data *e = entries->items[i].util;
3137                         if (!e->processed)
3138                                 die("BUG: unprocessed path??? %s",
3139                                     entries->items[i].string);
3140                 }
3141
3142 cleanup:
3143                 final_cleanup_renames(&re_info);
3144
3145                 string_list_clear(entries, 1);
3146                 free(entries);
3147
3148                 hashmap_free(&o->current_file_dir_set, 1);
3149
3150                 if (clean < 0)
3151                         return clean;
3152         }
3153         else
3154                 clean = 1;
3155
3156         /* Free the extra index left from git_merge_trees() */
3157         /*
3158          * FIXME: Need to also free data allocated by
3159          * setup_unpack_trees_porcelain() tucked away in o->unpack_opts.msgs,
3160          * but the problem is that only half of it refers to dynamically
3161          * allocated data, while the other half points at static strings.
3162          */
3163         discard_index(&o->orig_index);
3164
3165         if (o->call_depth && !(*result = write_tree_from_memory(o)))
3166                 return -1;
3167
3168         return clean;
3169 }
3170
3171 static struct commit_list *reverse_commit_list(struct commit_list *list)
3172 {
3173         struct commit_list *next = NULL, *current, *backup;
3174         for (current = list; current; current = backup) {
3175                 backup = current->next;
3176                 current->next = next;
3177                 next = current;
3178         }
3179         return next;
3180 }
3181
3182 /*
3183  * Merge the commits h1 and h2, return the resulting virtual
3184  * commit object and a flag indicating the cleanness of the merge.
3185  */
3186 int merge_recursive(struct merge_options *o,
3187                     struct commit *h1,
3188                     struct commit *h2,
3189                     struct commit_list *ca,
3190                     struct commit **result)
3191 {
3192         struct commit_list *iter;
3193         struct commit *merged_common_ancestors;
3194         struct tree *mrtree;
3195         int clean;
3196
3197         if (show(o, 4)) {
3198                 output(o, 4, _("Merging:"));
3199                 output_commit_title(o, h1);
3200                 output_commit_title(o, h2);
3201         }
3202
3203         if (!ca) {
3204                 ca = get_merge_bases(h1, h2);
3205                 ca = reverse_commit_list(ca);
3206         }
3207
3208         if (show(o, 5)) {
3209                 unsigned cnt = commit_list_count(ca);
3210
3211                 output(o, 5, Q_("found %u common ancestor:",
3212                                 "found %u common ancestors:", cnt), cnt);
3213                 for (iter = ca; iter; iter = iter->next)
3214                         output_commit_title(o, iter->item);
3215         }
3216
3217         merged_common_ancestors = pop_commit(&ca);
3218         if (merged_common_ancestors == NULL) {
3219                 /* if there is no common ancestor, use an empty tree */
3220                 struct tree *tree;
3221
3222                 tree = lookup_tree(the_hash_algo->empty_tree);
3223                 merged_common_ancestors = make_virtual_commit(tree, "ancestor");
3224         }
3225
3226         for (iter = ca; iter; iter = iter->next) {
3227                 const char *saved_b1, *saved_b2;
3228                 o->call_depth++;
3229                 /*
3230                  * When the merge fails, the result contains files
3231                  * with conflict markers. The cleanness flag is
3232                  * ignored (unless indicating an error), it was never
3233                  * actually used, as result of merge_trees has always
3234                  * overwritten it: the committed "conflicts" were
3235                  * already resolved.
3236                  */
3237                 discard_cache();
3238                 saved_b1 = o->branch1;
3239                 saved_b2 = o->branch2;
3240                 o->branch1 = "Temporary merge branch 1";
3241                 o->branch2 = "Temporary merge branch 2";
3242                 if (merge_recursive(o, merged_common_ancestors, iter->item,
3243                                     NULL, &merged_common_ancestors) < 0)
3244                         return -1;
3245                 o->branch1 = saved_b1;
3246                 o->branch2 = saved_b2;
3247                 o->call_depth--;
3248
3249                 if (!merged_common_ancestors)
3250                         return err(o, _("merge returned no commit"));
3251         }
3252
3253         discard_cache();
3254         if (!o->call_depth)
3255                 read_cache();
3256
3257         o->ancestor = "merged common ancestors";
3258         clean = merge_trees(o, get_commit_tree(h1), get_commit_tree(h2),
3259                             get_commit_tree(merged_common_ancestors),
3260                             &mrtree);
3261         if (clean < 0) {
3262                 flush_output(o);
3263                 return clean;
3264         }
3265
3266         if (o->call_depth) {
3267                 *result = make_virtual_commit(mrtree, "merged tree");
3268                 commit_list_insert(h1, &(*result)->parents);
3269                 commit_list_insert(h2, &(*result)->parents->next);
3270         }
3271         flush_output(o);
3272         if (!o->call_depth && o->buffer_output < 2)
3273                 strbuf_release(&o->obuf);
3274         if (show(o, 2))
3275                 diff_warn_rename_limit("merge.renamelimit",
3276                                        o->needed_rename_limit, 0);
3277         return clean;
3278 }
3279
3280 static struct commit *get_ref(const struct object_id *oid, const char *name)
3281 {
3282         struct object *object;
3283
3284         object = deref_tag(parse_object(oid), name, strlen(name));
3285         if (!object)
3286                 return NULL;
3287         if (object->type == OBJ_TREE)
3288                 return make_virtual_commit((struct tree*)object, name);
3289         if (object->type != OBJ_COMMIT)
3290                 return NULL;
3291         if (parse_commit((struct commit *)object))
3292                 return NULL;
3293         return (struct commit *)object;
3294 }
3295
3296 int merge_recursive_generic(struct merge_options *o,
3297                             const struct object_id *head,
3298                             const struct object_id *merge,
3299                             int num_base_list,
3300                             const struct object_id **base_list,
3301                             struct commit **result)
3302 {
3303         int clean;
3304         struct lock_file lock = LOCK_INIT;
3305         struct commit *head_commit = get_ref(head, o->branch1);
3306         struct commit *next_commit = get_ref(merge, o->branch2);
3307         struct commit_list *ca = NULL;
3308
3309         if (base_list) {
3310                 int i;
3311                 for (i = 0; i < num_base_list; ++i) {
3312                         struct commit *base;
3313                         if (!(base = get_ref(base_list[i], oid_to_hex(base_list[i]))))
3314                                 return err(o, _("Could not parse object '%s'"),
3315                                         oid_to_hex(base_list[i]));
3316                         commit_list_insert(base, &ca);
3317                 }
3318         }
3319
3320         hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
3321         clean = merge_recursive(o, head_commit, next_commit, ca,
3322                         result);
3323         if (clean < 0) {
3324                 rollback_lock_file(&lock);
3325                 return clean;
3326         }
3327
3328         if (write_locked_index(&the_index, &lock,
3329                                COMMIT_LOCK | SKIP_IF_UNCHANGED))
3330                 return err(o, _("Unable to write index."));
3331
3332         return clean ? 0 : 1;
3333 }
3334
3335 static void merge_recursive_config(struct merge_options *o)
3336 {
3337         char *value = NULL;
3338         git_config_get_int("merge.verbosity", &o->verbosity);
3339         git_config_get_int("diff.renamelimit", &o->diff_rename_limit);
3340         git_config_get_int("merge.renamelimit", &o->merge_rename_limit);
3341         if (!git_config_get_string("diff.renames", &value)) {
3342                 o->diff_detect_rename = git_config_rename("diff.renames", value);
3343                 free(value);
3344         }
3345         if (!git_config_get_string("merge.renames", &value)) {
3346                 o->merge_detect_rename = git_config_rename("merge.renames", value);
3347                 free(value);
3348         }
3349         git_config(git_xmerge_config, NULL);
3350 }
3351
3352 void init_merge_options(struct merge_options *o)
3353 {
3354         const char *merge_verbosity;
3355         memset(o, 0, sizeof(struct merge_options));
3356         o->verbosity = 2;
3357         o->buffer_output = 1;
3358         o->diff_rename_limit = -1;
3359         o->merge_rename_limit = -1;
3360         o->renormalize = 0;
3361         o->diff_detect_rename = -1;
3362         o->merge_detect_rename = -1;
3363         merge_recursive_config(o);
3364         merge_verbosity = getenv("GIT_MERGE_VERBOSITY");
3365         if (merge_verbosity)
3366                 o->verbosity = strtol(merge_verbosity, NULL, 10);
3367         if (o->verbosity >= 5)
3368                 o->buffer_output = 0;
3369         strbuf_init(&o->obuf, 0);
3370         string_list_init(&o->df_conflict_file_set, 1);
3371 }
3372
3373 int parse_merge_opt(struct merge_options *o, const char *s)
3374 {
3375         const char *arg;
3376
3377         if (!s || !*s)
3378                 return -1;
3379         if (!strcmp(s, "ours"))
3380                 o->recursive_variant = MERGE_RECURSIVE_OURS;
3381         else if (!strcmp(s, "theirs"))
3382                 o->recursive_variant = MERGE_RECURSIVE_THEIRS;
3383         else if (!strcmp(s, "subtree"))
3384                 o->subtree_shift = "";
3385         else if (skip_prefix(s, "subtree=", &arg))
3386                 o->subtree_shift = arg;
3387         else if (!strcmp(s, "patience"))
3388                 o->xdl_opts = DIFF_WITH_ALG(o, PATIENCE_DIFF);
3389         else if (!strcmp(s, "histogram"))
3390                 o->xdl_opts = DIFF_WITH_ALG(o, HISTOGRAM_DIFF);
3391         else if (skip_prefix(s, "diff-algorithm=", &arg)) {
3392                 long value = parse_algorithm_value(arg);
3393                 if (value < 0)
3394                         return -1;
3395                 /* clear out previous settings */
3396                 DIFF_XDL_CLR(o, NEED_MINIMAL);
3397                 o->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3398                 o->xdl_opts |= value;
3399         }
3400         else if (!strcmp(s, "ignore-space-change"))
3401                 DIFF_XDL_SET(o, IGNORE_WHITESPACE_CHANGE);
3402         else if (!strcmp(s, "ignore-all-space"))
3403                 DIFF_XDL_SET(o, IGNORE_WHITESPACE);
3404         else if (!strcmp(s, "ignore-space-at-eol"))
3405                 DIFF_XDL_SET(o, IGNORE_WHITESPACE_AT_EOL);
3406         else if (!strcmp(s, "ignore-cr-at-eol"))
3407                 DIFF_XDL_SET(o, IGNORE_CR_AT_EOL);
3408         else if (!strcmp(s, "renormalize"))
3409                 o->renormalize = 1;
3410         else if (!strcmp(s, "no-renormalize"))
3411                 o->renormalize = 0;
3412         else if (!strcmp(s, "no-renames"))
3413                 o->merge_detect_rename = 0;
3414         else if (!strcmp(s, "find-renames")) {
3415                 o->merge_detect_rename = 1;
3416                 o->rename_score = 0;
3417         }
3418         else if (skip_prefix(s, "find-renames=", &arg) ||
3419                  skip_prefix(s, "rename-threshold=", &arg)) {
3420                 if ((o->rename_score = parse_rename_score(&arg)) == -1 || *arg != 0)
3421                         return -1;
3422                 o->merge_detect_rename = 1;
3423         }
3424         else
3425                 return -1;
3426         return 0;
3427 }