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