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