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