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