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