]> git.ipfire.org Git - thirdparty/git.git/blame - merge-recursive.c
Merge branch 'en/ort-finalize-after-0-merges-fix'
[thirdparty/git.git] / merge-recursive.c
CommitLineData
9047ebbc
MV
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"
4615a8cb
EN
7#include "merge-recursive.h"
8
1c4b6604 9#include "advice.h"
4615a8cb
EN
10#include "alloc.h"
11#include "attr.h"
9047ebbc 12#include "blob.h"
4615a8cb
EN
13#include "cache-tree.h"
14#include "commit.h"
15#include "commit-reach.h"
16#include "config.h"
9047ebbc
MV
17#include "diff.h"
18#include "diffcore.h"
4615a8cb 19#include "dir.h"
32a8f510 20#include "environment.h"
f394e093 21#include "gettext.h"
41771fa4 22#include "hex.h"
4615a8cb
EN
23#include "ll-merge.h"
24#include "lockfile.h"
87bed179 25#include "object-file.h"
dabab1d6 26#include "object-name.h"
4615a8cb
EN
27#include "object-store.h"
28#include "repository.h"
29#include "revision.h"
30#include "string-list.h"
10a0d6ae 31#include "submodule-config.h"
4615a8cb 32#include "submodule.h"
9047ebbc 33#include "tag.h"
4615a8cb 34#include "tree-walk.h"
9047ebbc 35#include "unpack-trees.h"
d5ebb50d 36#include "wrapper.h"
9047ebbc 37#include "xdiff-interface.h"
9047ebbc 38
5bf7e577
EN
39struct merge_options_internal {
40 int call_depth;
41 int needed_rename_limit;
42 struct hashmap current_file_dir_set;
43 struct string_list df_conflict_file_set;
44 struct unpack_trees_options unpack_opts;
45 struct index_state orig_index;
46};
9047ebbc 47
fc65b00d
KW
48struct path_hashmap_entry {
49 struct hashmap_entry e;
50 char path[FLEX_ARRAY];
51};
52
5cf88fd8 53static int path_hashmap_cmp(const void *cmp_data UNUSED,
939af16e
EW
54 const struct hashmap_entry *eptr,
55 const struct hashmap_entry *entry_or_key,
fc65b00d
KW
56 const void *keydata)
57{
939af16e 58 const struct path_hashmap_entry *a, *b;
fc65b00d
KW
59 const char *key = keydata;
60
939af16e
EW
61 a = container_of(eptr, const struct path_hashmap_entry, e);
62 b = container_of(entry_or_key, const struct path_hashmap_entry, e);
63
2dee7e61 64 return fspathcmp(a->path, key ? key : b->path);
fc65b00d
KW
65}
66
7c0a6c8e
EN
67/*
68 * For dir_rename_entry, directory names are stored as a full path from the
69 * toplevel of the repository and do not include a trailing '/'. Also:
70 *
71 * dir: original name of directory being renamed
72 * non_unique_new_dir: if true, could not determine new_dir
73 * new_dir: final name of directory being renamed
74 * possible_new_dirs: temporary used to help determine new_dir; see comments
75 * in get_directory_renames() for details
76 */
77struct dir_rename_entry {
5efabc7e 78 struct hashmap_entry ent;
7c0a6c8e
EN
79 char *dir;
80 unsigned non_unique_new_dir:1;
81 struct strbuf new_dir;
82 struct string_list possible_new_dirs;
83};
84
7fe40b88
EN
85static struct dir_rename_entry *dir_rename_find_entry(struct hashmap *hashmap,
86 char *dir)
87{
88 struct dir_rename_entry key;
89
afe8a907 90 if (!dir)
7fe40b88 91 return NULL;
d22245a2 92 hashmap_entry_init(&key.ent, strhash(dir));
7fe40b88 93 key.dir = dir;
404ab78e 94 return hashmap_get_entry(hashmap, &key, ent, NULL);
7fe40b88
EN
95}
96
5cf88fd8 97static int dir_rename_cmp(const void *cmp_data UNUSED,
939af16e
EW
98 const struct hashmap_entry *eptr,
99 const struct hashmap_entry *entry_or_key,
5cf88fd8 100 const void *keydata UNUSED)
7fe40b88 101{
939af16e
EW
102 const struct dir_rename_entry *e1, *e2;
103
104 e1 = container_of(eptr, const struct dir_rename_entry, ent);
105 e2 = container_of(entry_or_key, const struct dir_rename_entry, ent);
7fe40b88
EN
106
107 return strcmp(e1->dir, e2->dir);
108}
109
110static void dir_rename_init(struct hashmap *map)
111{
112 hashmap_init(map, dir_rename_cmp, NULL, 0);
113}
114
115static void dir_rename_entry_init(struct dir_rename_entry *entry,
116 char *directory)
117{
d22245a2 118 hashmap_entry_init(&entry->ent, strhash(directory));
7fe40b88
EN
119 entry->dir = directory;
120 entry->non_unique_new_dir = 0;
121 strbuf_init(&entry->new_dir, 0);
bc40dfb1 122 string_list_init_nodup(&entry->possible_new_dirs);
7fe40b88
EN
123}
124
7c0a6c8e 125struct collision_entry {
5efabc7e 126 struct hashmap_entry ent;
7c0a6c8e
EN
127 char *target_file;
128 struct string_list source_files;
129 unsigned reported_already:1;
130};
131
e95ab70a
EN
132static struct collision_entry *collision_find_entry(struct hashmap *hashmap,
133 char *target_file)
134{
135 struct collision_entry key;
136
d22245a2 137 hashmap_entry_init(&key.ent, strhash(target_file));
e95ab70a 138 key.target_file = target_file;
404ab78e 139 return hashmap_get_entry(hashmap, &key, ent, NULL);
e95ab70a
EN
140}
141
5cf88fd8 142static int collision_cmp(const void *cmp_data UNUSED,
939af16e
EW
143 const struct hashmap_entry *eptr,
144 const struct hashmap_entry *entry_or_key,
5cf88fd8 145 const void *keydata UNUSED)
e95ab70a 146{
939af16e
EW
147 const struct collision_entry *e1, *e2;
148
149 e1 = container_of(eptr, const struct collision_entry, ent);
150 e2 = container_of(entry_or_key, const struct collision_entry, ent);
151
e95ab70a
EN
152 return strcmp(e1->target_file, e2->target_file);
153}
154
155static void collision_init(struct hashmap *map)
156{
939af16e 157 hashmap_init(map, collision_cmp, NULL, 0);
e95ab70a
EN
158}
159
259ccb6c 160static void flush_output(struct merge_options *opt)
bc9204d4 161{
259ccb6c
EN
162 if (opt->buffer_output < 2 && opt->obuf.len) {
163 fputs(opt->obuf.buf, stdout);
164 strbuf_reset(&opt->obuf);
bc9204d4
JS
165 }
166}
167
48ca53ca 168__attribute__((format (printf, 2, 3)))
259ccb6c 169static int err(struct merge_options *opt, const char *err, ...)
bc9204d4
JS
170{
171 va_list params;
172
259ccb6c
EN
173 if (opt->buffer_output < 2)
174 flush_output(opt);
f1e2426b 175 else {
259ccb6c
EN
176 strbuf_complete(&opt->obuf, '\n');
177 strbuf_addstr(&opt->obuf, "error: ");
f1e2426b 178 }
bc9204d4 179 va_start(params, err);
259ccb6c 180 strbuf_vaddf(&opt->obuf, err, params);
bc9204d4 181 va_end(params);
259ccb6c
EN
182 if (opt->buffer_output > 1)
183 strbuf_addch(&opt->obuf, '\n');
f1e2426b 184 else {
259ccb6c
EN
185 error("%s", opt->obuf.buf);
186 strbuf_reset(&opt->obuf);
f1e2426b 187 }
bc9204d4
JS
188
189 return -1;
190}
191
d7cf3a96
NTND
192static struct tree *shift_tree_object(struct repository *repo,
193 struct tree *one, struct tree *two,
85e51b78 194 const char *subtree_shift)
9047ebbc 195{
f2fd0760 196 struct object_id shifted;
9047ebbc 197
85e51b78 198 if (!*subtree_shift) {
90d34051 199 shift_tree(repo, &one->object.oid, &two->object.oid, &shifted, 0);
85e51b78 200 } else {
90d34051 201 shift_tree_by(repo, &one->object.oid, &two->object.oid, &shifted,
85e51b78
JH
202 subtree_shift);
203 }
4a7e27e9 204 if (oideq(&two->object.oid, &shifted))
9047ebbc 205 return two;
d7cf3a96 206 return lookup_tree(repo, &shifted);
9047ebbc
MV
207}
208
a133c40b
NTND
209static inline void set_commit_tree(struct commit *c, struct tree *t)
210{
211 c->maybe_tree = t;
212}
213
d7cf3a96
NTND
214static struct commit *make_virtual_commit(struct repository *repo,
215 struct tree *tree,
216 const char *comment)
9047ebbc 217{
d7cf3a96 218 struct commit *commit = alloc_commit_node(repo);
ae8e4c9c 219
a2571653 220 set_merge_remote_desc(commit, comment, (struct object *)commit);
a133c40b 221 set_commit_tree(commit, tree);
9047ebbc
MV
222 commit->object.parsed = 1;
223 return commit;
224}
225
25c39363
EN
226enum rename_type {
227 RENAME_NORMAL = 0,
5455c338 228 RENAME_VIA_DIR,
7f867165 229 RENAME_ADD,
25c39363 230 RENAME_DELETE,
4f66dade 231 RENAME_ONE_FILE_TO_ONE,
461f5041
EN
232 RENAME_ONE_FILE_TO_TWO,
233 RENAME_TWO_FILES_TO_ONE
25c39363
EN
234};
235
9047ebbc
MV
236/*
237 * Since we want to write the index eventually, we cannot reuse the index
238 * for these (temporary) data.
239 */
9cba13ca 240struct stage_data {
8daec1df 241 struct diff_filespec stages[4]; /* mostly for oid & mode; maybe path */
4f66dade 242 struct rename_conflict_info *rename_conflict_info;
9047ebbc
MV
243 unsigned processed:1;
244};
245
967d6be7 246struct rename {
6d169fd3 247 unsigned processed:1;
967d6be7 248 struct diff_filepair *pair;
c336ab85 249 const char *branch; /* branch that the rename occurred on */
6d169fd3
EN
250 /*
251 * If directory rename detection affected this rename, what was its
252 * original type ('A' or 'R') and it's original destination before
253 * the directory rename (otherwise, '\0' and NULL for these two vars).
254 */
255 char dir_rename_original_type;
256 char *dir_rename_original_dest;
967d6be7
EN
257 /*
258 * Purpose of src_entry and dst_entry:
259 *
260 * If 'before' is renamed to 'after' then src_entry will contain
261 * the versions of 'before' from the merge_base, HEAD, and MERGE in
262 * stages 1, 2, and 3; dst_entry will contain the respective
263 * versions of 'after' in corresponding locations. Thus, we have a
264 * total of six modes and oids, though some will be null. (Stage 0
265 * is ignored; we're interested in handling conflicts.)
266 *
267 * Since we don't turn on break-rewrites by default, neither
268 * src_entry nor dst_entry can have all three of their stages have
269 * non-null oids, meaning at most four of the six will be non-null.
270 * Also, since this is a rename, both src_entry and dst_entry will
271 * have at least one non-null oid, meaning at least two will be
272 * non-null. Of the six oids, a typical rename will have three be
273 * non-null. Only two implies a rename/delete, and four implies a
274 * rename/add.
275 */
276 struct stage_data *src_entry;
277 struct stage_data *dst_entry;
967d6be7
EN
278};
279
280struct rename_conflict_info {
281 enum rename_type rename_type;
e9cd1b5c
EN
282 struct rename *ren1;
283 struct rename *ren2;
967d6be7
EN
284};
285
4f66dade 286static inline void setup_rename_conflict_info(enum rename_type rename_type,
e9cd1b5c
EN
287 struct merge_options *opt,
288 struct rename *ren1,
c336ab85 289 struct rename *ren2)
25c39363 290{
4f445453
EN
291 struct rename_conflict_info *ci;
292
293 /*
294 * When we have two renames involved, it's easiest to get the
295 * correct things into stage 2 and 3, and to make sure that the
296 * content merge puts HEAD before the other branch if we just
259ccb6c 297 * ensure that branch1 == opt->branch1. So, simply flip arguments
4f445453
EN
298 * around if we don't have that.
299 */
c336ab85
EN
300 if (ren2 && ren1->branch != opt->branch1) {
301 setup_rename_conflict_info(rename_type, opt, ren2, ren1);
4f445453
EN
302 return;
303 }
304
ca56dadb 305 CALLOC_ARRAY(ci, 1);
25c39363 306 ci->rename_type = rename_type;
e9cd1b5c
EN
307 ci->ren1 = ren1;
308 ci->ren2 = ren2;
25c39363 309
e9cd1b5c
EN
310 ci->ren1->dst_entry->processed = 0;
311 ci->ren1->dst_entry->rename_conflict_info = ci;
e9cd1b5c
EN
312 if (ren2) {
313 ci->ren2->dst_entry->rename_conflict_info = ci;
25c39363
EN
314 }
315}
316
259ccb6c 317static int show(struct merge_options *opt, int v)
9047ebbc 318{
5bf7e577
EN
319 return (!opt->priv->call_depth && opt->verbosity >= v) ||
320 opt->verbosity >= 5;
9047ebbc
MV
321}
322
28bea9e5 323__attribute__((format (printf, 3, 4)))
259ccb6c 324static void output(struct merge_options *opt, int v, const char *fmt, ...)
9047ebbc 325{
9047ebbc
MV
326 va_list ap;
327
259ccb6c 328 if (!show(opt, v))
9047ebbc
MV
329 return;
330
5bf7e577 331 strbuf_addchars(&opt->obuf, ' ', opt->priv->call_depth * 2);
9047ebbc
MV
332
333 va_start(ap, fmt);
259ccb6c 334 strbuf_vaddf(&opt->obuf, fmt, ap);
9047ebbc
MV
335 va_end(ap);
336
259ccb6c
EN
337 strbuf_addch(&opt->obuf, '\n');
338 if (!opt->buffer_output)
339 flush_output(opt);
9047ebbc
MV
340}
341
155b517d
JT
342static void repo_output_commit_title(struct merge_options *opt,
343 struct repository *repo,
344 struct commit *commit)
9047ebbc 345{
e2e5ac23
NTND
346 struct merge_remote_desc *desc;
347
5bf7e577 348 strbuf_addchars(&opt->obuf, ' ', opt->priv->call_depth * 2);
e2e5ac23
NTND
349 desc = merge_remote_util(commit);
350 if (desc)
259ccb6c 351 strbuf_addf(&opt->obuf, "virtual %s\n", desc->name);
9047ebbc 352 else {
155b517d
JT
353 strbuf_repo_add_unique_abbrev(&opt->obuf, repo,
354 &commit->object.oid,
355 DEFAULT_ABBREV);
259ccb6c 356 strbuf_addch(&opt->obuf, ' ');
155b517d 357 if (repo_parse_commit(repo, commit) != 0)
259ccb6c 358 strbuf_addstr(&opt->obuf, _("(bad commit)\n"));
9047ebbc 359 else {
49b7120e 360 const char *title;
155b517d 361 const char *msg = repo_get_commit_buffer(repo, commit, NULL);
bc6b8fc1 362 int len = find_commit_subject(msg, &title);
49b7120e 363 if (len)
259ccb6c 364 strbuf_addf(&opt->obuf, "%.*s\n", len, title);
155b517d 365 repo_unuse_commit_buffer(repo, commit, msg);
9047ebbc
MV
366 }
367 }
259ccb6c 368 flush_output(opt);
9047ebbc
MV
369}
370
155b517d
JT
371static void output_commit_title(struct merge_options *opt, struct commit *commit)
372{
373 repo_output_commit_title(opt, the_repository, commit);
374}
375
259ccb6c 376static int add_cacheinfo(struct merge_options *opt,
8daec1df 377 const struct diff_filespec *blob,
d90e759f 378 const char *path, int stage, int refresh, int options)
9047ebbc 379{
259ccb6c 380 struct index_state *istate = opt->repo->index;
9047ebbc 381 struct cache_entry *ce;
1335d76e
JH
382 int ret;
383
8daec1df 384 ce = make_cache_entry(istate, blob->mode, &blob->oid, path, stage, 0);
9047ebbc 385 if (!ce)
259ccb6c 386 return err(opt, _("add_cacheinfo failed for path '%s'; merge aborting."), path);
1335d76e 387
0d6caa2d 388 ret = add_index_entry(istate, ce, options);
1335d76e
JH
389 if (refresh) {
390 struct cache_entry *nce;
391
0d6caa2d
NTND
392 nce = refresh_cache_entry(istate, ce,
393 CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING);
55e9f0e5 394 if (!nce)
259ccb6c 395 return err(opt, _("add_cacheinfo failed to refresh for path '%s'; merge aborting."), path);
1335d76e 396 if (nce != ce)
0d6caa2d 397 ret = add_index_entry(istate, nce, options);
1335d76e
JH
398 }
399 return ret;
9047ebbc
MV
400}
401
7c0a6c8e
EN
402static inline int merge_detect_rename(struct merge_options *opt)
403{
8599ab45 404 return (opt->detect_renames >= 0) ? opt->detect_renames : 1;
7c0a6c8e
EN
405}
406
9047ebbc
MV
407static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
408{
409 parse_tree(tree);
410 init_tree_desc(desc, tree->buffer, tree->size);
411}
412
259ccb6c 413static int unpack_trees_start(struct merge_options *opt,
3f1c1c36
EN
414 struct tree *common,
415 struct tree *head,
416 struct tree *merge)
9047ebbc
MV
417{
418 int rc;
419 struct tree_desc t[3];
6269f8ea 420 struct index_state tmp_index = INDEX_STATE_INIT(opt->repo);
9047ebbc 421
5bf7e577
EN
422 memset(&opt->priv->unpack_opts, 0, sizeof(opt->priv->unpack_opts));
423 if (opt->priv->call_depth)
424 opt->priv->unpack_opts.index_only = 1;
491a7575 425 else {
5bf7e577 426 opt->priv->unpack_opts.update = 1;
491a7575 427 /* FIXME: should only do this if !overwrite_ignore */
04988c8d 428 opt->priv->unpack_opts.preserve_ignored = 0;
491a7575 429 }
5bf7e577
EN
430 opt->priv->unpack_opts.merge = 1;
431 opt->priv->unpack_opts.head_idx = 2;
432 opt->priv->unpack_opts.fn = threeway_merge;
433 opt->priv->unpack_opts.src_index = opt->repo->index;
434 opt->priv->unpack_opts.dst_index = &tmp_index;
435 opt->priv->unpack_opts.aggressive = !merge_detect_rename(opt);
436 setup_unpack_trees_porcelain(&opt->priv->unpack_opts, "merge");
9047ebbc
MV
437
438 init_tree_desc_from_tree(t+0, common);
439 init_tree_desc_from_tree(t+1, head);
440 init_tree_desc_from_tree(t+2, merge);
441
5bf7e577 442 rc = unpack_trees(3, t, &opt->priv->unpack_opts);
259ccb6c 443 cache_tree_free(&opt->repo->index->cache_tree);
a35edc84 444
64b1abe9 445 /*
5bf7e577
EN
446 * Update opt->repo->index to match the new results, AFTER saving a
447 * copy in opt->priv->orig_index. Update src_index to point to the
448 * saved copy. (verify_uptodate() checks src_index, and the original
449 * index is the one that had the necessary modification timestamps.)
64b1abe9 450 */
5bf7e577 451 opt->priv->orig_index = *opt->repo->index;
259ccb6c 452 *opt->repo->index = tmp_index;
5bf7e577 453 opt->priv->unpack_opts.src_index = &opt->priv->orig_index;
a35edc84 454
9047ebbc
MV
455 return rc;
456}
457
259ccb6c 458static void unpack_trees_finish(struct merge_options *opt)
3f1c1c36 459{
5bf7e577
EN
460 discard_index(&opt->priv->orig_index);
461 clear_unpack_trees_porcelain(&opt->priv->unpack_opts);
9047ebbc
MV
462}
463
5cf88fd8 464static int save_files_dirs(const struct object_id *oid UNUSED,
d90e759f 465 struct strbuf *base, const char *path,
47957485 466 unsigned int mode, void *context)
9047ebbc 467{
fc65b00d 468 struct path_hashmap_entry *entry;
6a0b0b6d 469 int baselen = base->len;
259ccb6c 470 struct merge_options *opt = context;
696ee23c 471
6a0b0b6d 472 strbuf_addstr(base, path);
9047ebbc 473
fc65b00d 474 FLEX_ALLOC_MEM(entry, path, base->buf, base->len);
74318423 475 hashmap_entry_init(&entry->e, fspathhash(entry->path));
5efabc7e 476 hashmap_add(&opt->priv->current_file_dir_set, &entry->e);
9047ebbc 477
6a0b0b6d 478 strbuf_setlen(base, baselen);
d3bee161 479 return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
9047ebbc
MV
480}
481
259ccb6c 482static void get_files_dirs(struct merge_options *opt, struct tree *tree)
9047ebbc 483{
f0096c06 484 struct pathspec match_all;
9a087274 485 memset(&match_all, 0, sizeof(match_all));
47957485
ÆAB
486 read_tree(opt->repo, tree,
487 &match_all, save_files_dirs, opt);
9047ebbc
MV
488}
489
34e7771b
NTND
490static int get_tree_entry_if_blob(struct repository *r,
491 const struct object_id *tree,
5b047ac0 492 const char *path,
8daec1df 493 struct diff_filespec *dfs)
5b047ac0
EN
494{
495 int ret;
496
34e7771b 497 ret = get_tree_entry(r, tree, path, &dfs->oid, &dfs->mode);
8daec1df 498 if (S_ISDIR(dfs->mode)) {
14228447 499 oidcpy(&dfs->oid, null_oid());
8daec1df 500 dfs->mode = 0;
5b047ac0
EN
501 }
502 return ret;
503}
504
9047ebbc
MV
505/*
506 * Returns an index_entry instance which doesn't have to correspond to
507 * a real cache entry in Git's index.
508 */
34e7771b
NTND
509static struct stage_data *insert_stage_data(struct repository *r,
510 const char *path,
9047ebbc
MV
511 struct tree *o, struct tree *a, struct tree *b,
512 struct string_list *entries)
513{
514 struct string_list_item *item;
515 struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
34e7771b
NTND
516 get_tree_entry_if_blob(r, &o->object.oid, path, &e->stages[1]);
517 get_tree_entry_if_blob(r, &a->object.oid, path, &e->stages[2]);
518 get_tree_entry_if_blob(r, &b->object.oid, path, &e->stages[3]);
78a395d3 519 item = string_list_insert(entries, path);
9047ebbc
MV
520 item->util = e;
521 return e;
522}
523
524/*
525 * Create a dictionary mapping file names to stage_data objects. The
526 * dictionary contains one entry for every path with a non-zero stage entry.
527 */
0d6caa2d 528static struct string_list *get_unmerged(struct index_state *istate)
9047ebbc 529{
f2605051 530 struct string_list *unmerged = xmalloc(sizeof(struct string_list));
9047ebbc
MV
531 int i;
532
f2605051 533 string_list_init_dup(unmerged);
9047ebbc 534
f7ef64be
DS
535 /* TODO: audit for interaction with sparse-index. */
536 ensure_full_index(istate);
0d6caa2d 537 for (i = 0; i < istate->cache_nr; i++) {
9047ebbc
MV
538 struct string_list_item *item;
539 struct stage_data *e;
0d6caa2d 540 const struct cache_entry *ce = istate->cache[i];
9047ebbc
MV
541 if (!ce_stage(ce))
542 continue;
543
e8c8b713 544 item = string_list_lookup(unmerged, ce->name);
9047ebbc 545 if (!item) {
78a395d3 546 item = string_list_insert(unmerged, ce->name);
9047ebbc
MV
547 item->util = xcalloc(1, sizeof(struct stage_data));
548 }
549 e = item->util;
550 e->stages[ce_stage(ce)].mode = ce->ce_mode;
99d1a986 551 oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid);
9047ebbc
MV
552 }
553
554 return unmerged;
555}
556
fa6ca111 557static int string_list_df_name_compare(const char *one, const char *two)
ef02b317 558{
fa6ca111
NTND
559 int onelen = strlen(one);
560 int twolen = strlen(two);
f0fd4d05
EN
561 /*
562 * Here we only care that entries for D/F conflicts are
563 * adjacent, in particular with the file of the D/F conflict
564 * appearing before files below the corresponding directory.
565 * The order of the rest of the list is irrelevant for us.
ef02b317 566 *
f0fd4d05
EN
567 * To achieve this, we sort with df_name_compare and provide
568 * the mode S_IFDIR so that D/F conflicts will sort correctly.
569 * We use the mode S_IFDIR for everything else for simplicity,
570 * since in other cases any changes in their order due to
571 * sorting cause no problems for us.
572 */
fa6ca111
NTND
573 int cmp = df_name_compare(one, onelen, S_IFDIR,
574 two, twolen, S_IFDIR);
f0fd4d05
EN
575 /*
576 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
577 * that 'foo' comes before 'foo/bar'.
ef02b317 578 */
f0fd4d05
EN
579 if (cmp)
580 return cmp;
581 return onelen - twolen;
582}
583
259ccb6c 584static void record_df_conflict_files(struct merge_options *opt,
70cc3d36 585 struct string_list *entries)
ef02b317 586{
70cc3d36 587 /* If there is a D/F conflict and the file for such a conflict
2d6bad91 588 * currently exists in the working tree, we want to allow it to be
edd2faf5
EN
589 * removed to make room for the corresponding directory if needed.
590 * The files underneath the directories of such D/F conflicts will
591 * be processed before the corresponding file involved in the D/F
592 * conflict. If the D/F directory ends up being removed by the
593 * merge, then we won't have to touch the D/F file. If the D/F
594 * directory needs to be written to the working copy, then the D/F
595 * file will simply be removed (in make_room_for_path()) to make
596 * room for the necessary paths. Note that if both the directory
597 * and the file need to be present, then the D/F file will be
598 * reinstated with a new unique name at the time it is processed.
ef02b317 599 */
af4941d4 600 struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP;
ef02b317 601 const char *last_file = NULL;
c8516500 602 int last_len = 0;
ef02b317
EN
603 int i;
604
0b30e812
EN
605 /*
606 * If we're merging merge-bases, we don't want to bother with
607 * any working directory changes.
608 */
5bf7e577 609 if (opt->priv->call_depth)
0b30e812
EN
610 return;
611
f0fd4d05 612 /* Ensure D/F conflicts are adjacent in the entries list. */
ef02b317 613 for (i = 0; i < entries->nr; i++) {
f701aae0
EN
614 struct string_list_item *next = &entries->items[i];
615 string_list_append(&df_sorted_entries, next->string)->util =
616 next->util;
617 }
fa6ca111
NTND
618 df_sorted_entries.cmp = string_list_df_name_compare;
619 string_list_sort(&df_sorted_entries);
f0fd4d05 620
5bf7e577 621 string_list_clear(&opt->priv->df_conflict_file_set, 1);
f701aae0
EN
622 for (i = 0; i < df_sorted_entries.nr; i++) {
623 const char *path = df_sorted_entries.items[i].string;
ef02b317 624 int len = strlen(path);
f701aae0 625 struct stage_data *e = df_sorted_entries.items[i].util;
ef02b317
EN
626
627 /*
628 * Check if last_file & path correspond to a D/F conflict;
629 * i.e. whether path is last_file+'/'+<something>.
70cc3d36
EN
630 * If so, record that it's okay to remove last_file to make
631 * room for path and friends if needed.
ef02b317
EN
632 */
633 if (last_file &&
634 len > last_len &&
635 memcmp(path, last_file, last_len) == 0 &&
636 path[last_len] == '/') {
5bf7e577 637 string_list_insert(&opt->priv->df_conflict_file_set, last_file);
ef02b317
EN
638 }
639
640 /*
641 * Determine whether path could exist as a file in the
642 * working directory as a possible D/F conflict. This
643 * will only occur when it exists in stage 2 as a
644 * file.
645 */
646 if (S_ISREG(e->stages[2].mode) || S_ISLNK(e->stages[2].mode)) {
647 last_file = path;
648 last_len = len;
ef02b317
EN
649 } else {
650 last_file = NULL;
651 }
652 }
f701aae0 653 string_list_clear(&df_sorted_entries, 0);
ef02b317
EN
654}
655
bc9204d4
JS
656static int update_stages(struct merge_options *opt, const char *path,
657 const struct diff_filespec *o,
650467cf
EN
658 const struct diff_filespec *a,
659 const struct diff_filespec *b)
9047ebbc 660{
f53d3977
EN
661
662 /*
663 * NOTE: It is usually a bad idea to call update_stages on a path
664 * before calling update_file on that same path, since it can
665 * sometimes lead to spurious "refusing to lose untracked file..."
666 * messages from update_file (via make_room_for path via
667 * would_lose_untracked). Instead, reverse the order of the calls
668 * (executing update_file first and then update_stages).
669 */
650467cf
EN
670 int clear = 1;
671 int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK;
9047ebbc 672 if (clear)
0d6caa2d 673 if (remove_file_from_index(opt->repo->index, path))
9047ebbc
MV
674 return -1;
675 if (o)
8daec1df 676 if (add_cacheinfo(opt, o, path, 1, 0, options))
9047ebbc
MV
677 return -1;
678 if (a)
8daec1df 679 if (add_cacheinfo(opt, a, path, 2, 0, options))
9047ebbc
MV
680 return -1;
681 if (b)
8daec1df 682 if (add_cacheinfo(opt, b, path, 3, 0, options))
9047ebbc
MV
683 return -1;
684 return 0;
685}
686
b8ddf164
EN
687static void update_entry(struct stage_data *entry,
688 struct diff_filespec *o,
689 struct diff_filespec *a,
690 struct diff_filespec *b)
2ff739f9 691{
2ff739f9
EN
692 entry->processed = 0;
693 entry->stages[1].mode = o->mode;
694 entry->stages[2].mode = a->mode;
695 entry->stages[3].mode = b->mode;
fd429e98 696 oidcpy(&entry->stages[1].oid, &o->oid);
697 oidcpy(&entry->stages[2].oid, &a->oid);
698 oidcpy(&entry->stages[3].oid, &b->oid);
2ff739f9
EN
699}
700
259ccb6c 701static int remove_file(struct merge_options *opt, int clean,
b7fa51da 702 const char *path, int no_wd)
9047ebbc 703{
5bf7e577
EN
704 int update_cache = opt->priv->call_depth || clean;
705 int update_working_directory = !opt->priv->call_depth && !no_wd;
9047ebbc
MV
706
707 if (update_cache) {
259ccb6c 708 if (remove_file_from_index(opt->repo->index, path))
9047ebbc
MV
709 return -1;
710 }
711 if (update_working_directory) {
ae352c7f
DT
712 if (ignore_case) {
713 struct cache_entry *ce;
259ccb6c 714 ce = index_file_exists(opt->repo->index, path, strlen(path),
0d6caa2d 715 ignore_case);
4cba2b01 716 if (ce && ce_stage(ce) == 0 && strcmp(path, ce->name))
ae352c7f
DT
717 return 0;
718 }
25755e84 719 if (remove_path(path))
9047ebbc 720 return -1;
9047ebbc
MV
721 }
722 return 0;
723}
724
45bc131d
JK
725/* add a string to a strbuf, but converting "/" to "_" */
726static void add_flattened_path(struct strbuf *out, const char *s)
727{
728 size_t i = out->len;
729 strbuf_addstr(out, s);
730 for (; i < out->len; i++)
731 if (out->buf[i] == '/')
732 out->buf[i] = '_';
733}
734
4d7101e2
EN
735static char *unique_path(struct merge_options *opt,
736 const char *path,
737 const char *branch)
9047ebbc 738{
fc65b00d 739 struct path_hashmap_entry *entry;
45bc131d 740 struct strbuf newpath = STRBUF_INIT;
9047ebbc 741 int suffix = 0;
45bc131d
JK
742 size_t base_len;
743
744 strbuf_addf(&newpath, "%s~", path);
745 add_flattened_path(&newpath, branch);
746
747 base_len = newpath.len;
5bf7e577 748 while (hashmap_get_from_hash(&opt->priv->current_file_dir_set,
74318423 749 fspathhash(newpath.buf), newpath.buf) ||
5bf7e577 750 (!opt->priv->call_depth && file_exists(newpath.buf))) {
45bc131d
JK
751 strbuf_setlen(&newpath, base_len);
752 strbuf_addf(&newpath, "_%d", suffix++);
753 }
754
fc65b00d 755 FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len);
74318423 756 hashmap_entry_init(&entry->e, fspathhash(entry->path));
5efabc7e 757 hashmap_add(&opt->priv->current_file_dir_set, &entry->e);
45bc131d 758 return strbuf_detach(&newpath, NULL);
9047ebbc
MV
759}
760
5423d2e7
DT
761/**
762 * Check whether a directory in the index is in the way of an incoming
763 * file. Return 1 if so. If check_working_copy is non-zero, also
764 * check the working directory. If empty_ok is non-zero, also return
765 * 0 in the case where the working-tree dir exists but is empty.
766 */
0d6caa2d
NTND
767static int dir_in_way(struct index_state *istate, const char *path,
768 int check_working_copy, int empty_ok)
f2507b4e 769{
b4600fbe
JK
770 int pos;
771 struct strbuf dirpath = STRBUF_INIT;
f2507b4e
EN
772 struct stat st;
773
b4600fbe
JK
774 strbuf_addstr(&dirpath, path);
775 strbuf_addch(&dirpath, '/');
f2507b4e 776
0d6caa2d 777 pos = index_name_pos(istate, dirpath.buf, dirpath.len);
f2507b4e
EN
778
779 if (pos < 0)
780 pos = -1 - pos;
0d6caa2d
NTND
781 if (pos < istate->cache_nr &&
782 !strncmp(dirpath.buf, istate->cache[pos]->name, dirpath.len)) {
b4600fbe 783 strbuf_release(&dirpath);
f2507b4e
EN
784 return 1;
785 }
786
b4600fbe 787 strbuf_release(&dirpath);
5423d2e7 788 return check_working_copy && !lstat(path, &st) && S_ISDIR(st.st_mode) &&
83e3ad3b
JT
789 !(empty_ok && is_empty_dir(path)) &&
790 !has_symlink_leading_path(path, strlen(path));
f2507b4e
EN
791}
792
1de70dbd
EN
793/*
794 * Returns whether path was tracked in the index before the merge started,
795 * and its oid and mode match the specified values
796 */
259ccb6c 797static int was_tracked_and_matches(struct merge_options *opt, const char *path,
8daec1df 798 const struct diff_filespec *blob)
60c91181 799{
5bf7e577 800 int pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
1de70dbd
EN
801 struct cache_entry *ce;
802
803 if (0 > pos)
804 /* we were not tracking this path before the merge */
805 return 0;
806
807 /* See if the file we were tracking before matches */
5bf7e577 808 ce = opt->priv->orig_index.cache[pos];
763a59e7 809 return (oideq(&ce->oid, &blob->oid) && ce->ce_mode == blob->mode);
1de70dbd
EN
810}
811
a35edc84
EN
812/*
813 * Returns whether path was tracked in the index before the merge started
814 */
259ccb6c 815static int was_tracked(struct merge_options *opt, const char *path)
60c91181 816{
5bf7e577 817 int pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
60c91181 818
f8d83fb6 819 if (0 <= pos)
a35edc84 820 /* we were tracking this path before the merge */
f8d83fb6
JS
821 return 1;
822
aacb82de 823 return 0;
60c91181
JH
824}
825
259ccb6c 826static int would_lose_untracked(struct merge_options *opt, const char *path)
9047ebbc 827{
259ccb6c 828 struct index_state *istate = opt->repo->index;
0d6caa2d 829
a35edc84
EN
830 /*
831 * This may look like it can be simplified to:
259ccb6c 832 * return !was_tracked(opt, path) && file_exists(path)
a35edc84
EN
833 * but it can't. This function needs to know whether path was in
834 * the working tree due to EITHER having been tracked in the index
835 * before the merge OR having been put into the working copy and
836 * index by unpack_trees(). Due to that either-or requirement, we
837 * check the current index instead of the original one.
838 *
839 * Note that we do not need to worry about merge-recursive itself
840 * updating the index after unpack_trees() and before calling this
841 * function, because we strictly require all code paths in
842 * merge-recursive to update the working tree first and the index
843 * second. Doing otherwise would break
844 * update_file()/would_lose_untracked(); see every comment in this
845 * file which mentions "update_stages".
846 */
0d6caa2d 847 int pos = index_name_pos(istate, path, strlen(path));
a35edc84
EN
848
849 if (pos < 0)
850 pos = -1 - pos;
0d6caa2d
NTND
851 while (pos < istate->cache_nr &&
852 !strcmp(path, istate->cache[pos]->name)) {
a35edc84
EN
853 /*
854 * If stage #0, it is definitely tracked.
855 * If it has stage #2 then it was tracked
856 * before this merge started. All other
857 * cases the path was not tracked.
858 */
0d6caa2d 859 switch (ce_stage(istate->cache[pos])) {
a35edc84
EN
860 case 0:
861 case 2:
862 return 0;
863 }
864 pos++;
865 }
866 return file_exists(path);
60c91181
JH
867}
868
259ccb6c 869static int was_dirty(struct merge_options *opt, const char *path)
64b1abe9
EN
870{
871 struct cache_entry *ce;
872 int dirty = 1;
873
5bf7e577 874 if (opt->priv->call_depth || !was_tracked(opt, path))
64b1abe9
EN
875 return !dirty;
876
5bf7e577 877 ce = index_file_exists(opt->priv->unpack_opts.src_index,
277292d5 878 path, strlen(path), ignore_case);
5bf7e577 879 dirty = verify_uptodate(ce, &opt->priv->unpack_opts) != 0;
64b1abe9 880 return dirty;
60c91181
JH
881}
882
259ccb6c 883static int make_room_for_path(struct merge_options *opt, const char *path)
9047ebbc 884{
ed0148a5 885 int status, i;
55653a68 886 const char *msg = _("failed to create path '%s'%s");
9047ebbc 887
ed0148a5 888 /* Unlink any D/F conflict files that are in the way */
5bf7e577
EN
889 for (i = 0; i < opt->priv->df_conflict_file_set.nr; i++) {
890 const char *df_path = opt->priv->df_conflict_file_set.items[i].string;
ed0148a5
EN
891 size_t pathlen = strlen(path);
892 size_t df_pathlen = strlen(df_path);
893 if (df_pathlen < pathlen &&
894 path[df_pathlen] == '/' &&
895 strncmp(path, df_path, df_pathlen) == 0) {
259ccb6c 896 output(opt, 3,
55653a68 897 _("Removing %s to make room for subdirectory\n"),
ed0148a5
EN
898 df_path);
899 unlink(df_path);
5bf7e577 900 unsorted_string_list_delete_item(&opt->priv->df_conflict_file_set,
ed0148a5
EN
901 i, 0);
902 break;
903 }
904 }
905
906 /* Make sure leading directories are created */
9047ebbc
MV
907 status = safe_create_leading_directories_const(path);
908 if (status) {
6003303a 909 if (status == SCLD_EXISTS)
9047ebbc 910 /* something else exists */
259ccb6c
EN
911 return err(opt, msg, path, _(": perhaps a D/F conflict?"));
912 return err(opt, msg, path, "");
9047ebbc
MV
913 }
914
60c91181
JH
915 /*
916 * Do not unlink a file in the work tree if we are not
917 * tracking it.
918 */
259ccb6c
EN
919 if (would_lose_untracked(opt, path))
920 return err(opt, _("refusing to lose untracked file at '%s'"),
d90e759f 921 path);
60c91181 922
9047ebbc
MV
923 /* Successful unlink is good.. */
924 if (!unlink(path))
925 return 0;
926 /* .. and so is no existing file */
927 if (errno == ENOENT)
928 return 0;
929 /* .. but not some other error (who really cares what?) */
259ccb6c 930 return err(opt, msg, path, _(": perhaps a D/F conflict?"));
9047ebbc
MV
931}
932
259ccb6c 933static int update_file_flags(struct merge_options *opt,
8daec1df 934 const struct diff_filespec *contents,
75456f96
JS
935 const char *path,
936 int update_cache,
937 int update_wd)
9047ebbc 938{
6003303a
JS
939 int ret = 0;
940
5bf7e577 941 if (opt->priv->call_depth)
9047ebbc
MV
942 update_wd = 0;
943
944 if (update_wd) {
945 enum object_type type;
946 void *buf;
947 unsigned long size;
948
8daec1df 949 if (S_ISGITLINK(contents->mode)) {
0c44c943
JH
950 /*
951 * We may later decide to recursively descend into
952 * the submodule directory and update its index
953 * and/or work tree, but we do not do that now.
954 */
68d03e4a 955 update_wd = 0;
0c44c943 956 goto update_index;
68d03e4a 957 }
9047ebbc 958
bc726bd0
ÆAB
959 buf = repo_read_object_file(the_repository, &contents->oid,
960 &type, &size);
f836bf39
EN
961 if (!buf) {
962 ret = err(opt, _("cannot read object %s '%s'"),
963 oid_to_hex(&contents->oid), path);
964 goto free_buf;
965 }
6003303a 966 if (type != OBJ_BLOB) {
8daec1df
EN
967 ret = err(opt, _("blob expected for %s '%s'"),
968 oid_to_hex(&contents->oid), path);
6003303a
JS
969 goto free_buf;
970 }
8daec1df 971 if (S_ISREG(contents->mode)) {
f285a2d7 972 struct strbuf strbuf = STRBUF_INIT;
4d7101e2 973 if (convert_to_working_tree(opt->repo->index,
ab90ecae 974 path, buf, size, &strbuf, NULL)) {
9047ebbc
MV
975 free(buf);
976 size = strbuf.len;
977 buf = strbuf_detach(&strbuf, NULL);
978 }
979 }
980
259ccb6c 981 if (make_room_for_path(opt, path) < 0) {
9047ebbc 982 update_wd = 0;
75456f96 983 goto free_buf;
9047ebbc 984 }
8daec1df
EN
985 if (S_ISREG(contents->mode) ||
986 (!has_symlinks && S_ISLNK(contents->mode))) {
9047ebbc 987 int fd;
8daec1df
EN
988 int mode = (contents->mode & 0100 ? 0777 : 0666);
989
9047ebbc 990 fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
6003303a 991 if (fd < 0) {
259ccb6c 992 ret = err(opt, _("failed to open '%s': %s"),
bc9204d4 993 path, strerror(errno));
6003303a
JS
994 goto free_buf;
995 }
f633ea2c 996 write_in_full(fd, buf, size);
9047ebbc 997 close(fd);
8daec1df 998 } else if (S_ISLNK(contents->mode)) {
9047ebbc
MV
999 char *lnk = xmemdupz(buf, size);
1000 safe_create_leading_directories_const(path);
1001 unlink(path);
304dcf26 1002 if (symlink(lnk, path))
259ccb6c 1003 ret = err(opt, _("failed to symlink '%s': %s"),
d90e759f 1004 path, strerror(errno));
9047ebbc
MV
1005 free(lnk);
1006 } else
259ccb6c 1007 ret = err(opt,
bc9204d4 1008 _("do not know what to do with %06o %s '%s'"),
8daec1df 1009 contents->mode, oid_to_hex(&contents->oid), path);
93665365 1010 free_buf:
9047ebbc
MV
1011 free(buf);
1012 }
93665365 1013update_index:
fb1c18fc
EN
1014 if (!ret && update_cache) {
1015 int refresh = (!opt->priv->call_depth &&
1016 contents->mode != S_IFGITLINK);
1017 if (add_cacheinfo(opt, contents, path, 0, refresh,
fd53b7ff
EN
1018 ADD_CACHE_OK_TO_ADD))
1019 return -1;
fb1c18fc 1020 }
6003303a 1021 return ret;
9047ebbc
MV
1022}
1023
259ccb6c 1024static int update_file(struct merge_options *opt,
75456f96 1025 int clean,
8daec1df 1026 const struct diff_filespec *contents,
75456f96 1027 const char *path)
9047ebbc 1028{
8daec1df 1029 return update_file_flags(opt, contents, path,
5bf7e577 1030 opt->priv->call_depth || clean, !opt->priv->call_depth);
9047ebbc
MV
1031}
1032
1033/* Low level file merging, update and removal */
1034
9cba13ca 1035struct merge_file_info {
8daec1df 1036 struct diff_filespec blob; /* mostly use oid & mode; sometimes path */
9047ebbc
MV
1037 unsigned clean:1,
1038 merge:1;
1039};
1040
259ccb6c 1041static int merge_3way(struct merge_options *opt,
b7fa51da 1042 mmbuffer_t *result_buf,
e3de888c 1043 const struct diff_filespec *o,
0c059420
EN
1044 const struct diff_filespec *a,
1045 const struct diff_filespec *b,
9047ebbc 1046 const char *branch1,
b2a7942b
EN
1047 const char *branch2,
1048 const int extra_marker_size)
9047ebbc
MV
1049{
1050 mmfile_t orig, src1, src2;
712516bc 1051 struct ll_merge_options ll_opts = {0};
139ef37a 1052 char *base, *name1, *name2;
35f69671 1053 enum ll_merge_result merge_status;
8cc5b290 1054
259ccb6c 1055 ll_opts.renormalize = opt->renormalize;
b2a7942b 1056 ll_opts.extra_marker_size = extra_marker_size;
259ccb6c 1057 ll_opts.xdl_opts = opt->xdl_opts;
712516bc 1058
5bf7e577 1059 if (opt->priv->call_depth) {
712516bc
JN
1060 ll_opts.virtual_ancestor = 1;
1061 ll_opts.variant = 0;
1062 } else {
259ccb6c 1063 switch (opt->recursive_variant) {
f3081dae 1064 case MERGE_VARIANT_OURS:
712516bc 1065 ll_opts.variant = XDL_MERGE_FAVOR_OURS;
8cc5b290 1066 break;
f3081dae 1067 case MERGE_VARIANT_THEIRS:
712516bc 1068 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
8cc5b290
AP
1069 break;
1070 default:
712516bc 1071 ll_opts.variant = 0;
8cc5b290
AP
1072 break;
1073 }
1074 }
9047ebbc 1075
139ef37a
EN
1076 assert(a->path && b->path && o->path && opt->ancestor);
1077 if (strcmp(a->path, b->path) || strcmp(a->path, o->path) != 0) {
1078 base = mkpathdup("%s:%s", opt->ancestor, o->path);
4e2d094d
RJ
1079 name1 = mkpathdup("%s:%s", branch1, a->path);
1080 name2 = mkpathdup("%s:%s", branch2, b->path);
606475f3 1081 } else {
139ef37a 1082 base = mkpathdup("%s", opt->ancestor);
4e2d094d
RJ
1083 name1 = mkpathdup("%s", branch1);
1084 name2 = mkpathdup("%s", branch2);
606475f3 1085 }
9047ebbc 1086
e3de888c 1087 read_mmblob(&orig, &o->oid);
d449347d 1088 read_mmblob(&src1, &a->oid);
1089 read_mmblob(&src2, &b->oid);
9047ebbc 1090
816147e7
EN
1091 /*
1092 * FIXME: Using a->path for normalization rules in ll_merge could be
1093 * wrong if we renamed from a->path to b->path. We should use the
1094 * target path for where the file will be written.
1095 */
139ef37a 1096 merge_status = ll_merge(result_buf, a->path, &orig, base,
32eaa468 1097 &src1, name1, &src2, name2,
259ccb6c 1098 opt->repo->index, &ll_opts);
35f69671
EN
1099 if (merge_status == LL_MERGE_BINARY_CONFLICT)
1100 warning("Cannot merge binary files: %s (%s vs. %s)",
1101 a->path, name1, name2);
9047ebbc 1102
139ef37a 1103 free(base);
9047ebbc
MV
1104 free(name1);
1105 free(name2);
1106 free(orig.ptr);
1107 free(src1.ptr);
1108 free(src2.ptr);
1109 return merge_status;
1110}
1111
0d6caa2d
NTND
1112static int find_first_merges(struct repository *repo,
1113 struct object_array *result, const char *path,
d90e759f 1114 struct commit *a, struct commit *b)
18cfc088
SB
1115{
1116 int i, j;
1117 struct object_array merges = OBJECT_ARRAY_INIT;
1118 struct commit *commit;
1119 int contains_another;
1120
db1ba2a2 1121 char merged_revision[GIT_MAX_HEXSZ + 2];
18cfc088
SB
1122 const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1123 "--all", merged_revision, NULL };
1124 struct rev_info revs;
1125 struct setup_revision_opt rev_opts;
1126
1127 memset(result, 0, sizeof(struct object_array));
1128 memset(&rev_opts, 0, sizeof(rev_opts));
1129
1130 /* get all revisions that merge commit a */
1131 xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
d90e759f 1132 oid_to_hex(&a->object.oid));
0d6caa2d 1133 repo_init_revisions(repo, &revs, NULL);
18cfc088
SB
1134 /* FIXME: can't handle linked worktrees in submodules yet */
1135 revs.single_worktree = path != NULL;
1136 setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1137
1138 /* save all revisions from the above list that contain b */
1139 if (prepare_revision_walk(&revs))
1140 die("revision walk setup failed");
1141 while ((commit = get_revision(&revs)) != NULL) {
1142 struct object *o = &(commit->object);
10a0d6ae 1143 if (repo_in_merge_bases(repo, b, commit))
18cfc088
SB
1144 add_object_array(o, NULL, &merges);
1145 }
1146 reset_revision_walk();
1147
1148 /* Now we've got all merges that contain a and b. Prune all
1149 * merges that contain another found merge and save them in
1150 * result.
1151 */
1152 for (i = 0; i < merges.nr; i++) {
1153 struct commit *m1 = (struct commit *) merges.objects[i].item;
1154
1155 contains_another = 0;
1156 for (j = 0; j < merges.nr; j++) {
1157 struct commit *m2 = (struct commit *) merges.objects[j].item;
10a0d6ae 1158 if (i != j && repo_in_merge_bases(repo, m2, m1)) {
18cfc088
SB
1159 contains_another = 1;
1160 break;
1161 }
1162 }
1163
1164 if (!contains_another)
1165 add_object_array(merges.objects[i].item, NULL, result);
1166 }
1167
1168 object_array_clear(&merges);
2108fe4a 1169 release_revisions(&revs);
18cfc088
SB
1170 return result->nr;
1171}
1172
155b517d 1173static void print_commit(struct repository *repo, struct commit *commit)
18cfc088
SB
1174{
1175 struct strbuf sb = STRBUF_INIT;
1176 struct pretty_print_context ctx = {0};
1177 ctx.date_mode.type = DATE_NORMAL;
816147e7
EN
1178 /* FIXME: Merge this with output_commit_title() */
1179 assert(!merge_remote_util(commit));
155b517d 1180 repo_format_commit_message(repo, commit, " %h: %m %s", &sb, &ctx);
18cfc088
SB
1181 fprintf(stderr, "%s\n", sb.buf);
1182 strbuf_release(&sb);
1183}
1184
8daec1df
EN
1185static int is_valid(const struct diff_filespec *dfs)
1186{
1187 return dfs->mode != 0 && !is_null_oid(&dfs->oid);
1188}
1189
259ccb6c 1190static int merge_submodule(struct merge_options *opt,
325f3a8e 1191 struct object_id *result, const char *path,
18cfc088 1192 const struct object_id *base, const struct object_id *a,
325f3a8e 1193 const struct object_id *b)
18cfc088 1194{
10a0d6ae
JT
1195 struct repository subrepo;
1196 int ret = 0;
18cfc088
SB
1197 struct commit *commit_base, *commit_a, *commit_b;
1198 int parent_count;
1199 struct object_array merges;
1200
1201 int i;
5bf7e577 1202 int search = !opt->priv->call_depth;
18cfc088
SB
1203
1204 /* store a in result in case we fail */
816147e7
EN
1205 /* FIXME: This is the WRONG resolution for the recursive case when
1206 * we need to be careful to avoid accidentally matching either side.
1207 * Should probably use o instead there, much like we do for merging
1208 * binaries.
1209 */
18cfc088
SB
1210 oidcpy(result, a);
1211
1212 /* we can not handle deletion conflicts */
1213 if (is_null_oid(base))
1214 return 0;
1215 if (is_null_oid(a))
1216 return 0;
1217 if (is_null_oid(b))
1218 return 0;
1219
10a0d6ae
JT
1220 if (repo_submodule_init(&subrepo, opt->repo, path, null_oid())) {
1221 output(opt, 1, _("Failed to merge submodule %s (not checked out)"), path);
18cfc088
SB
1222 return 0;
1223 }
1224
10a0d6ae
JT
1225 if (!(commit_base = lookup_commit_reference(&subrepo, base)) ||
1226 !(commit_a = lookup_commit_reference(&subrepo, a)) ||
1227 !(commit_b = lookup_commit_reference(&subrepo, b))) {
1228 output(opt, 1, _("Failed to merge submodule %s (commits not present)"), path);
1229 goto cleanup;
1230 }
1231
18cfc088 1232 /* check whether both changes are forward */
10a0d6ae
JT
1233 if (!repo_in_merge_bases(&subrepo, commit_base, commit_a) ||
1234 !repo_in_merge_bases(&subrepo, commit_base, commit_b)) {
259ccb6c 1235 output(opt, 1, _("Failed to merge submodule %s (commits don't follow merge-base)"), path);
10a0d6ae 1236 goto cleanup;
18cfc088
SB
1237 }
1238
1239 /* Case #1: a is contained in b or vice versa */
10a0d6ae 1240 if (repo_in_merge_bases(&subrepo, commit_a, commit_b)) {
18cfc088 1241 oidcpy(result, b);
259ccb6c
EN
1242 if (show(opt, 3)) {
1243 output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
155b517d 1244 repo_output_commit_title(opt, &subrepo, commit_b);
259ccb6c
EN
1245 } else if (show(opt, 2))
1246 output(opt, 2, _("Fast-forwarding submodule %s"), path);
76f42125
LM
1247 else
1248 ; /* no output */
1249
10a0d6ae
JT
1250 ret = 1;
1251 goto cleanup;
18cfc088 1252 }
10a0d6ae 1253 if (repo_in_merge_bases(&subrepo, commit_b, commit_a)) {
18cfc088 1254 oidcpy(result, a);
259ccb6c
EN
1255 if (show(opt, 3)) {
1256 output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
155b517d 1257 repo_output_commit_title(opt, &subrepo, commit_a);
259ccb6c
EN
1258 } else if (show(opt, 2))
1259 output(opt, 2, _("Fast-forwarding submodule %s"), path);
76f42125
LM
1260 else
1261 ; /* no output */
1262
10a0d6ae
JT
1263 ret = 1;
1264 goto cleanup;
18cfc088
SB
1265 }
1266
1267 /*
1268 * Case #2: There are one or more merges that contain a and b in
1269 * the submodule. If there is only one, then present it as a
1270 * suggestion to the user, but leave it marked unmerged so the
1271 * user needs to confirm the resolution.
1272 */
1273
1274 /* Skip the search if makes no sense to the calling context. */
1275 if (!search)
10a0d6ae 1276 goto cleanup;
18cfc088
SB
1277
1278 /* find commit which merges them */
10a0d6ae 1279 parent_count = find_first_merges(&subrepo, &merges, path,
0d6caa2d 1280 commit_a, commit_b);
18cfc088
SB
1281 switch (parent_count) {
1282 case 0:
259ccb6c 1283 output(opt, 1, _("Failed to merge submodule %s (merge following commits not found)"), path);
18cfc088
SB
1284 break;
1285
1286 case 1:
259ccb6c
EN
1287 output(opt, 1, _("Failed to merge submodule %s (not fast-forward)"), path);
1288 output(opt, 2, _("Found a possible merge resolution for the submodule:\n"));
155b517d 1289 print_commit(&subrepo, (struct commit *) merges.objects[0].item);
259ccb6c 1290 output(opt, 2, _(
d90e759f
EN
1291 "If this is correct simply add it to the index "
1292 "for example\n"
1293 "by using:\n\n"
1294 " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1295 "which will accept this suggestion.\n"),
1296 oid_to_hex(&merges.objects[0].item->oid), path);
18cfc088
SB
1297 break;
1298
1299 default:
259ccb6c 1300 output(opt, 1, _("Failed to merge submodule %s (multiple merges found)"), path);
18cfc088 1301 for (i = 0; i < merges.nr; i++)
155b517d 1302 print_commit(&subrepo, (struct commit *) merges.objects[i].item);
18cfc088
SB
1303 }
1304
1305 object_array_clear(&merges);
10a0d6ae
JT
1306cleanup:
1307 repo_clear(&subrepo);
1308 return ret;
18cfc088
SB
1309}
1310
259ccb6c 1311static int merge_mode_and_contents(struct merge_options *opt,
e3de888c 1312 const struct diff_filespec *o,
d9573556
EN
1313 const struct diff_filespec *a,
1314 const struct diff_filespec *b,
1315 const char *filename,
1316 const char *branch1,
1317 const char *branch2,
b2a7942b 1318 const int extra_marker_size,
d9573556 1319 struct merge_file_info *result)
9047ebbc 1320{
259ccb6c 1321 if (opt->branch1 != branch1) {
4f445453
EN
1322 /*
1323 * It's weird getting a reverse merge with HEAD on the bottom
1324 * side of the conflict markers and the other branch on the
1325 * top. Fix that.
1326 */
e3de888c 1327 return merge_mode_and_contents(opt, o, b, a,
4f445453 1328 filename,
b2a7942b
EN
1329 branch2, branch1,
1330 extra_marker_size, result);
4f445453
EN
1331 }
1332
3c8a51e8
JS
1333 result->merge = 0;
1334 result->clean = 1;
9047ebbc
MV
1335
1336 if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
3c8a51e8 1337 result->clean = 0;
816147e7
EN
1338 /*
1339 * FIXME: This is a bad resolution for recursive case; for
1340 * the recursive case we want something that is unlikely to
1341 * accidentally match either side. Also, while it makes
1342 * sense to prefer regular files over symlinks, it doesn't
1343 * make sense to prefer regular files over submodules.
1344 */
9047ebbc 1345 if (S_ISREG(a->mode)) {
8daec1df
EN
1346 result->blob.mode = a->mode;
1347 oidcpy(&result->blob.oid, &a->oid);
9047ebbc 1348 } else {
8daec1df
EN
1349 result->blob.mode = b->mode;
1350 oidcpy(&result->blob.oid, &b->oid);
9047ebbc
MV
1351 }
1352 } else {
763a59e7 1353 if (!oideq(&a->oid, &o->oid) && !oideq(&b->oid, &o->oid))
3c8a51e8 1354 result->merge = 1;
9047ebbc
MV
1355
1356 /*
1357 * Merge modes
1358 */
e3de888c 1359 if (a->mode == b->mode || a->mode == o->mode)
8daec1df 1360 result->blob.mode = b->mode;
9047ebbc 1361 else {
8daec1df 1362 result->blob.mode = a->mode;
e3de888c 1363 if (b->mode != o->mode) {
3c8a51e8
JS
1364 result->clean = 0;
1365 result->merge = 1;
9047ebbc
MV
1366 }
1367 }
1368
763a59e7 1369 if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
8daec1df 1370 oidcpy(&result->blob.oid, &b->oid);
763a59e7 1371 else if (oideq(&b->oid, &o->oid))
8daec1df 1372 oidcpy(&result->blob.oid, &a->oid);
9047ebbc
MV
1373 else if (S_ISREG(a->mode)) {
1374 mmbuffer_t result_buf;
6003303a 1375 int ret = 0, merge_status;
9047ebbc 1376
e3de888c 1377 merge_status = merge_3way(opt, &result_buf, o, a, b,
b2a7942b
EN
1378 branch1, branch2,
1379 extra_marker_size);
9047ebbc
MV
1380
1381 if ((merge_status < 0) || !result_buf.ptr)
259ccb6c 1382 ret = err(opt, _("Failed to execute internal merge"));
9047ebbc 1383
a09c985e
PO
1384 if (!ret &&
1385 write_object_file(result_buf.ptr, result_buf.size,
c80d226a 1386 OBJ_BLOB, &result->blob.oid))
259ccb6c 1387 ret = err(opt, _("Unable to add %s to database"),
bc9204d4 1388 a->path);
9047ebbc
MV
1389
1390 free(result_buf.ptr);
6003303a
JS
1391 if (ret)
1392 return ret;
816147e7 1393 /* FIXME: bug, what if modes didn't match? */
3c8a51e8 1394 result->clean = (merge_status == 0);
9047ebbc 1395 } else if (S_ISGITLINK(a->mode)) {
8daec1df 1396 result->clean = merge_submodule(opt, &result->blob.oid,
e3de888c
EN
1397 o->path,
1398 &o->oid,
d90e759f
EN
1399 &a->oid,
1400 &b->oid);
9047ebbc 1401 } else if (S_ISLNK(a->mode)) {
259ccb6c 1402 switch (opt->recursive_variant) {
f3081dae 1403 case MERGE_VARIANT_NORMAL:
8daec1df 1404 oidcpy(&result->blob.oid, &a->oid);
763a59e7 1405 if (!oideq(&a->oid, &b->oid))
fd48b464
JH
1406 result->clean = 0;
1407 break;
f3081dae 1408 case MERGE_VARIANT_OURS:
8daec1df 1409 oidcpy(&result->blob.oid, &a->oid);
fd48b464 1410 break;
f3081dae 1411 case MERGE_VARIANT_THEIRS:
8daec1df 1412 oidcpy(&result->blob.oid, &b->oid);
fd48b464
JH
1413 break;
1414 }
ef1177d1 1415 } else
033abf97 1416 BUG("unsupported object type in the tree");
9047ebbc
MV
1417 }
1418
05cf21eb 1419 if (result->merge)
259ccb6c 1420 output(opt, 2, _("Auto-merging %s"), filename);
05cf21eb 1421
3c8a51e8 1422 return 0;
9047ebbc
MV
1423}
1424
259ccb6c 1425static int handle_rename_via_dir(struct merge_options *opt,
e2d563df 1426 struct rename_conflict_info *ci)
9c0743fe 1427{
5455c338
EN
1428 /*
1429 * Handle file adds that need to be renamed due to directory rename
1430 * detection. This differs from handle_rename_normal, because
1431 * there is no content merge to do; just move the file into the
1432 * desired final location.
1433 */
e2d563df
EN
1434 const struct rename *ren = ci->ren1;
1435 const struct diff_filespec *dest = ren->pair->two;
8c8e5bd6 1436 char *file_path = dest->path;
8e012516
DS
1437 int mark_conflicted = (opt->detect_directory_renames ==
1438 MERGE_DIRECTORY_RENAMES_CONFLICT);
8c8e5bd6 1439 assert(ren->dir_rename_original_dest);
9c0743fe 1440
5bf7e577 1441 if (!opt->priv->call_depth && would_lose_untracked(opt, dest->path)) {
8c8e5bd6
EN
1442 mark_conflicted = 1;
1443 file_path = unique_path(opt, dest->path, ren->branch);
259ccb6c 1444 output(opt, 1, _("Error: Refusing to lose untracked file at %s; "
8c8e5bd6
EN
1445 "writing to %s instead."),
1446 dest->path, file_path);
1447 }
79c47598 1448
8c8e5bd6 1449 if (mark_conflicted) {
79c47598 1450 /*
8c8e5bd6
EN
1451 * Write the file in worktree at file_path. In the index,
1452 * only record the file at dest->path in the appropriate
1453 * higher stage.
79c47598 1454 */
8c8e5bd6 1455 if (update_file(opt, 0, dest, file_path))
79c47598 1456 return -1;
8c8e5bd6
EN
1457 if (file_path != dest->path)
1458 free(file_path);
1459 if (update_stages(opt, dest->path, NULL,
1460 ren->branch == opt->branch1 ? dest : NULL,
1461 ren->branch == opt->branch1 ? NULL : dest))
1462 return -1;
1463 return 0; /* not clean, but conflicted */
1464 } else {
1465 /* Update dest->path both in index and in worktree */
1466 if (update_file(opt, 1, dest, dest->path))
1467 return -1;
1468 return 1; /* clean */
79c47598 1469 }
6bdaead1
EN
1470}
1471
259ccb6c 1472static int handle_change_delete(struct merge_options *opt,
d90e759f 1473 const char *path, const char *old_path,
8daec1df
EN
1474 const struct diff_filespec *o,
1475 const struct diff_filespec *changed,
d90e759f
EN
1476 const char *change_branch,
1477 const char *delete_branch,
1478 const char *change, const char *change_past)
b7033252 1479{
b26d87f2
MM
1480 char *alt_path = NULL;
1481 const char *update_path = path;
75456f96 1482 int ret = 0;
b26d87f2 1483
5bf7e577
EN
1484 if (dir_in_way(opt->repo->index, path, !opt->priv->call_depth, 0) ||
1485 (!opt->priv->call_depth && would_lose_untracked(opt, path))) {
259ccb6c 1486 update_path = alt_path = unique_path(opt, path, change_branch);
b7033252
EN
1487 }
1488
5bf7e577 1489 if (opt->priv->call_depth) {
b7033252
EN
1490 /*
1491 * We cannot arbitrarily accept either a_sha or b_sha as
1492 * correct; since there is no true "middle point" between
1493 * them, simply reuse the base version for virtual merge base.
1494 */
259ccb6c 1495 ret = remove_file_from_index(opt->repo->index, path);
75456f96 1496 if (!ret)
8daec1df 1497 ret = update_file(opt, 0, o, update_path);
b7033252 1498 } else {
5b26c3c9
EN
1499 /*
1500 * Despite the four nearly duplicate messages and argument
1501 * lists below and the ugliness of the nested if-statements,
1502 * having complete messages makes the job easier for
1503 * translators.
1504 *
1505 * The slight variance among the cases is due to the fact
1506 * that:
1507 * 1) directory/file conflicts (in effect if
1508 * !alt_path) could cause us to need to write the
1509 * file to a different path.
1510 * 2) renames (in effect if !old_path) could mean that
1511 * there are two names for the path that the user
1512 * may know the file by.
1513 */
b26d87f2
MM
1514 if (!alt_path) {
1515 if (!old_path) {
259ccb6c 1516 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
b26d87f2
MM
1517 "and %s in %s. Version %s of %s left in tree."),
1518 change, path, delete_branch, change_past,
1519 change_branch, change_branch, path);
1520 } else {
259ccb6c 1521 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
b26d87f2
MM
1522 "and %s to %s in %s. Version %s of %s left in tree."),
1523 change, old_path, delete_branch, change_past, path,
1524 change_branch, change_branch, path);
1525 }
55653a68 1526 } else {
b26d87f2 1527 if (!old_path) {
259ccb6c 1528 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
b26d87f2
MM
1529 "and %s in %s. Version %s of %s left in tree at %s."),
1530 change, path, delete_branch, change_past,
1531 change_branch, change_branch, path, alt_path);
1532 } else {
259ccb6c 1533 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
b26d87f2
MM
1534 "and %s to %s in %s. Version %s of %s left in tree at %s."),
1535 change, old_path, delete_branch, change_past, path,
1536 change_branch, change_branch, path, alt_path);
1537 }
55653a68 1538 }
35a74abf 1539 /*
b26d87f2 1540 * No need to call update_file() on path when change_branch ==
259ccb6c 1541 * opt->branch1 && !alt_path, since that would needlessly touch
b26d87f2
MM
1542 * path. We could call update_file_flags() with update_cache=0
1543 * and update_wd=0, but that's a no-op.
35a74abf 1544 */
259ccb6c 1545 if (change_branch != opt->branch1 || alt_path)
8daec1df 1546 ret = update_file(opt, 0, changed, update_path);
b7033252 1547 }
b26d87f2 1548 free(alt_path);
75456f96
JS
1549
1550 return ret;
b7033252
EN
1551}
1552
259ccb6c 1553static int handle_rename_delete(struct merge_options *opt,
e2d563df 1554 struct rename_conflict_info *ci)
9047ebbc 1555{
e2d563df
EN
1556 const struct rename *ren = ci->ren1;
1557 const struct diff_filespec *orig = ren->pair->one;
1558 const struct diff_filespec *dest = ren->pair->two;
1559 const char *rename_branch = ren->branch;
1560 const char *delete_branch = (opt->branch1 == ren->branch ?
1561 opt->branch2 : opt->branch1);
6ef2cb00 1562
259ccb6c 1563 if (handle_change_delete(opt,
5bf7e577
EN
1564 opt->priv->call_depth ? orig->path : dest->path,
1565 opt->priv->call_depth ? NULL : orig->path,
8daec1df 1566 orig, dest,
b26d87f2 1567 rename_branch, delete_branch,
75456f96
JS
1568 _("rename"), _("renamed")))
1569 return -1;
e03acb8b 1570
5bf7e577 1571 if (opt->priv->call_depth)
259ccb6c 1572 return remove_file_from_index(opt->repo->index, dest->path);
75456f96 1573 else
259ccb6c
EN
1574 return update_stages(opt, dest->path, NULL,
1575 rename_branch == opt->branch1 ? dest : NULL,
1576 rename_branch == opt->branch1 ? NULL : dest);
6ef2cb00
EN
1577}
1578
259ccb6c 1579static int handle_file_collision(struct merge_options *opt,
37b65ce3
EN
1580 const char *collide_path,
1581 const char *prev_path1,
1582 const char *prev_path2,
1583 const char *branch1, const char *branch2,
8daec1df
EN
1584 struct diff_filespec *a,
1585 struct diff_filespec *b)
3672c971 1586{
37b65ce3 1587 struct merge_file_info mfi;
8daec1df 1588 struct diff_filespec null;
37b65ce3
EN
1589 char *alt_path = NULL;
1590 const char *update_path = collide_path;
3672c971 1591
7f867165
EN
1592 /*
1593 * It's easiest to get the correct things into stage 2 and 3, and
1594 * to make sure that the content merge puts HEAD before the other
259ccb6c 1595 * branch if we just ensure that branch1 == opt->branch1. So, simply
7f867165
EN
1596 * flip arguments around if we don't have that.
1597 */
259ccb6c
EN
1598 if (branch1 != opt->branch1) {
1599 return handle_file_collision(opt, collide_path,
7f867165
EN
1600 prev_path2, prev_path1,
1601 branch2, branch1,
8daec1df 1602 b, a);
9047ebbc 1603 }
3672c971 1604
37b65ce3
EN
1605 /* Remove rename sources if rename/add or rename/rename(2to1) */
1606 if (prev_path1)
259ccb6c 1607 remove_file(opt, 1, prev_path1,
5bf7e577 1608 opt->priv->call_depth || would_lose_untracked(opt, prev_path1));
37b65ce3 1609 if (prev_path2)
259ccb6c 1610 remove_file(opt, 1, prev_path2,
5bf7e577 1611 opt->priv->call_depth || would_lose_untracked(opt, prev_path2));
37b65ce3
EN
1612
1613 /*
1614 * Remove the collision path, if it wouldn't cause dirty contents
1615 * or an untracked file to get lost. We'll either overwrite with
1616 * merged contents, or just write out to differently named files.
1617 */
259ccb6c
EN
1618 if (was_dirty(opt, collide_path)) {
1619 output(opt, 1, _("Refusing to lose dirty file at %s"),
37b65ce3 1620 collide_path);
259ccb6c
EN
1621 update_path = alt_path = unique_path(opt, collide_path, "merged");
1622 } else if (would_lose_untracked(opt, collide_path)) {
18797a3b 1623 /*
37b65ce3
EN
1624 * Only way we get here is if both renames were from
1625 * a directory rename AND user had an untracked file
1626 * at the location where both files end up after the
1627 * two directory renames. See testcase 10d of t6043.
18797a3b 1628 */
259ccb6c 1629 output(opt, 1, _("Refusing to lose untracked file at "
37b65ce3
EN
1630 "%s, even though it's in the way."),
1631 collide_path);
259ccb6c 1632 update_path = alt_path = unique_path(opt, collide_path, "merged");
3672c971 1633 } else {
37b65ce3
EN
1634 /*
1635 * FIXME: It's possible that the two files are identical
1636 * and that the current working copy happens to match, in
1637 * which case we are unnecessarily touching the working
1638 * tree file. It's not a likely enough scenario that I
1639 * want to code up the checks for it and a better fix is
1640 * available if we restructure how unpack_trees() and
1641 * merge-recursive interoperate anyway, so punting for
1642 * now...
1643 */
259ccb6c 1644 remove_file(opt, 0, collide_path, 0);
9047ebbc 1645 }
3672c971 1646
37b65ce3 1647 /* Store things in diff_filespecs for functions that need it */
8daec1df 1648 null.path = (char *)collide_path;
14228447 1649 oidcpy(&null.oid, null_oid());
37b65ce3 1650 null.mode = 0;
8daec1df
EN
1651
1652 if (merge_mode_and_contents(opt, &null, a, b, collide_path,
5bf7e577 1653 branch1, branch2, opt->priv->call_depth * 2, &mfi))
37b65ce3
EN
1654 return -1;
1655 mfi.clean &= !alt_path;
8daec1df 1656 if (update_file(opt, mfi.clean, &mfi.blob, update_path))
37b65ce3 1657 return -1;
5bf7e577 1658 if (!mfi.clean && !opt->priv->call_depth &&
8daec1df 1659 update_stages(opt, collide_path, NULL, a, b))
37b65ce3
EN
1660 return -1;
1661 free(alt_path);
1662 /*
1663 * FIXME: If both a & b both started with conflicts (only possible
1664 * if they came from a rename/rename(2to1)), but had IDENTICAL
1665 * contents including those conflicts, then in the next line we claim
1666 * it was clean. If someone cares about this case, we should have the
1667 * caller notify us if we started with conflicts.
1668 */
1669 return mfi.clean;
1670}
7f867165 1671
259ccb6c 1672static int handle_rename_add(struct merge_options *opt,
7f867165
EN
1673 struct rename_conflict_info *ci)
1674{
1675 /* a was renamed to c, and a separate c was added. */
e9cd1b5c
EN
1676 struct diff_filespec *a = ci->ren1->pair->one;
1677 struct diff_filespec *c = ci->ren1->pair->two;
7f867165
EN
1678 char *path = c->path;
1679 char *prev_path_desc;
1680 struct merge_file_info mfi;
1681
c336ab85
EN
1682 const char *rename_branch = ci->ren1->branch;
1683 const char *add_branch = (opt->branch1 == rename_branch ?
1684 opt->branch2 : opt->branch1);
1685 int other_stage = (ci->ren1->branch == opt->branch1 ? 3 : 2);
7f867165 1686
259ccb6c 1687 output(opt, 1, _("CONFLICT (rename/add): "
7f867165 1688 "Rename %s->%s in %s. Added %s in %s"),
c336ab85
EN
1689 a->path, c->path, rename_branch,
1690 c->path, add_branch);
7f867165
EN
1691
1692 prev_path_desc = xstrfmt("version of %s from %s", path, a->path);
481de8a2 1693 ci->ren1->src_entry->stages[other_stage].path = a->path;
8daec1df
EN
1694 if (merge_mode_and_contents(opt, a, c,
1695 &ci->ren1->src_entry->stages[other_stage],
3f9c92ec 1696 prev_path_desc,
259ccb6c 1697 opt->branch1, opt->branch2,
5bf7e577 1698 1 + opt->priv->call_depth * 2, &mfi))
7f867165
EN
1699 return -1;
1700 free(prev_path_desc);
1701
8daec1df 1702 ci->ren1->dst_entry->stages[other_stage].path = mfi.blob.path = c->path;
259ccb6c 1703 return handle_file_collision(opt,
7f867165 1704 c->path, a->path, NULL,
c336ab85 1705 rename_branch, add_branch,
8daec1df
EN
1706 &mfi.blob,
1707 &ci->ren1->dst_entry->stages[other_stage]);
7f867165 1708}
37b65ce3 1709
259ccb6c 1710static char *find_path_for_conflict(struct merge_options *opt,
80cee6e3
DS
1711 const char *path,
1712 const char *branch1,
1713 const char *branch2)
1714{
1715 char *new_path = NULL;
5bf7e577 1716 if (dir_in_way(opt->repo->index, path, !opt->priv->call_depth, 0)) {
259ccb6c
EN
1717 new_path = unique_path(opt, path, branch1);
1718 output(opt, 1, _("%s is a directory in %s adding "
80cee6e3
DS
1719 "as %s instead"),
1720 path, branch2, new_path);
259ccb6c
EN
1721 } else if (would_lose_untracked(opt, path)) {
1722 new_path = unique_path(opt, path, branch1);
1723 output(opt, 1, _("Refusing to lose untracked file"
80cee6e3
DS
1724 " at %s; adding as %s instead"),
1725 path, new_path);
1726 }
1727
1728 return new_path;
3672c971
EN
1729}
1730
ee798742 1731/*
4c616c2b 1732 * Toggle the stage number between "ours" and "theirs" (2 and 3).
ee798742
JK
1733 */
1734static inline int flip_stage(int stage)
1735{
4c616c2b 1736 return (2 + 3) - stage;
ee798742
JK
1737}
1738
259ccb6c 1739static int handle_rename_rename_1to2(struct merge_options *opt,
8ebe7b05 1740 struct rename_conflict_info *ci)
9047ebbc 1741{
09c01f85 1742 /* One file was renamed in both branches, but to different names. */
48c9cb9d 1743 struct merge_file_info mfi;
48c9cb9d 1744 struct diff_filespec *add;
e9cd1b5c
EN
1745 struct diff_filespec *o = ci->ren1->pair->one;
1746 struct diff_filespec *a = ci->ren1->pair->two;
1747 struct diff_filespec *b = ci->ren2->pair->two;
48c9cb9d 1748 char *path_desc;
4f66dade 1749
259ccb6c 1750 output(opt, 1, _("CONFLICT (rename/rename): "
4f66dade 1751 "Rename \"%s\"->\"%s\" in branch \"%s\" "
55653a68 1752 "rename \"%s\"->\"%s\" in \"%s\"%s"),
c336ab85
EN
1753 o->path, a->path, ci->ren1->branch,
1754 o->path, b->path, ci->ren2->branch,
5bf7e577 1755 opt->priv->call_depth ? _(" (left unresolved)") : "");
75456f96 1756
48c9cb9d 1757 path_desc = xstrfmt("%s and %s, both renamed from %s",
e3de888c
EN
1758 a->path, b->path, o->path);
1759 if (merge_mode_and_contents(opt, o, a, b, path_desc,
c336ab85 1760 ci->ren1->branch, ci->ren2->branch,
5bf7e577 1761 opt->priv->call_depth * 2, &mfi))
48c9cb9d
EN
1762 return -1;
1763 free(path_desc);
1764
80205040
EN
1765 if (opt->priv->call_depth)
1766 remove_file_from_index(opt->repo->index, o->path);
07413c5a 1767
80205040
EN
1768 /*
1769 * For each destination path, we need to see if there is a
1770 * rename/add collision. If not, we can write the file out
1771 * to the specified location.
1772 */
1773 add = &ci->ren1->dst_entry->stages[flip_stage(2)];
1774 if (is_valid(add)) {
1775 add->path = mfi.blob.path = a->path;
1776 if (handle_file_collision(opt, a->path,
1777 NULL, NULL,
1778 ci->ren1->branch,
1779 ci->ren2->branch,
1780 &mfi.blob, add) < 0)
1781 return -1;
48c9cb9d 1782 } else {
80205040
EN
1783 char *new_path = find_path_for_conflict(opt, a->path,
1784 ci->ren1->branch,
1785 ci->ren2->branch);
1786 if (update_file(opt, 0, &mfi.blob,
1787 new_path ? new_path : a->path))
1788 return -1;
1789 free(new_path);
1790 if (!opt->priv->call_depth &&
1791 update_stages(opt, a->path, NULL, a, NULL))
1792 return -1;
1793 }
48c9cb9d 1794
95983da6
EN
1795 if (!mfi.clean && mfi.blob.mode == a->mode &&
1796 oideq(&mfi.blob.oid, &a->oid)) {
1797 /*
1798 * Getting here means we were attempting to merge a binary
1799 * blob. Since we can't merge binaries, the merge algorithm
1800 * just takes one side. But we don't want to copy the
1801 * contents of one side to both paths; we'd rather use the
1802 * original content at the given path for each path.
1803 */
1804 oidcpy(&mfi.blob.oid, &b->oid);
1805 mfi.blob.mode = b->mode;
1806 }
80205040
EN
1807 add = &ci->ren2->dst_entry->stages[flip_stage(3)];
1808 if (is_valid(add)) {
1809 add->path = mfi.blob.path = b->path;
1810 if (handle_file_collision(opt, b->path,
1811 NULL, NULL,
1812 ci->ren1->branch,
1813 ci->ren2->branch,
1814 add, &mfi.blob) < 0)
1815 return -1;
1816 } else {
1817 char *new_path = find_path_for_conflict(opt, b->path,
1818 ci->ren2->branch,
1819 ci->ren1->branch);
1820 if (update_file(opt, 0, &mfi.blob,
1821 new_path ? new_path : b->path))
1822 return -1;
1823 free(new_path);
1824 if (!opt->priv->call_depth &&
1825 update_stages(opt, b->path, NULL, NULL, b))
1826 return -1;
48c9cb9d 1827 }
75456f96
JS
1828
1829 return 0;
9047ebbc
MV
1830}
1831
259ccb6c 1832static int handle_rename_rename_2to1(struct merge_options *opt,
8ebe7b05 1833 struct rename_conflict_info *ci)
9047ebbc 1834{
461f5041 1835 /* Two files, a & b, were renamed to the same thing, c. */
e9cd1b5c
EN
1836 struct diff_filespec *a = ci->ren1->pair->one;
1837 struct diff_filespec *b = ci->ren2->pair->one;
1838 struct diff_filespec *c1 = ci->ren1->pair->two;
1839 struct diff_filespec *c2 = ci->ren2->pair->two;
461f5041 1840 char *path = c1->path; /* == c2->path */
05cf21eb
EN
1841 char *path_side_1_desc;
1842 char *path_side_2_desc;
434b8525
EN
1843 struct merge_file_info mfi_c1;
1844 struct merge_file_info mfi_c2;
8daec1df 1845 int ostage1, ostage2;
461f5041 1846
259ccb6c 1847 output(opt, 1, _("CONFLICT (rename/rename): "
461f5041 1848 "Rename %s->%s in %s. "
55653a68 1849 "Rename %s->%s in %s"),
c336ab85
EN
1850 a->path, c1->path, ci->ren1->branch,
1851 b->path, c2->path, ci->ren2->branch);
461f5041 1852
2b168ef3
EN
1853 path_side_1_desc = xstrfmt("version of %s from %s", path, a->path);
1854 path_side_2_desc = xstrfmt("version of %s from %s", path, b->path);
8daec1df 1855 ostage1 = ci->ren1->branch == opt->branch1 ? 3 : 2;
ee798742 1856 ostage2 = flip_stage(ostage1);
8daec1df
EN
1857 ci->ren1->src_entry->stages[ostage1].path = a->path;
1858 ci->ren2->src_entry->stages[ostage2].path = b->path;
1859 if (merge_mode_and_contents(opt, a, c1,
1860 &ci->ren1->src_entry->stages[ostage1],
1861 path_side_1_desc,
259ccb6c 1862 opt->branch1, opt->branch2,
5bf7e577 1863 1 + opt->priv->call_depth * 2, &mfi_c1) ||
8daec1df
EN
1864 merge_mode_and_contents(opt, b,
1865 &ci->ren2->src_entry->stages[ostage2],
1866 c2, path_side_2_desc,
259ccb6c 1867 opt->branch1, opt->branch2,
5bf7e577 1868 1 + opt->priv->call_depth * 2, &mfi_c2))
75456f96 1869 return -1;
05cf21eb
EN
1870 free(path_side_1_desc);
1871 free(path_side_2_desc);
8daec1df
EN
1872 mfi_c1.blob.path = path;
1873 mfi_c2.blob.path = path;
434b8525 1874
259ccb6c 1875 return handle_file_collision(opt, path, a->path, b->path,
c336ab85 1876 ci->ren1->branch, ci->ren2->branch,
8daec1df 1877 &mfi_c1.blob, &mfi_c2.blob);
9047ebbc
MV
1878}
1879
9ba91557 1880/*
e5257b2a 1881 * Get the diff_filepairs changed between o_tree and tree.
9ba91557 1882 */
259ccb6c 1883static struct diff_queue_struct *get_diffpairs(struct merge_options *opt,
e5257b2a
EN
1884 struct tree *o_tree,
1885 struct tree *tree)
9ba91557 1886{
e5257b2a 1887 struct diff_queue_struct *ret;
9ba91557
EN
1888 struct diff_options opts;
1889
259ccb6c 1890 repo_diff_setup(opt->repo, &opts);
9ba91557
EN
1891 opts.flags.recursive = 1;
1892 opts.flags.rename_empty = 0;
259ccb6c 1893 opts.detect_rename = merge_detect_rename(opt);
85b46030
BP
1894 /*
1895 * We do not have logic to handle the detection of copies. In
1896 * fact, it may not even make sense to add such logic: would we
1897 * really want a change to a base file to be propagated through
1898 * multiple other files by a merge?
1899 */
1900 if (opts.detect_rename > DIFF_DETECT_RENAME)
1901 opts.detect_rename = DIFF_DETECT_RENAME;
94b82d56 1902 opts.rename_limit = (opt->rename_limit >= 0) ? opt->rename_limit : 7000;
259ccb6c
EN
1903 opts.rename_score = opt->rename_score;
1904 opts.show_rename_progress = opt->show_rename_progress;
9ba91557
EN
1905 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1906 diff_setup_done(&opts);
1907 diff_tree_oid(&o_tree->object.oid, &tree->object.oid, "", &opts);
1908 diffcore_std(&opts);
5bf7e577
EN
1909 if (opts.needed_rename_limit > opt->priv->needed_rename_limit)
1910 opt->priv->needed_rename_limit = opts.needed_rename_limit;
e5257b2a
EN
1911
1912 ret = xmalloc(sizeof(*ret));
1913 *ret = diff_queued_diff;
1914
1915 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1916 diff_queued_diff.nr = 0;
1917 diff_queued_diff.queue = NULL;
1918 diff_flush(&opts);
1919 return ret;
1920}
1921
34e7771b
NTND
1922static int tree_has_path(struct repository *r, struct tree *tree,
1923 const char *path)
96e7ffbd
EN
1924{
1925 struct object_id hashy;
5ec1e728 1926 unsigned short mode_o;
96e7ffbd 1927
34e7771b 1928 return !get_tree_entry(r,
50ddb089 1929 &tree->object.oid, path,
96e7ffbd
EN
1930 &hashy, &mode_o);
1931}
1932
e95ab70a
EN
1933/*
1934 * Return a new string that replaces the beginning portion (which matches
1935 * entry->dir), with entry->new_dir. In perl-speak:
1936 * new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);
1937 * NOTE:
1938 * Caller must ensure that old_path starts with entry->dir + '/'.
1939 */
1940static char *apply_dir_rename(struct dir_rename_entry *entry,
1941 const char *old_path)
1942{
1943 struct strbuf new_path = STRBUF_INIT;
1944 int oldlen, newlen;
1945
1946 if (entry->non_unique_new_dir)
1947 return NULL;
1948
1949 oldlen = strlen(entry->dir);
49b8133a
EN
1950 if (entry->new_dir.len == 0)
1951 /*
1952 * If someone renamed/merged a subdirectory into the root
1953 * directory (e.g. 'some/subdir' -> ''), then we want to
1954 * avoid returning
1955 * '' + '/filename'
1956 * as the rename; we need to make old_path + oldlen advance
1957 * past the '/' character.
1958 */
1959 oldlen++;
e95ab70a
EN
1960 newlen = entry->new_dir.len + (strlen(old_path) - oldlen) + 1;
1961 strbuf_grow(&new_path, newlen);
1962 strbuf_addbuf(&new_path, &entry->new_dir);
1963 strbuf_addstr(&new_path, &old_path[oldlen]);
1964
1965 return strbuf_detach(&new_path, NULL);
1966}
1967
7fe40b88
EN
1968static void get_renamed_dir_portion(const char *old_path, const char *new_path,
1969 char **old_dir, char **new_dir)
1970{
1971 char *end_of_old, *end_of_new;
7fe40b88 1972
d3eebaad 1973 /* Default return values: NULL, meaning no rename */
7fe40b88
EN
1974 *old_dir = NULL;
1975 *new_dir = NULL;
1976
1977 /*
1978 * For
1979 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
1980 * the "e/foo.c" part is the same, we just want to know that
1981 * "a/b/c/d" was renamed to "a/b/some/thing/else"
1982 * so, for this example, this function returns "a/b/c/d" in
1983 * *old_dir and "a/b/some/thing/else" in *new_dir.
d3eebaad
EN
1984 */
1985
1986 /*
1987 * If the basename of the file changed, we don't care. We want
1988 * to know which portion of the directory, if any, changed.
7fe40b88
EN
1989 */
1990 end_of_old = strrchr(old_path, '/');
1991 end_of_new = strrchr(new_path, '/');
1992
49b8133a
EN
1993 /*
1994 * If end_of_old is NULL, old_path wasn't in a directory, so there
1995 * could not be a directory rename (our rule elsewhere that a
1996 * directory which still exists is not considered to have been
1997 * renamed means the root directory can never be renamed -- because
1998 * the root directory always exists).
1999 */
afe8a907 2000 if (!end_of_old)
49b8133a
EN
2001 return; /* Note: *old_dir and *new_dir are still NULL */
2002
2003 /*
2004 * If new_path contains no directory (end_of_new is NULL), then we
2005 * have a rename of old_path's directory to the root directory.
2006 */
afe8a907 2007 if (!end_of_new) {
49b8133a
EN
2008 *old_dir = xstrndup(old_path, end_of_old - old_path);
2009 *new_dir = xstrdup("");
7fe40b88 2010 return;
49b8133a 2011 }
d3eebaad
EN
2012
2013 /* Find the first non-matching character traversing backwards */
7fe40b88
EN
2014 while (*--end_of_new == *--end_of_old &&
2015 end_of_old != old_path &&
2016 end_of_new != new_path)
2017 ; /* Do nothing; all in the while loop */
d3eebaad 2018
7fe40b88 2019 /*
d3eebaad
EN
2020 * If both got back to the beginning of their strings, then the
2021 * directory didn't change at all, only the basename did.
7fe40b88 2022 */
d3eebaad
EN
2023 if (end_of_old == old_path && end_of_new == new_path &&
2024 *end_of_old == *end_of_new)
49b8133a 2025 return; /* Note: *old_dir and *new_dir are still NULL */
7fe40b88
EN
2026
2027 /*
49b8133a
EN
2028 * If end_of_new got back to the beginning of its string, and
2029 * end_of_old got back to the beginning of some subdirectory, then
2030 * we have a rename/merge of a subdirectory into the root, which
2031 * needs slightly special handling.
2032 *
2033 * Note: There is no need to consider the opposite case, with a
2034 * rename/merge of the root directory into some subdirectory
2035 * because as noted above the root directory always exists so it
2036 * cannot be considered to be renamed.
7fe40b88 2037 */
49b8133a
EN
2038 if (end_of_new == new_path &&
2039 end_of_old != old_path && end_of_old[-1] == '/') {
2040 *old_dir = xstrndup(old_path, --end_of_old - old_path);
2041 *new_dir = xstrdup("");
2042 return;
7fe40b88 2043 }
7fe40b88
EN
2044
2045 /*
d3eebaad
EN
2046 * We've found the first non-matching character in the directory
2047 * paths. That means the current characters we were looking at
2048 * were part of the first non-matching subdir name going back from
2049 * the end of the strings. Get the whole name by advancing both
2050 * end_of_old and end_of_new to the NEXT '/' character. That will
2051 * represent the entire directory rename.
2052 *
2053 * The reason for the increment is cases like
2054 * a/b/star/foo/whatever.c -> a/b/tar/foo/random.c
2055 * After dropping the basename and going back to the first
2056 * non-matching character, we're now comparing:
2057 * a/b/s and a/b/
2058 * and we want to be comparing:
2059 * a/b/star/ and a/b/tar/
2060 * but without the pre-increment, the one on the right would stay
2061 * a/b/.
7fe40b88 2062 */
d3eebaad
EN
2063 end_of_old = strchr(++end_of_old, '/');
2064 end_of_new = strchr(++end_of_new, '/');
7fe40b88 2065
d3eebaad
EN
2066 /* Copy the old and new directories into *old_dir and *new_dir. */
2067 *old_dir = xstrndup(old_path, end_of_old - old_path);
2068 *new_dir = xstrndup(new_path, end_of_new - new_path);
7fe40b88
EN
2069}
2070
96e7ffbd
EN
2071static void remove_hashmap_entries(struct hashmap *dir_renames,
2072 struct string_list *items_to_remove)
2073{
2074 int i;
2075 struct dir_rename_entry *entry;
2076
2077 for (i = 0; i < items_to_remove->nr; i++) {
2078 entry = items_to_remove->items[i].util;
28ee7941 2079 hashmap_remove(dir_renames, &entry->ent, NULL);
96e7ffbd
EN
2080 }
2081 string_list_clear(items_to_remove, 0);
2082}
2083
f6f77559
EN
2084/*
2085 * See if there is a directory rename for path, and if there are any file
2086 * level conflicts for the renamed location. If there is a rename and
2087 * there are no conflicts, return the new name. Otherwise, return NULL.
2088 */
259ccb6c 2089static char *handle_path_level_conflicts(struct merge_options *opt,
f6f77559
EN
2090 const char *path,
2091 struct dir_rename_entry *entry,
2092 struct hashmap *collisions,
2093 struct tree *tree)
2094{
2095 char *new_path = NULL;
2096 struct collision_entry *collision_ent;
2097 int clean = 1;
2098 struct strbuf collision_paths = STRBUF_INIT;
2099
2100 /*
2101 * entry has the mapping of old directory name to new directory name
2102 * that we want to apply to path.
2103 */
2104 new_path = apply_dir_rename(entry, path);
2105
2106 if (!new_path) {
2107 /* This should only happen when entry->non_unique_new_dir set */
2108 if (!entry->non_unique_new_dir)
42db324c 2109 BUG("entry->non_unique_new_dir not set and !new_path");
259ccb6c 2110 output(opt, 1, _("CONFLICT (directory rename split): "
f6f77559
EN
2111 "Unclear where to place %s because directory "
2112 "%s was renamed to multiple other directories, "
2113 "with no destination getting a majority of the "
2114 "files."),
2115 path, entry->dir);
2116 clean = 0;
2117 return NULL;
2118 }
2119
2120 /*
2121 * The caller needs to have ensured that it has pre-populated
2122 * collisions with all paths that map to new_path. Do a quick check
2123 * to ensure that's the case.
2124 */
2125 collision_ent = collision_find_entry(collisions, new_path);
afe8a907 2126 if (!collision_ent)
f6f77559
EN
2127 BUG("collision_ent is NULL");
2128
2129 /*
2130 * Check for one-sided add/add/.../add conflicts, i.e.
2131 * where implicit renames from the other side doing
2132 * directory rename(s) can affect this side of history
2133 * to put multiple paths into the same location. Warn
2134 * and bail on directory renames for such paths.
2135 */
2136 if (collision_ent->reported_already) {
2137 clean = 0;
34e7771b 2138 } else if (tree_has_path(opt->repo, tree, new_path)) {
f6f77559
EN
2139 collision_ent->reported_already = 1;
2140 strbuf_add_separated_string_list(&collision_paths, ", ",
2141 &collision_ent->source_files);
259ccb6c 2142 output(opt, 1, _("CONFLICT (implicit dir rename): Existing "
f6f77559
EN
2143 "file/dir at %s in the way of implicit "
2144 "directory rename(s) putting the following "
2145 "path(s) there: %s."),
2146 new_path, collision_paths.buf);
2147 clean = 0;
2148 } else if (collision_ent->source_files.nr > 1) {
2149 collision_ent->reported_already = 1;
2150 strbuf_add_separated_string_list(&collision_paths, ", ",
2151 &collision_ent->source_files);
259ccb6c 2152 output(opt, 1, _("CONFLICT (implicit dir rename): Cannot map "
f6f77559
EN
2153 "more than one path to %s; implicit directory "
2154 "renames tried to put these paths there: %s"),
2155 new_path, collision_paths.buf);
2156 clean = 0;
2157 }
2158
2159 /* Free memory we no longer need */
2160 strbuf_release(&collision_paths);
2161 if (!clean && new_path) {
2162 free(new_path);
2163 return NULL;
2164 }
2165
2166 return new_path;
2167}
2168
96e7ffbd
EN
2169/*
2170 * There are a couple things we want to do at the directory level:
2171 * 1. Check for both sides renaming to the same thing, in order to avoid
2172 * implicit renaming of files that should be left in place. (See
2173 * testcase 6b in t6043 for details.)
2174 * 2. Prune directory renames if there are still files left in the
abcb66c6 2175 * original directory. These represent a partial directory rename,
96e7ffbd
EN
2176 * i.e. a rename where only some of the files within the directory
2177 * were renamed elsewhere. (Technically, this could be done earlier
2178 * in get_directory_renames(), except that would prevent us from
2179 * doing the previous check and thus failing testcase 6b.)
2180 * 3. Check for rename/rename(1to2) conflicts (at the directory level).
2181 * In the future, we could potentially record this info as well and
2182 * omit reporting rename/rename(1to2) conflicts for each path within
2183 * the affected directories, thus cleaning up the merge output.
2184 * NOTE: We do NOT check for rename/rename(2to1) conflicts at the
2185 * directory level, because merging directories is fine. If it
2186 * causes conflicts for files within those merged directories, then
2187 * that should be detected at the individual path level.
2188 */
259ccb6c 2189static void handle_directory_level_conflicts(struct merge_options *opt,
96e7ffbd
EN
2190 struct hashmap *dir_re_head,
2191 struct tree *head,
2192 struct hashmap *dir_re_merge,
2193 struct tree *merge)
2194{
2195 struct hashmap_iter iter;
2196 struct dir_rename_entry *head_ent;
2197 struct dir_rename_entry *merge_ent;
2198
2199 struct string_list remove_from_head = STRING_LIST_INIT_NODUP;
2200 struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;
2201
87571c3f 2202 hashmap_for_each_entry(dir_re_head, &iter, head_ent,
87571c3f 2203 ent /* member name */) {
96e7ffbd
EN
2204 merge_ent = dir_rename_find_entry(dir_re_merge, head_ent->dir);
2205 if (merge_ent &&
2206 !head_ent->non_unique_new_dir &&
2207 !merge_ent->non_unique_new_dir &&
2208 !strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {
2209 /* 1. Renamed identically; remove it from both sides */
2210 string_list_append(&remove_from_head,
2211 head_ent->dir)->util = head_ent;
2212 strbuf_release(&head_ent->new_dir);
2213 string_list_append(&remove_from_merge,
2214 merge_ent->dir)->util = merge_ent;
2215 strbuf_release(&merge_ent->new_dir);
34e7771b 2216 } else if (tree_has_path(opt->repo, head, head_ent->dir)) {
96e7ffbd
EN
2217 /* 2. This wasn't a directory rename after all */
2218 string_list_append(&remove_from_head,
2219 head_ent->dir)->util = head_ent;
2220 strbuf_release(&head_ent->new_dir);
2221 }
2222 }
2223
2224 remove_hashmap_entries(dir_re_head, &remove_from_head);
2225 remove_hashmap_entries(dir_re_merge, &remove_from_merge);
2226
87571c3f 2227 hashmap_for_each_entry(dir_re_merge, &iter, merge_ent,
87571c3f 2228 ent /* member name */) {
96e7ffbd 2229 head_ent = dir_rename_find_entry(dir_re_head, merge_ent->dir);
34e7771b 2230 if (tree_has_path(opt->repo, merge, merge_ent->dir)) {
96e7ffbd
EN
2231 /* 2. This wasn't a directory rename after all */
2232 string_list_append(&remove_from_merge,
2233 merge_ent->dir)->util = merge_ent;
2234 } else if (head_ent &&
2235 !head_ent->non_unique_new_dir &&
2236 !merge_ent->non_unique_new_dir) {
2237 /* 3. rename/rename(1to2) */
2238 /*
2239 * We can assume it's not rename/rename(1to1) because
2240 * that was case (1), already checked above. So we
2241 * know that head_ent->new_dir and merge_ent->new_dir
2242 * are different strings.
2243 */
259ccb6c 2244 output(opt, 1, _("CONFLICT (rename/rename): "
96e7ffbd
EN
2245 "Rename directory %s->%s in %s. "
2246 "Rename directory %s->%s in %s"),
259ccb6c
EN
2247 head_ent->dir, head_ent->new_dir.buf, opt->branch1,
2248 head_ent->dir, merge_ent->new_dir.buf, opt->branch2);
96e7ffbd
EN
2249 string_list_append(&remove_from_head,
2250 head_ent->dir)->util = head_ent;
2251 strbuf_release(&head_ent->new_dir);
2252 string_list_append(&remove_from_merge,
2253 merge_ent->dir)->util = merge_ent;
2254 strbuf_release(&merge_ent->new_dir);
2255 }
2256 }
2257
2258 remove_hashmap_entries(dir_re_head, &remove_from_head);
2259 remove_hashmap_entries(dir_re_merge, &remove_from_merge);
2260}
2261
b53c5028 2262static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs)
7fe40b88
EN
2263{
2264 struct hashmap *dir_renames;
2265 struct hashmap_iter iter;
2266 struct dir_rename_entry *entry;
2267 int i;
2268
2269 /*
2270 * Typically, we think of a directory rename as all files from a
2271 * certain directory being moved to a target directory. However,
2272 * what if someone first moved two files from the original
2273 * directory in one commit, and then renamed the directory
2274 * somewhere else in a later commit? At merge time, we just know
2275 * that files from the original directory went to two different
2276 * places, and that the bulk of them ended up in the same place.
2277 * We want each directory rename to represent where the bulk of the
2278 * files from that directory end up; this function exists to find
2279 * where the bulk of the files went.
2280 *
2281 * The first loop below simply iterates through the list of file
2282 * renames, finding out how often each directory rename pair
2283 * possibility occurs.
2284 */
2285 dir_renames = xmalloc(sizeof(*dir_renames));
2286 dir_rename_init(dir_renames);
2287 for (i = 0; i < pairs->nr; ++i) {
2288 struct string_list_item *item;
2289 int *count;
2290 struct diff_filepair *pair = pairs->queue[i];
2291 char *old_dir, *new_dir;
2292
2293 /* File not part of directory rename if it wasn't renamed */
2294 if (pair->status != 'R')
2295 continue;
2296
2297 get_renamed_dir_portion(pair->one->path, pair->two->path,
2298 &old_dir, &new_dir);
2299 if (!old_dir)
2300 /* Directory didn't change at all; ignore this one. */
2301 continue;
2302
2303 entry = dir_rename_find_entry(dir_renames, old_dir);
2304 if (!entry) {
2305 entry = xmalloc(sizeof(*entry));
2306 dir_rename_entry_init(entry, old_dir);
26b455f2 2307 hashmap_put(dir_renames, &entry->ent);
7fe40b88
EN
2308 } else {
2309 free(old_dir);
2310 }
2311 item = string_list_lookup(&entry->possible_new_dirs, new_dir);
2312 if (!item) {
2313 item = string_list_insert(&entry->possible_new_dirs,
2314 new_dir);
2315 item->util = xcalloc(1, sizeof(int));
2316 } else {
2317 free(new_dir);
2318 }
2319 count = item->util;
2320 *count += 1;
2321 }
2322
2323 /*
2324 * For each directory with files moved out of it, we find out which
2325 * target directory received the most files so we can declare it to
2326 * be the "winning" target location for the directory rename. This
2327 * winner gets recorded in new_dir. If there is no winner
2328 * (multiple target directories received the same number of files),
2329 * we set non_unique_new_dir. Once we've determined the winner (or
2330 * that there is no winner), we no longer need possible_new_dirs.
2331 */
87571c3f 2332 hashmap_for_each_entry(dir_renames, &iter, entry,
87571c3f 2333 ent /* member name */) {
7fe40b88
EN
2334 int max = 0;
2335 int bad_max = 0;
2336 char *best = NULL;
2337
2338 for (i = 0; i < entry->possible_new_dirs.nr; i++) {
2339 int *count = entry->possible_new_dirs.items[i].util;
2340
2341 if (*count == max)
2342 bad_max = max;
2343 else if (*count > max) {
2344 max = *count;
2345 best = entry->possible_new_dirs.items[i].string;
2346 }
2347 }
2348 if (bad_max == max)
2349 entry->non_unique_new_dir = 1;
2350 else {
2351 assert(entry->new_dir.len == 0);
2352 strbuf_addstr(&entry->new_dir, best);
2353 }
2354 /*
2355 * The relevant directory sub-portion of the original full
2356 * filepaths were xstrndup'ed before inserting into
2357 * possible_new_dirs, and instead of manually iterating the
2358 * list and free'ing each, just lie and tell
2359 * possible_new_dirs that it did the strdup'ing so that it
2360 * will free them for us.
2361 */
2362 entry->possible_new_dirs.strdup_strings = 1;
2363 string_list_clear(&entry->possible_new_dirs, 1);
2364 }
2365
2366 return dir_renames;
2367}
2368
e95ab70a
EN
2369static struct dir_rename_entry *check_dir_renamed(const char *path,
2370 struct hashmap *dir_renames)
2371{
9da2d037 2372 char *temp = xstrdup(path);
e95ab70a 2373 char *end;
c3b9bc94 2374 struct dir_rename_entry *entry = NULL;
e95ab70a 2375
e95ab70a
EN
2376 while ((end = strrchr(temp, '/'))) {
2377 *end = '\0';
2378 entry = dir_rename_find_entry(dir_renames, temp);
2379 if (entry)
9da2d037 2380 break;
e95ab70a 2381 }
9da2d037
RS
2382 free(temp);
2383 return entry;
e95ab70a
EN
2384}
2385
2386static void compute_collisions(struct hashmap *collisions,
2387 struct hashmap *dir_renames,
2388 struct diff_queue_struct *pairs)
2389{
2390 int i;
2391
2392 /*
2393 * Multiple files can be mapped to the same path due to directory
2394 * renames done by the other side of history. Since that other
2395 * side of history could have merged multiple directories into one,
2396 * if our side of history added the same file basename to each of
2397 * those directories, then all N of them would get implicitly
2398 * renamed by the directory rename detection into the same path,
2399 * and we'd get an add/add/.../add conflict, and all those adds
2400 * from *this* side of history. This is not representable in the
2401 * index, and users aren't going to easily be able to make sense of
2402 * it. So we need to provide a good warning about what's
2403 * happening, and fall back to no-directory-rename detection
2404 * behavior for those paths.
2405 *
2406 * See testcases 9e and all of section 5 from t6043 for examples.
2407 */
2408 collision_init(collisions);
2409
2410 for (i = 0; i < pairs->nr; ++i) {
2411 struct dir_rename_entry *dir_rename_ent;
2412 struct collision_entry *collision_ent;
2413 char *new_path;
2414 struct diff_filepair *pair = pairs->queue[i];
2415
6e7e027f 2416 if (pair->status != 'A' && pair->status != 'R')
e95ab70a
EN
2417 continue;
2418 dir_rename_ent = check_dir_renamed(pair->two->path,
2419 dir_renames);
2420 if (!dir_rename_ent)
2421 continue;
2422
2423 new_path = apply_dir_rename(dir_rename_ent, pair->two->path);
2424 if (!new_path)
2425 /*
2426 * dir_rename_ent->non_unique_new_path is true, which
2427 * means there is no directory rename for us to use,
2428 * which means it won't cause us any additional
2429 * collisions.
2430 */
2431 continue;
2432 collision_ent = collision_find_entry(collisions, new_path);
2433 if (!collision_ent) {
ca56dadb 2434 CALLOC_ARRAY(collision_ent, 1);
d22245a2
EW
2435 hashmap_entry_init(&collision_ent->ent,
2436 strhash(new_path));
26b455f2 2437 hashmap_put(collisions, &collision_ent->ent);
e95ab70a
EN
2438 collision_ent->target_file = new_path;
2439 } else {
2440 free(new_path);
2441 }
2442 string_list_insert(&collision_ent->source_files,
2443 pair->two->path);
2444 }
2445}
2446
259ccb6c 2447static char *check_for_directory_rename(struct merge_options *opt,
f6f77559
EN
2448 const char *path,
2449 struct tree *tree,
2450 struct hashmap *dir_renames,
2451 struct hashmap *dir_rename_exclusions,
2452 struct hashmap *collisions,
2453 int *clean_merge)
2454{
2455 char *new_path = NULL;
2456 struct dir_rename_entry *entry = check_dir_renamed(path, dir_renames);
2457 struct dir_rename_entry *oentry = NULL;
2458
2459 if (!entry)
2460 return new_path;
2461
2462 /*
2463 * This next part is a little weird. We do not want to do an
2464 * implicit rename into a directory we renamed on our side, because
2465 * that will result in a spurious rename/rename(1to2) conflict. An
2466 * example:
2467 * Base commit: dumbdir/afile, otherdir/bfile
2468 * Side 1: smrtdir/afile, otherdir/bfile
2469 * Side 2: dumbdir/afile, dumbdir/bfile
2470 * Here, while working on Side 1, we could notice that otherdir was
2471 * renamed/merged to dumbdir, and change the diff_filepair for
2472 * otherdir/bfile into a rename into dumbdir/bfile. However, Side
2473 * 2 will notice the rename from dumbdir to smrtdir, and do the
2474 * transitive rename to move it from dumbdir/bfile to
2475 * smrtdir/bfile. That gives us bfile in dumbdir vs being in
2476 * smrtdir, a rename/rename(1to2) conflict. We really just want
2477 * the file to end up in smrtdir. And the way to achieve that is
2478 * to not let Side1 do the rename to dumbdir, since we know that is
2479 * the source of one of our directory renames.
2480 *
2481 * That's why oentry and dir_rename_exclusions is here.
2482 *
2483 * As it turns out, this also prevents N-way transient rename
2484 * confusion; See testcases 9c and 9d of t6043.
2485 */
2486 oentry = dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);
2487 if (oentry) {
259ccb6c 2488 output(opt, 1, _("WARNING: Avoiding applying %s -> %s rename "
f6f77559
EN
2489 "to %s, because %s itself was renamed."),
2490 entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);
2491 } else {
259ccb6c 2492 new_path = handle_path_level_conflicts(opt, path, entry,
f6f77559
EN
2493 collisions, tree);
2494 *clean_merge &= (new_path != NULL);
2495 }
2496
2497 return new_path;
2498}
2499
259ccb6c 2500static void apply_directory_rename_modifications(struct merge_options *opt,
9c0743fe
EN
2501 struct diff_filepair *pair,
2502 char *new_path,
2503 struct rename *re,
2504 struct tree *tree,
2505 struct tree *o_tree,
2506 struct tree *a_tree,
2507 struct tree *b_tree,
b53c5028 2508 struct string_list *entries)
9c0743fe
EN
2509{
2510 struct string_list_item *item;
2511 int stage = (tree == a_tree ? 2 : 3);
18797a3b 2512 int update_wd;
9c0743fe
EN
2513
2514 /*
2515 * In all cases where we can do directory rename detection,
2516 * unpack_trees() will have read pair->two->path into the
2517 * index and the working copy. We need to remove it so that
2518 * we can instead place it at new_path. It is guaranteed to
2519 * not be untracked (unpack_trees() would have errored out
2520 * saying the file would have been overwritten), but it might
2521 * be dirty, though.
2522 */
259ccb6c 2523 update_wd = !was_dirty(opt, pair->two->path);
18797a3b 2524 if (!update_wd)
259ccb6c 2525 output(opt, 1, _("Refusing to lose dirty file at %s"),
18797a3b 2526 pair->two->path);
259ccb6c 2527 remove_file(opt, 1, pair->two->path, !update_wd);
9c0743fe
EN
2528
2529 /* Find or create a new re->dst_entry */
2530 item = string_list_lookup(entries, new_path);
2531 if (item) {
2532 /*
2533 * Since we're renaming on this side of history, and it's
2534 * due to a directory rename on the other side of history
2535 * (which we only allow when the directory in question no
2536 * longer exists on the other side of history), the
2537 * original entry for re->dst_entry is no longer
2538 * necessary...
2539 */
2540 re->dst_entry->processed = 1;
2541
2542 /*
2543 * ...because we'll be using this new one.
2544 */
2545 re->dst_entry = item->util;
2546 } else {
2547 /*
2548 * re->dst_entry is for the before-dir-rename path, and we
2549 * need it to hold information for the after-dir-rename
2550 * path. Before creating a new entry, we need to mark the
2551 * old one as unnecessary (...unless it is shared by
2552 * src_entry, i.e. this didn't use to be a rename, in which
2553 * case we can just allow the normal processing to happen
2554 * for it).
2555 */
2556 if (pair->status == 'R')
2557 re->dst_entry->processed = 1;
2558
34e7771b 2559 re->dst_entry = insert_stage_data(opt->repo, new_path,
9c0743fe
EN
2560 o_tree, a_tree, b_tree,
2561 entries);
2562 item = string_list_insert(entries, new_path);
2563 item->util = re->dst_entry;
2564 }
2565
2566 /*
2567 * Update the stage_data with the information about the path we are
2568 * moving into place. That slot will be empty and available for us
2569 * to write to because of the collision checks in
2570 * handle_path_level_conflicts(). In other words,
2571 * re->dst_entry->stages[stage].oid will be the null_oid, so it's
2572 * open for us to write to.
2573 *
2574 * It may be tempting to actually update the index at this point as
2575 * well, using update_stages_for_stage_data(), but as per the big
2576 * "NOTE" in update_stages(), doing so will modify the current
2577 * in-memory index which will break calls to would_lose_untracked()
2578 * that we need to make. Instead, we need to just make sure that
8ebe7b05 2579 * the various handle_rename_*() functions update the index
9c0743fe
EN
2580 * explicitly rather than relying on unpack_trees() to have done it.
2581 */
50ddb089
NTND
2582 get_tree_entry(opt->repo,
2583 &tree->object.oid,
9c0743fe
EN
2584 pair->two->path,
2585 &re->dst_entry->stages[stage].oid,
2586 &re->dst_entry->stages[stage].mode);
2587
6d169fd3
EN
2588 /*
2589 * Record the original change status (or 'type' of change). If it
2590 * was originally an add ('A'), this lets us differentiate later
2591 * between a RENAME_DELETE conflict and RENAME_VIA_DIR (they
2592 * otherwise look the same). If it was originally a rename ('R'),
2593 * this lets us remember and report accurately about the transitive
2594 * renaming that occurred via the directory rename detection. Also,
2595 * record the original destination name.
2596 */
2597 re->dir_rename_original_type = pair->status;
2598 re->dir_rename_original_dest = pair->two->path;
2599
9c0743fe
EN
2600 /*
2601 * We don't actually look at pair->status again, but it seems
2602 * pedagogically correct to adjust it.
2603 */
2604 pair->status = 'R';
2605
2606 /*
2607 * Finally, record the new location.
2608 */
2609 pair->two->path = new_path;
2610}
2611
e5257b2a
EN
2612/*
2613 * Get information of all renames which occurred in 'pairs', making use of
2614 * any implicit directory renames inferred from the other side of history.
2615 * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')
2616 * to be able to associate the correct cache entries with the rename
2617 * information; tree is always equal to either a_tree or b_tree.
2618 */
259ccb6c 2619static struct string_list *get_renames(struct merge_options *opt,
c336ab85 2620 const char *branch,
e5257b2a 2621 struct diff_queue_struct *pairs,
e95ab70a 2622 struct hashmap *dir_renames,
f6f77559 2623 struct hashmap *dir_rename_exclusions,
e5257b2a
EN
2624 struct tree *tree,
2625 struct tree *o_tree,
2626 struct tree *a_tree,
2627 struct tree *b_tree,
f6f77559
EN
2628 struct string_list *entries,
2629 int *clean_merge)
e5257b2a
EN
2630{
2631 int i;
e95ab70a
EN
2632 struct hashmap collisions;
2633 struct hashmap_iter iter;
2634 struct collision_entry *e;
e5257b2a
EN
2635 struct string_list *renames;
2636
e95ab70a 2637 compute_collisions(&collisions, dir_renames, pairs);
ca56dadb 2638 CALLOC_ARRAY(renames, 1);
e5257b2a
EN
2639
2640 for (i = 0; i < pairs->nr; ++i) {
9ba91557
EN
2641 struct string_list_item *item;
2642 struct rename *re;
e5257b2a 2643 struct diff_filepair *pair = pairs->queue[i];
f6f77559 2644 char *new_path; /* non-NULL only with directory renames */
9ba91557 2645
6e7e027f 2646 if (pair->status != 'A' && pair->status != 'R') {
9ba91557
EN
2647 diff_free_filepair(pair);
2648 continue;
2649 }
259ccb6c 2650 new_path = check_for_directory_rename(opt, pair->two->path, tree,
f6f77559
EN
2651 dir_renames,
2652 dir_rename_exclusions,
2653 &collisions,
2654 clean_merge);
2655 if (pair->status != 'R' && !new_path) {
2656 diff_free_filepair(pair);
2657 continue;
2658 }
2659
9ba91557
EN
2660 re = xmalloc(sizeof(*re));
2661 re->processed = 0;
2662 re->pair = pair;
c336ab85 2663 re->branch = branch;
6d169fd3
EN
2664 re->dir_rename_original_type = '\0';
2665 re->dir_rename_original_dest = NULL;
9ba91557
EN
2666 item = string_list_lookup(entries, re->pair->one->path);
2667 if (!item)
34e7771b
NTND
2668 re->src_entry = insert_stage_data(opt->repo,
2669 re->pair->one->path,
9ba91557
EN
2670 o_tree, a_tree, b_tree, entries);
2671 else
2672 re->src_entry = item->util;
2673
2674 item = string_list_lookup(entries, re->pair->two->path);
2675 if (!item)
34e7771b
NTND
2676 re->dst_entry = insert_stage_data(opt->repo,
2677 re->pair->two->path,
9ba91557
EN
2678 o_tree, a_tree, b_tree, entries);
2679 else
2680 re->dst_entry = item->util;
2681 item = string_list_insert(renames, pair->one->path);
2682 item->util = re;
9c0743fe 2683 if (new_path)
259ccb6c 2684 apply_directory_rename_modifications(opt, pair, new_path,
9c0743fe
EN
2685 re, tree, o_tree,
2686 a_tree, b_tree,
b53c5028 2687 entries);
9ba91557 2688 }
e95ab70a 2689
87571c3f 2690 hashmap_for_each_entry(&collisions, &iter, e,
87571c3f 2691 ent /* member name */) {
e95ab70a
EN
2692 free(e->target_file);
2693 string_list_clear(&e->source_files, 0);
2694 }
6da1a258 2695 hashmap_clear_and_free(&collisions, struct collision_entry, ent);
9ba91557
EN
2696 return renames;
2697}
2698
259ccb6c 2699static int process_renames(struct merge_options *opt,
8a2fce18
MV
2700 struct string_list *a_renames,
2701 struct string_list *b_renames)
9047ebbc
MV
2702{
2703 int clean_merge = 1, i, j;
183113a5
TF
2704 struct string_list a_by_dst = STRING_LIST_INIT_NODUP;
2705 struct string_list b_by_dst = STRING_LIST_INIT_NODUP;
9047ebbc
MV
2706 const struct rename *sre;
2707
816147e7
EN
2708 /*
2709 * FIXME: As string-list.h notes, it's O(n^2) to build a sorted
2710 * string_list one-by-one, but O(n log n) to build it unsorted and
2711 * then sort it. Note that as we build the list, we do not need to
2712 * check if the existing destination path is already in the list,
2713 * because the structure of diffcore_rename guarantees we won't
2714 * have duplicates.
2715 */
9047ebbc
MV
2716 for (i = 0; i < a_renames->nr; i++) {
2717 sre = a_renames->items[i].util;
78a395d3 2718 string_list_insert(&a_by_dst, sre->pair->two->path)->util
0a6b8712 2719 = (void *)sre;
9047ebbc
MV
2720 }
2721 for (i = 0; i < b_renames->nr; i++) {
2722 sre = b_renames->items[i].util;
78a395d3 2723 string_list_insert(&b_by_dst, sre->pair->two->path)->util
0a6b8712 2724 = (void *)sre;
9047ebbc
MV
2725 }
2726
2727 for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
8e24cbae 2728 struct string_list *renames1, *renames2Dst;
9047ebbc 2729 struct rename *ren1 = NULL, *ren2 = NULL;
9047ebbc 2730 const char *ren1_src, *ren1_dst;
461f5041 2731 struct string_list_item *lookup;
9047ebbc
MV
2732
2733 if (i >= a_renames->nr) {
9047ebbc
MV
2734 ren2 = b_renames->items[j++].util;
2735 } else if (j >= b_renames->nr) {
9047ebbc
MV
2736 ren1 = a_renames->items[i++].util;
2737 } else {
8e24cbae
BK
2738 int compare = strcmp(a_renames->items[i].string,
2739 b_renames->items[j].string);
9047ebbc
MV
2740 if (compare <= 0)
2741 ren1 = a_renames->items[i++].util;
2742 if (compare >= 0)
2743 ren2 = b_renames->items[j++].util;
2744 }
2745
2746 /* TODO: refactor, so that 1/2 are not needed */
2747 if (ren1) {
2748 renames1 = a_renames;
9047ebbc 2749 renames2Dst = &b_by_dst;
9047ebbc 2750 } else {
9047ebbc 2751 renames1 = b_renames;
9047ebbc 2752 renames2Dst = &a_by_dst;
35d803bc 2753 SWAP(ren2, ren1);
9047ebbc 2754 }
9047ebbc 2755
9047ebbc
MV
2756 if (ren1->processed)
2757 continue;
2758 ren1->processed = 1;
9047ebbc 2759 ren1->dst_entry->processed = 1;
7769a75e
EN
2760 /* BUG: We should only mark src_entry as processed if we
2761 * are not dealing with a rename + add-source case.
2762 */
9047ebbc 2763 ren1->src_entry->processed = 1;
9047ebbc
MV
2764
2765 ren1_src = ren1->pair->one->path;
2766 ren1_dst = ren1->pair->two->path;
2767
2768 if (ren2) {
461f5041 2769 /* One file renamed on both sides */
9047ebbc
MV
2770 const char *ren2_src = ren2->pair->one->path;
2771 const char *ren2_dst = ren2->pair->two->path;
4f66dade 2772 enum rename_type rename_type;
9047ebbc 2773 if (strcmp(ren1_src, ren2_src) != 0)
033abf97 2774 BUG("ren1_src != ren2_src");
9047ebbc
MV
2775 ren2->dst_entry->processed = 1;
2776 ren2->processed = 1;
2777 if (strcmp(ren1_dst, ren2_dst) != 0) {
4f66dade 2778 rename_type = RENAME_ONE_FILE_TO_TWO;
461f5041 2779 clean_merge = 0;
9047ebbc 2780 } else {
4f66dade 2781 rename_type = RENAME_ONE_FILE_TO_ONE;
7769a75e
EN
2782 /* BUG: We should only remove ren1_src in
2783 * the base stage (think of rename +
2784 * add-source cases).
2785 */
259ccb6c 2786 remove_file(opt, 1, ren1_src, 1);
b8ddf164
EN
2787 update_entry(ren1->dst_entry,
2788 ren1->pair->one,
2789 ren1->pair->two,
2790 ren2->pair->two);
9047ebbc 2791 }
c336ab85 2792 setup_rename_conflict_info(rename_type, opt, ren1, ren2);
461f5041
EN
2793 } else if ((lookup = string_list_lookup(renames2Dst, ren1_dst))) {
2794 /* Two different files renamed to the same thing */
2795 char *ren2_dst;
2796 ren2 = lookup->util;
2797 ren2_dst = ren2->pair->two->path;
2798 if (strcmp(ren1_dst, ren2_dst) != 0)
033abf97 2799 BUG("ren1_dst != ren2_dst");
461f5041
EN
2800
2801 clean_merge = 0;
2802 ren2->processed = 1;
2803 /*
2804 * BUG: We should only mark src_entry as processed
2805 * if we are not dealing with a rename + add-source
2806 * case.
2807 */
2808 ren2->src_entry->processed = 1;
2809
2810 setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,
c336ab85 2811 opt, ren1, ren2);
9047ebbc
MV
2812 } else {
2813 /* Renamed in 1, maybe changed in 2 */
9047ebbc
MV
2814 /* we only use sha1 and mode of these */
2815 struct diff_filespec src_other, dst_other;
41d70bd6 2816 int try_merge;
9047ebbc 2817
41d70bd6
EN
2818 /*
2819 * unpack_trees loads entries from common-commit
2820 * into stage 1, from head-commit into stage 2, and
2821 * from merge-commit into stage 3. We keep track
2822 * of which side corresponds to the rename.
2823 */
2824 int renamed_stage = a_renames == renames1 ? 2 : 3;
2825 int other_stage = a_renames == renames1 ? 3 : 2;
9047ebbc 2826
3585d0ea
EN
2827 /*
2828 * Directory renames have a funny corner case...
2829 */
2830 int renamed_to_self = !strcmp(ren1_src, ren1_dst);
2831
7769a75e
EN
2832 /* BUG: We should only remove ren1_src in the base
2833 * stage and in other_stage (think of rename +
2834 * add-source case).
2835 */
3585d0ea
EN
2836 if (!renamed_to_self)
2837 remove_file(opt, 1, ren1_src,
2838 renamed_stage == 2 ||
2839 !was_tracked(opt, ren1_src));
9047ebbc 2840
fd429e98 2841 oidcpy(&src_other.oid,
2842 &ren1->src_entry->stages[other_stage].oid);
41d70bd6 2843 src_other.mode = ren1->src_entry->stages[other_stage].mode;
fd429e98 2844 oidcpy(&dst_other.oid,
2845 &ren1->dst_entry->stages[other_stage].oid);
41d70bd6 2846 dst_other.mode = ren1->dst_entry->stages[other_stage].mode;
9047ebbc
MV
2847 try_merge = 0;
2848
14228447 2849 if (oideq(&src_other.oid, null_oid()) &&
6d169fd3 2850 ren1->dir_rename_original_type == 'A') {
5455c338 2851 setup_rename_conflict_info(RENAME_VIA_DIR,
c336ab85 2852 opt, ren1, NULL);
3585d0ea
EN
2853 } else if (renamed_to_self) {
2854 setup_rename_conflict_info(RENAME_NORMAL,
2855 opt, ren1, NULL);
14228447 2856 } else if (oideq(&src_other.oid, null_oid())) {
4f66dade 2857 setup_rename_conflict_info(RENAME_DELETE,
c336ab85 2858 opt, ren1, NULL);
d5af5105 2859 } else if ((dst_other.mode == ren1->pair->two->mode) &&
763a59e7 2860 oideq(&dst_other.oid, &ren1->pair->two->oid)) {
35a74abf
EN
2861 /*
2862 * Added file on the other side identical to
2863 * the file being renamed: clean merge.
2864 * Also, there is no need to overwrite the
2865 * file already in the working copy, so call
2866 * update_file_flags() instead of
2867 * update_file().
2868 */
259ccb6c 2869 if (update_file_flags(opt,
8daec1df 2870 ren1->pair->two,
75456f96
JS
2871 ren1_dst,
2872 1, /* update_cache */
2873 0 /* update_wd */))
2874 clean_merge = -1;
14228447 2875 } else if (!oideq(&dst_other.oid, null_oid())) {
7f867165
EN
2876 /*
2877 * Probably not a clean merge, but it's
2878 * premature to set clean_merge to 0 here,
2879 * because if the rename merges cleanly and
2880 * the merge exactly matches the newly added
2881 * file, then the merge will be clean.
2882 */
2883 setup_rename_conflict_info(RENAME_ADD,
c336ab85 2884 opt, ren1, NULL);
9047ebbc
MV
2885 } else
2886 try_merge = 1;
2887
75456f96
JS
2888 if (clean_merge < 0)
2889 goto cleanup_and_return;
9047ebbc 2890 if (try_merge) {
e3de888c 2891 struct diff_filespec *o, *a, *b;
9047ebbc
MV
2892 src_other.path = (char *)ren1_src;
2893
e3de888c 2894 o = ren1->pair->one;
9047ebbc
MV
2895 if (a_renames == renames1) {
2896 a = ren1->pair->two;
2897 b = &src_other;
2898 } else {
2899 b = ren1->pair->two;
2900 a = &src_other;
2901 }
e3de888c 2902 update_entry(ren1->dst_entry, o, a, b);
4f66dade 2903 setup_rename_conflict_info(RENAME_NORMAL,
c336ab85 2904 opt, ren1, NULL);
9047ebbc
MV
2905 }
2906 }
2907 }
75456f96 2908cleanup_and_return:
9047ebbc
MV
2909 string_list_clear(&a_by_dst, 0);
2910 string_list_clear(&b_by_dst, 0);
2911
2912 return clean_merge;
2913}
2914
f172589e
EN
2915struct rename_info {
2916 struct string_list *head_renames;
2917 struct string_list *merge_renames;
2918};
2919
7fe40b88
EN
2920static void initial_cleanup_rename(struct diff_queue_struct *pairs,
2921 struct hashmap *dir_renames)
ffc16c49 2922{
7fe40b88
EN
2923 struct hashmap_iter iter;
2924 struct dir_rename_entry *e;
2925
87571c3f 2926 hashmap_for_each_entry(dir_renames, &iter, e,
87571c3f 2927 ent /* member name */) {
7fe40b88
EN
2928 free(e->dir);
2929 strbuf_release(&e->new_dir);
2930 /* possible_new_dirs already cleared in get_directory_renames */
2931 }
6da1a258 2932 hashmap_clear_and_free(dir_renames, struct dir_rename_entry, ent);
7fe40b88
EN
2933 free(dir_renames);
2934
ffc16c49
EN
2935 free(pairs->queue);
2936 free(pairs);
2937}
2938
259ccb6c 2939static int detect_and_process_renames(struct merge_options *opt,
8ebe7b05
EN
2940 struct tree *common,
2941 struct tree *head,
2942 struct tree *merge,
2943 struct string_list *entries,
2944 struct rename_info *ri)
f172589e 2945{
e5257b2a 2946 struct diff_queue_struct *head_pairs, *merge_pairs;
7fe40b88 2947 struct hashmap *dir_re_head, *dir_re_merge;
f6f77559 2948 int clean = 1;
e5257b2a 2949
3992ff0c
EN
2950 ri->head_renames = NULL;
2951 ri->merge_renames = NULL;
2952
259ccb6c 2953 if (!merge_detect_rename(opt))
3992ff0c
EN
2954 return 1;
2955
259ccb6c
EN
2956 head_pairs = get_diffpairs(opt, common, head);
2957 merge_pairs = get_diffpairs(opt, common, merge);
e5257b2a 2958
8e012516
DS
2959 if ((opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE) ||
2960 (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT &&
5bf7e577 2961 !opt->priv->call_depth)) {
b53c5028
JK
2962 dir_re_head = get_directory_renames(head_pairs);
2963 dir_re_merge = get_directory_renames(merge_pairs);
7fe40b88 2964
259ccb6c 2965 handle_directory_level_conflicts(opt,
5fdddd9b
EN
2966 dir_re_head, head,
2967 dir_re_merge, merge);
2968 } else {
2969 dir_re_head = xmalloc(sizeof(*dir_re_head));
2970 dir_re_merge = xmalloc(sizeof(*dir_re_merge));
2971 dir_rename_init(dir_re_head);
2972 dir_rename_init(dir_re_merge);
2973 }
96e7ffbd 2974
c336ab85 2975 ri->head_renames = get_renames(opt, opt->branch1, head_pairs,
f6f77559
EN
2976 dir_re_merge, dir_re_head, head,
2977 common, head, merge, entries,
2978 &clean);
2979 if (clean < 0)
2980 goto cleanup;
c336ab85 2981 ri->merge_renames = get_renames(opt, opt->branch2, merge_pairs,
f6f77559
EN
2982 dir_re_head, dir_re_merge, merge,
2983 common, head, merge, entries,
2984 &clean);
2985 if (clean < 0)
2986 goto cleanup;
259ccb6c 2987 clean &= process_renames(opt, ri->head_renames, ri->merge_renames);
f6f77559
EN
2988
2989cleanup:
e5257b2a
EN
2990 /*
2991 * Some cleanup is deferred until cleanup_renames() because the
2992 * data structures are still needed and referenced in
2993 * process_entry(). But there are a few things we can free now.
2994 */
7fe40b88
EN
2995 initial_cleanup_rename(head_pairs, dir_re_head);
2996 initial_cleanup_rename(merge_pairs, dir_re_merge);
e5257b2a
EN
2997
2998 return clean;
f172589e
EN
2999}
3000
ffc16c49 3001static void final_cleanup_rename(struct string_list *rename)
f172589e 3002{
9cfee25a
EN
3003 const struct rename *re;
3004 int i;
f172589e 3005
afe8a907 3006 if (!rename)
3992ff0c
EN
3007 return;
3008
9cfee25a
EN
3009 for (i = 0; i < rename->nr; i++) {
3010 re = rename->items[i].util;
3011 diff_free_filepair(re->pair);
3012 }
3013 string_list_clear(rename, 1);
3014 free(rename);
3015}
3016
ffc16c49 3017static void final_cleanup_renames(struct rename_info *re_info)
9cfee25a 3018{
ffc16c49
EN
3019 final_cleanup_rename(re_info->head_renames);
3020 final_cleanup_rename(re_info->merge_renames);
f172589e
EN
3021}
3022
259ccb6c 3023static int read_oid_strbuf(struct merge_options *opt,
d90e759f
EN
3024 const struct object_id *oid,
3025 struct strbuf *dst)
331a1838
EB
3026{
3027 void *buf;
3028 enum object_type type;
3029 unsigned long size;
bc726bd0 3030 buf = repo_read_object_file(the_repository, oid, &type, &size);
331a1838 3031 if (!buf)
259ccb6c 3032 return err(opt, _("cannot read object %s"), oid_to_hex(oid));
331a1838
EB
3033 if (type != OBJ_BLOB) {
3034 free(buf);
259ccb6c 3035 return err(opt, _("object %s is not a blob"), oid_to_hex(oid));
331a1838
EB
3036 }
3037 strbuf_attach(dst, buf, size, size + 1);
3038 return 0;
3039}
3040
bc9204d4 3041static int blob_unchanged(struct merge_options *opt,
8daec1df
EN
3042 const struct diff_filespec *o,
3043 const struct diff_filespec *a,
3e7589b7 3044 int renormalize, const char *path)
331a1838 3045{
93a02c55
EN
3046 struct strbuf obuf = STRBUF_INIT;
3047 struct strbuf abuf = STRBUF_INIT;
331a1838 3048 int ret = 0; /* assume changed for safety */
847a9e5d 3049 struct index_state *idx = opt->repo->index;
331a1838 3050
8daec1df 3051 if (a->mode != o->mode)
72fac66b 3052 return 0;
763a59e7 3053 if (oideq(&o->oid, &a->oid))
331a1838 3054 return 1;
3e7589b7 3055 if (!renormalize)
331a1838
EB
3056 return 0;
3057
8daec1df
EN
3058 if (read_oid_strbuf(opt, &o->oid, &obuf) ||
3059 read_oid_strbuf(opt, &a->oid, &abuf))
331a1838
EB
3060 goto error_return;
3061 /*
3062 * Note: binary | is used so that both renormalizations are
3063 * performed. Comparison can be skipped if both files are
3064 * unchanged since their sha1s have already been compared.
3065 */
93a02c55
EN
3066 if (renormalize_buffer(idx, path, obuf.buf, obuf.len, &obuf) |
3067 renormalize_buffer(idx, path, abuf.buf, abuf.len, &abuf))
3068 ret = (obuf.len == abuf.len && !memcmp(obuf.buf, abuf.buf, obuf.len));
331a1838
EB
3069
3070error_return:
93a02c55
EN
3071 strbuf_release(&obuf);
3072 strbuf_release(&abuf);
331a1838
EB
3073 return ret;
3074}
3075
259ccb6c 3076static int handle_modify_delete(struct merge_options *opt,
d90e759f 3077 const char *path,
8daec1df
EN
3078 const struct diff_filespec *o,
3079 const struct diff_filespec *a,
3080 const struct diff_filespec *b)
5e3ce663 3081{
b26d87f2 3082 const char *modify_branch, *delete_branch;
8daec1df 3083 const struct diff_filespec *changed;
b26d87f2 3084
8daec1df 3085 if (is_valid(a)) {
259ccb6c
EN
3086 modify_branch = opt->branch1;
3087 delete_branch = opt->branch2;
8daec1df 3088 changed = a;
b26d87f2 3089 } else {
259ccb6c
EN
3090 modify_branch = opt->branch2;
3091 delete_branch = opt->branch1;
8daec1df 3092 changed = b;
b26d87f2
MM
3093 }
3094
259ccb6c 3095 return handle_change_delete(opt,
b26d87f2 3096 path, NULL,
8daec1df 3097 o, changed,
b26d87f2 3098 modify_branch, delete_branch,
75456f96 3099 _("modify"), _("modified"));
5e3ce663
EN
3100}
3101
e62d1123
EN
3102static int handle_content_merge(struct merge_file_info *mfi,
3103 struct merge_options *opt,
d9573556
EN
3104 const char *path,
3105 int is_dirty,
8daec1df
EN
3106 const struct diff_filespec *o,
3107 const struct diff_filespec *a,
3108 const struct diff_filespec *b,
043622b2 3109 struct rename_conflict_info *ci)
0c4918d1 3110{
55653a68 3111 const char *reason = _("content");
4ab9a157 3112 unsigned df_conflict_remains = 0;
0c4918d1 3113
8daec1df 3114 if (!is_valid(o))
55653a68 3115 reason = _("add/add");
8daec1df
EN
3116
3117 assert(o->path && a->path && b->path);
5bf7e577 3118 if (ci && dir_in_way(opt->repo->index, path, !opt->priv->call_depth,
8daec1df
EN
3119 S_ISGITLINK(ci->ren1->pair->two->mode)))
3120 df_conflict_remains = 1;
3121
3122 if (merge_mode_and_contents(opt, o, a, b, path,
259ccb6c 3123 opt->branch1, opt->branch2,
5bf7e577 3124 opt->priv->call_depth * 2, mfi))
3c8a51e8 3125 return -1;
4ab9a157 3126
1de70dbd
EN
3127 /*
3128 * We can skip updating the working tree file iff:
3129 * a) The merge is clean
3130 * b) The merge matches what was in HEAD (content, mode, pathname)
3131 * c) The target path is usable (i.e. not involved in D/F conflict)
3132 */
e62d1123 3133 if (mfi->clean && was_tracked_and_matches(opt, path, &mfi->blob) &&
1de70dbd 3134 !df_conflict_remains) {
2b75fb60
EN
3135 int pos;
3136 struct cache_entry *ce;
3137
259ccb6c 3138 output(opt, 3, _("Skipped %s (merged same as existing)"), path);
e62d1123 3139 if (add_cacheinfo(opt, &mfi->blob, path,
5bf7e577 3140 0, (!opt->priv->call_depth && !is_dirty), 0))
1de70dbd 3141 return -1;
2b75fb60
EN
3142 /*
3143 * However, add_cacheinfo() will delete the old cache entry
3144 * and add a new one. We need to copy over any skip_worktree
3145 * flag to avoid making the file appear as if it were
3146 * deleted by the user.
3147 */
5bf7e577
EN
3148 pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
3149 ce = opt->priv->orig_index.cache[pos];
2b75fb60 3150 if (ce_skip_worktree(ce)) {
259ccb6c
EN
3151 pos = index_name_pos(opt->repo->index, path, strlen(path));
3152 ce = opt->repo->index->cache[pos];
2b75fb60
EN
3153 ce->ce_flags |= CE_SKIP_WORKTREE;
3154 }
e62d1123 3155 return mfi->clean;
05cf21eb 3156 }
0c4918d1 3157
e62d1123
EN
3158 if (!mfi->clean) {
3159 if (S_ISGITLINK(mfi->blob.mode))
55653a68 3160 reason = _("submodule");
259ccb6c 3161 output(opt, 1, _("CONFLICT (%s): Merge conflict in %s"),
0c4918d1 3162 reason, path);
043622b2 3163 if (ci && !df_conflict_remains)
8daec1df 3164 if (update_stages(opt, path, o, a, b))
75456f96 3165 return -1;
0c4918d1
EN
3166 }
3167
bd42380e 3168 if (df_conflict_remains || is_dirty) {
3d6b8e88 3169 char *new_path;
5bf7e577 3170 if (opt->priv->call_depth) {
259ccb6c 3171 remove_file_from_index(opt->repo->index, path);
51931bf0 3172 } else {
e62d1123 3173 if (!mfi->clean) {
8daec1df 3174 if (update_stages(opt, path, o, a, b))
75456f96
JS
3175 return -1;
3176 } else {
259ccb6c 3177 int file_from_stage2 = was_tracked(opt, path);
51931bf0 3178
259ccb6c 3179 if (update_stages(opt, path, NULL,
e62d1123
EN
3180 file_from_stage2 ? &mfi->blob : NULL,
3181 file_from_stage2 ? NULL : &mfi->blob))
75456f96 3182 return -1;
51931bf0
EN
3183 }
3184
3185 }
c336ab85 3186 new_path = unique_path(opt, path, ci->ren1->branch);
bd42380e 3187 if (is_dirty) {
259ccb6c 3188 output(opt, 1, _("Refusing to lose dirty file at %s"),
bd42380e
EN
3189 path);
3190 }
259ccb6c 3191 output(opt, 1, _("Adding as %s instead"), new_path);
e62d1123 3192 if (update_file(opt, 0, &mfi->blob, new_path)) {
75456f96
JS
3193 free(new_path);
3194 return -1;
3195 }
3d6b8e88 3196 free(new_path);
e62d1123
EN
3197 mfi->clean = 0;
3198 } else if (update_file(opt, mfi->clean, &mfi->blob, path))
75456f96 3199 return -1;
e62d1123 3200 return !is_dirty && mfi->clean;
0c4918d1
EN
3201}
3202
259ccb6c 3203static int handle_rename_normal(struct merge_options *opt,
8ebe7b05 3204 const char *path,
8daec1df
EN
3205 const struct diff_filespec *o,
3206 const struct diff_filespec *a,
3207 const struct diff_filespec *b,
8ebe7b05 3208 struct rename_conflict_info *ci)
64b1abe9 3209{
8c8e5bd6 3210 struct rename *ren = ci->ren1;
e62d1123 3211 struct merge_file_info mfi;
8c8e5bd6 3212 int clean;
8c8e5bd6 3213
64b1abe9 3214 /* Merge the content and write it out */
8c8e5bd6
EN
3215 clean = handle_content_merge(&mfi, opt, path, was_dirty(opt, path),
3216 o, a, b, ci);
3217
8e012516
DS
3218 if (clean &&
3219 opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT &&
8c8e5bd6
EN
3220 ren->dir_rename_original_dest) {
3221 if (update_stages(opt, path,
3585d0ea 3222 &mfi.blob, &mfi.blob, &mfi.blob))
8c8e5bd6
EN
3223 return -1;
3224 clean = 0; /* not clean, but conflicted */
3225 }
3226 return clean;
3227}
3228
3229static void dir_rename_warning(const char *msg,
3230 int is_add,
3231 int clean,
3232 struct merge_options *opt,
3233 struct rename *ren)
3234{
3235 const char *other_branch;
3236 other_branch = (ren->branch == opt->branch1 ?
3237 opt->branch2 : opt->branch1);
3238 if (is_add) {
3239 output(opt, clean ? 2 : 1, msg,
3240 ren->pair->one->path, ren->branch,
3241 other_branch, ren->pair->two->path);
3242 return;
3243 }
3244 output(opt, clean ? 2 : 1, msg,
3245 ren->pair->one->path, ren->dir_rename_original_dest, ren->branch,
3246 other_branch, ren->pair->two->path);
3247}
3248static int warn_about_dir_renamed_entries(struct merge_options *opt,
3249 struct rename *ren)
3250{
3251 const char *msg;
3252 int clean = 1, is_add;
3253
3254 if (!ren)
3255 return clean;
3256
3257 /* Return early if ren was not affected/created by a directory rename */
3258 if (!ren->dir_rename_original_dest)
3259 return clean;
3260
3261 /* Sanity checks */
8e012516 3262 assert(opt->detect_directory_renames > MERGE_DIRECTORY_RENAMES_NONE);
8c8e5bd6
EN
3263 assert(ren->dir_rename_original_type == 'A' ||
3264 ren->dir_rename_original_type == 'R');
3265
3266 /* Check whether to treat directory renames as a conflict */
8e012516 3267 clean = (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE);
8c8e5bd6
EN
3268
3269 is_add = (ren->dir_rename_original_type == 'A');
3270 if (ren->dir_rename_original_type == 'A' && clean) {
3271 msg = _("Path updated: %s added in %s inside a "
3272 "directory that was renamed in %s; moving it to %s.");
3273 } else if (ren->dir_rename_original_type == 'A' && !clean) {
3274 msg = _("CONFLICT (file location): %s added in %s "
3275 "inside a directory that was renamed in %s, "
3276 "suggesting it should perhaps be moved to %s.");
3277 } else if (ren->dir_rename_original_type == 'R' && clean) {
3278 msg = _("Path updated: %s renamed to %s in %s, inside a "
3279 "directory that was renamed in %s; moving it to %s.");
3280 } else if (ren->dir_rename_original_type == 'R' && !clean) {
3281 msg = _("CONFLICT (file location): %s renamed to %s in %s, "
3282 "inside a directory that was renamed in %s, "
3283 "suggesting it should perhaps be moved to %s.");
3284 } else {
3285 BUG("Impossible dir_rename_original_type/clean combination");
3286 }
3287 dir_rename_warning(msg, is_add, clean, opt, ren);
3288
3289 return clean;
0c4918d1
EN
3290}
3291
9047ebbc 3292/* Per entry merge function */
259ccb6c 3293static int process_entry(struct merge_options *opt,
8a2fce18 3294 const char *path, struct stage_data *entry)
9047ebbc 3295{
9047ebbc 3296 int clean_merge = 1;
259ccb6c 3297 int normalize = opt->renormalize;
8daec1df
EN
3298
3299 struct diff_filespec *o = &entry->stages[1];
3300 struct diff_filespec *a = &entry->stages[2];
3301 struct diff_filespec *b = &entry->stages[3];
3302 int o_valid = is_valid(o);
3303 int a_valid = is_valid(a);
3304 int b_valid = is_valid(b);
3305 o->path = a->path = b->path = (char*)path;
9047ebbc 3306
37348937 3307 entry->processed = 1;
4f66dade 3308 if (entry->rename_conflict_info) {
043622b2 3309 struct rename_conflict_info *ci = entry->rename_conflict_info;
8daec1df 3310 struct diff_filespec *temp;
8c8e5bd6
EN
3311 int path_clean;
3312
3313 path_clean = warn_about_dir_renamed_entries(opt, ci->ren1);
3314 path_clean &= warn_about_dir_renamed_entries(opt, ci->ren2);
8daec1df
EN
3315
3316 /*
3317 * For cases with a single rename, {o,a,b}->path have all been
3318 * set to the rename target path; we need to set two of these
3319 * back to the rename source.
3320 * For rename/rename conflicts, we'll manually fix paths below.
3321 */
3322 temp = (opt->branch1 == ci->ren1->branch) ? b : a;
3323 o->path = temp->path = ci->ren1->pair->one->path;
3324 if (ci->ren2) {
3325 assert(opt->branch1 == ci->ren1->branch);
3326 }
3327
043622b2 3328 switch (ci->rename_type) {
882fd11a 3329 case RENAME_NORMAL:
4f66dade 3330 case RENAME_ONE_FILE_TO_ONE:
8daec1df 3331 clean_merge = handle_rename_normal(opt, path, o, a, b,
043622b2 3332 ci);
882fd11a 3333 break;
5455c338 3334 case RENAME_VIA_DIR:
8c8e5bd6 3335 clean_merge = handle_rename_via_dir(opt, ci);
882fd11a 3336 break;
7f867165
EN
3337 case RENAME_ADD:
3338 /*
3339 * Probably unclean merge, but if the renamed file
3340 * merges cleanly and the result can then be
3341 * two-way merged cleanly with the added file, I
3342 * guess it's a clean merge?
3343 */
043622b2 3344 clean_merge = handle_rename_add(opt, ci);
7f867165 3345 break;
3b130adf
EN
3346 case RENAME_DELETE:
3347 clean_merge = 0;
e2d563df 3348 if (handle_rename_delete(opt, ci))
75456f96 3349 clean_merge = -1;
3b130adf 3350 break;
07413c5a 3351 case RENAME_ONE_FILE_TO_TWO:
8daec1df
EN
3352 /*
3353 * Manually fix up paths; note:
3354 * ren[12]->pair->one->path are equal.
3355 */
3356 o->path = ci->ren1->pair->one->path;
3357 a->path = ci->ren1->pair->two->path;
3358 b->path = ci->ren2->pair->two->path;
3359
07413c5a 3360 clean_merge = 0;
043622b2 3361 if (handle_rename_rename_1to2(opt, ci))
75456f96 3362 clean_merge = -1;
07413c5a 3363 break;
461f5041 3364 case RENAME_TWO_FILES_TO_ONE:
8daec1df
EN
3365 /*
3366 * Manually fix up paths; note,
3367 * ren[12]->pair->two->path are actually equal.
3368 */
3369 o->path = NULL;
3370 a->path = ci->ren1->pair->two->path;
3371 b->path = ci->ren2->pair->two->path;
3372
bbafc9c4
EN
3373 /*
3374 * Probably unclean merge, but if the two renamed
3375 * files merge cleanly and the two resulting files
3376 * can then be two-way merged cleanly, I guess it's
3377 * a clean merge?
3378 */
043622b2 3379 clean_merge = handle_rename_rename_2to1(opt, ci);
07413c5a
EN
3380 break;
3381 default:
3382 entry->processed = 0;
3383 break;
3384 }
8c8e5bd6
EN
3385 if (path_clean < clean_merge)
3386 clean_merge = path_clean;
8daec1df 3387 } else if (o_valid && (!a_valid || !b_valid)) {
edd2faf5 3388 /* Case A: Deleted in one */
8daec1df
EN
3389 if ((!a_valid && !b_valid) ||
3390 (!b_valid && blob_unchanged(opt, o, a, normalize, path)) ||
3391 (!a_valid && blob_unchanged(opt, o, b, normalize, path))) {
edd2faf5
EN
3392 /* Deleted in both or deleted in one and
3393 * unchanged in the other */
8daec1df 3394 if (a_valid)
259ccb6c 3395 output(opt, 2, _("Removing %s"), path);
edd2faf5 3396 /* do not touch working file if it did not exist */
8daec1df 3397 remove_file(opt, 1, path, !a_valid);
edd2faf5
EN
3398 } else {
3399 /* Modify/delete; deleted side may have put a directory in the way */
edd2faf5 3400 clean_merge = 0;
8daec1df 3401 if (handle_modify_delete(opt, path, o, a, b))
75456f96 3402 clean_merge = -1;
3d6b8e88 3403 }
8daec1df
EN
3404 } else if ((!o_valid && a_valid && !b_valid) ||
3405 (!o_valid && !a_valid && b_valid)) {
edd2faf5
EN
3406 /* Case B: Added in one. */
3407 /* [nothing|directory] -> ([nothing|directory], file) */
3408
9c0bbb50
EN
3409 const char *add_branch;
3410 const char *other_branch;
9c0bbb50 3411 const char *conf;
8daec1df 3412 const struct diff_filespec *contents;
37348937 3413
8daec1df 3414 if (a_valid) {
259ccb6c
EN
3415 add_branch = opt->branch1;
3416 other_branch = opt->branch2;
8daec1df 3417 contents = a;
55653a68 3418 conf = _("file/directory");
9c0bbb50 3419 } else {
259ccb6c
EN
3420 add_branch = opt->branch2;
3421 other_branch = opt->branch1;
8daec1df 3422 contents = b;
55653a68 3423 conf = _("directory/file");
9c0bbb50 3424 }
259ccb6c 3425 if (dir_in_way(opt->repo->index, path,
5bf7e577 3426 !opt->priv->call_depth && !S_ISGITLINK(a->mode),
c641ca67 3427 0)) {
259ccb6c 3428 char *new_path = unique_path(opt, path, add_branch);
9c0bbb50 3429 clean_merge = 0;
259ccb6c 3430 output(opt, 1, _("CONFLICT (%s): There is a directory with name %s in %s. "
55653a68 3431 "Adding %s as %s"),
9c0bbb50 3432 conf, path, other_branch, path, new_path);
8daec1df 3433 if (update_file(opt, 0, contents, new_path))
75456f96 3434 clean_merge = -1;
5bf7e577 3435 else if (opt->priv->call_depth)
259ccb6c 3436 remove_file_from_index(opt->repo->index, path);
3d6b8e88 3437 free(new_path);
9c0bbb50 3438 } else {
259ccb6c 3439 output(opt, 2, _("Adding %s"), path);
35a74abf 3440 /* do not overwrite file if already present */
8daec1df 3441 if (update_file_flags(opt, contents, path, 1, !a_valid))
75456f96 3442 clean_merge = -1;
9c0bbb50 3443 }
8daec1df
EN
3444 } else if (a_valid && b_valid) {
3445 if (!o_valid) {
dcf28150 3446 /* Case C: Added in both (check for same permissions) */
259ccb6c 3447 output(opt, 1,
dcf28150
EN
3448 _("CONFLICT (add/add): Merge conflict in %s"),
3449 path);
259ccb6c 3450 clean_merge = handle_file_collision(opt,
dcf28150 3451 path, NULL, NULL,
259ccb6c
EN
3452 opt->branch1,
3453 opt->branch2,
8daec1df 3454 a, b);
dcf28150
EN
3455 } else {
3456 /* case D: Modified in both, but differently. */
e62d1123 3457 struct merge_file_info mfi;
dcf28150 3458 int is_dirty = 0; /* unpack_trees would have bailed if dirty */
e62d1123 3459 clean_merge = handle_content_merge(&mfi, opt, path,
dcf28150 3460 is_dirty,
8daec1df 3461 o, a, b, NULL);
dcf28150 3462 }
8daec1df 3463 } else if (!o_valid && !a_valid && !b_valid) {
edd2faf5
EN
3464 /*
3465 * this entry was deleted altogether. a_mode == 0 means
3466 * we had that path and want to actively remove it.
3467 */
8daec1df 3468 remove_file(opt, 1, path, !a->mode);
edd2faf5 3469 } else
033abf97 3470 BUG("fatal merge failure, shouldn't happen.");
37348937
EN
3471
3472 return clean_merge;
3473}
3474
98a1d3d8
EN
3475static int merge_trees_internal(struct merge_options *opt,
3476 struct tree *head,
3477 struct tree *merge,
ff1bfa2c 3478 struct tree *merge_base,
98a1d3d8 3479 struct tree **result)
9047ebbc 3480{
259ccb6c 3481 struct index_state *istate = opt->repo->index;
9047ebbc
MV
3482 int code, clean;
3483
259ccb6c 3484 if (opt->subtree_shift) {
ff1bfa2c
EN
3485 merge = shift_tree_object(opt->repo, head, merge,
3486 opt->subtree_shift);
3487 merge_base = shift_tree_object(opt->repo, head, merge_base,
3488 opt->subtree_shift);
9047ebbc
MV
3489 }
3490
763a59e7 3491 if (oideq(&merge_base->object.oid, &merge->object.oid)) {
80cde95e 3492 output(opt, 0, _("Already up to date."));
9047ebbc
MV
3493 *result = head;
3494 return 1;
3495 }
3496
ff1bfa2c 3497 code = unpack_trees_start(opt, merge_base, head, merge);
9047ebbc 3498
fadd069d 3499 if (code != 0) {
5bf7e577 3500 if (show(opt, 4) || opt->priv->call_depth)
259ccb6c 3501 err(opt, _("merging of trees %s and %s failed"),
f2fd0760 3502 oid_to_hex(&head->object.oid),
3503 oid_to_hex(&merge->object.oid));
259ccb6c 3504 unpack_trees_finish(opt);
6003303a 3505 return -1;
fadd069d 3506 }
9047ebbc 3507
0d6caa2d 3508 if (unmerged_index(istate)) {
f172589e
EN
3509 struct string_list *entries;
3510 struct rename_info re_info;
9047ebbc 3511 int i;
fc65b00d
KW
3512 /*
3513 * Only need the hashmap while processing entries, so
3514 * initialize it here and free it when we are done running
3515 * through the entries. Keeping it in the merge_options as
3516 * opposed to decaring a local hashmap is for convenience
3517 * so that we don't have to pass it to around.
3518 */
5bf7e577 3519 hashmap_init(&opt->priv->current_file_dir_set, path_hashmap_cmp,
4d7101e2 3520 NULL, 512);
259ccb6c
EN
3521 get_files_dirs(opt, head);
3522 get_files_dirs(opt, merge);
9047ebbc 3523
259ccb6c 3524 entries = get_unmerged(opt->repo->index);
ff1bfa2c 3525 clean = detect_and_process_renames(opt, merge_base, head, merge,
8ebe7b05 3526 entries, &re_info);
259ccb6c 3527 record_df_conflict_files(opt, entries);
75456f96 3528 if (clean < 0)
e336bdc5 3529 goto cleanup;
edd2faf5 3530 for (i = entries->nr-1; 0 <= i; i--) {
9047ebbc
MV
3531 const char *path = entries->items[i].string;
3532 struct stage_data *e = entries->items[i].util;
75456f96 3533 if (!e->processed) {
259ccb6c 3534 int ret = process_entry(opt, path, e);
75456f96
JS
3535 if (!ret)
3536 clean = 0;
e336bdc5
KW
3537 else if (ret < 0) {
3538 clean = ret;
3539 goto cleanup;
3540 }
75456f96 3541 }
9047ebbc 3542 }
7edba4c4
JH
3543 for (i = 0; i < entries->nr; i++) {
3544 struct stage_data *e = entries->items[i].util;
3545 if (!e->processed)
033abf97 3546 BUG("unprocessed path??? %s",
7edba4c4
JH
3547 entries->items[i].string);
3548 }
9047ebbc 3549
93665365 3550 cleanup:
ffc16c49 3551 final_cleanup_renames(&re_info);
f172589e 3552
9047ebbc 3553 string_list_clear(entries, 1);
f172589e 3554 free(entries);
9047ebbc 3555
6da1a258 3556 hashmap_clear_and_free(&opt->priv->current_file_dir_set,
c8e424c9 3557 struct path_hashmap_entry, e);
fc65b00d 3558
3f1c1c36 3559 if (clean < 0) {
259ccb6c 3560 unpack_trees_finish(opt);
e336bdc5 3561 return clean;
3f1c1c36 3562 }
9047ebbc
MV
3563 }
3564 else
3565 clean = 1;
3566
259ccb6c 3567 unpack_trees_finish(opt);
a35edc84 3568
5bf7e577 3569 if (opt->priv->call_depth &&
724dd767 3570 !(*result = write_in_core_index_as_tree(opt->repo)))
fbc87eb5 3571 return -1;
9047ebbc
MV
3572
3573 return clean;
3574}
3575
9047ebbc 3576/*
56e74342
EN
3577 * Merge the commits h1 and h2, returning a flag (int) indicating the
3578 * cleanness of the merge. Also, if opt->priv->call_depth, create a
3579 * virtual commit and write its location to *result.
9047ebbc 3580 */
98a1d3d8
EN
3581static int merge_recursive_internal(struct merge_options *opt,
3582 struct commit *h1,
3583 struct commit *h2,
ff1bfa2c 3584 struct commit_list *merge_bases,
98a1d3d8 3585 struct commit **result)
9047ebbc
MV
3586{
3587 struct commit_list *iter;
ff1bfa2c 3588 struct commit *merged_merge_bases;
bab56877 3589 struct tree *result_tree;
9047ebbc 3590 int clean;
743474cb
EN
3591 const char *ancestor_name;
3592 struct strbuf merge_base_abbrev = STRBUF_INIT;
9047ebbc 3593
259ccb6c
EN
3594 if (show(opt, 4)) {
3595 output(opt, 4, _("Merging:"));
3596 output_commit_title(opt, h1);
3597 output_commit_title(opt, h2);
9047ebbc
MV
3598 }
3599
ff1bfa2c 3600 if (!merge_bases) {
cb338c23 3601 merge_bases = repo_get_merge_bases(the_repository, h1, h2);
ff1bfa2c 3602 merge_bases = reverse_commit_list(merge_bases);
9047ebbc
MV
3603 }
3604
259ccb6c 3605 if (show(opt, 5)) {
ff1bfa2c 3606 unsigned cnt = commit_list_count(merge_bases);
e0453cd8 3607
259ccb6c 3608 output(opt, 5, Q_("found %u common ancestor:",
e0453cd8 3609 "found %u common ancestors:", cnt), cnt);
ff1bfa2c 3610 for (iter = merge_bases; iter; iter = iter->next)
259ccb6c 3611 output_commit_title(opt, iter->item);
9047ebbc
MV
3612 }
3613
ff1bfa2c 3614 merged_merge_bases = pop_commit(&merge_bases);
afe8a907 3615 if (!merged_merge_bases) {
03f622c8
JN
3616 /* if there is no common ancestor, use an empty tree */
3617 struct tree *tree;
9047ebbc 3618
259ccb6c 3619 tree = lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);
ff1bfa2c
EN
3620 merged_merge_bases = make_virtual_commit(opt->repo, tree,
3621 "ancestor");
743474cb 3622 ancestor_name = "empty tree";
b6570477 3623 } else if (opt->ancestor && !opt->priv->call_depth) {
8e4ec337 3624 ancestor_name = opt->ancestor;
ff1bfa2c 3625 } else if (merge_bases) {
743474cb
EN
3626 ancestor_name = "merged common ancestors";
3627 } else {
3628 strbuf_add_unique_abbrev(&merge_base_abbrev,
ff1bfa2c 3629 &merged_merge_bases->object.oid,
743474cb
EN
3630 DEFAULT_ABBREV);
3631 ancestor_name = merge_base_abbrev.buf;
9047ebbc
MV
3632 }
3633
ff1bfa2c 3634 for (iter = merge_bases; iter; iter = iter->next) {
8a2fce18 3635 const char *saved_b1, *saved_b2;
5bf7e577 3636 opt->priv->call_depth++;
9047ebbc
MV
3637 /*
3638 * When the merge fails, the result contains files
3639 * with conflict markers. The cleanness flag is
de8946de
JS
3640 * ignored (unless indicating an error), it was never
3641 * actually used, as result of merge_trees has always
3642 * overwritten it: the committed "conflicts" were
3643 * already resolved.
9047ebbc 3644 */
259ccb6c
EN
3645 discard_index(opt->repo->index);
3646 saved_b1 = opt->branch1;
3647 saved_b2 = opt->branch2;
3648 opt->branch1 = "Temporary merge branch 1";
3649 opt->branch2 = "Temporary merge branch 2";
ff1bfa2c
EN
3650 if (merge_recursive_internal(opt, merged_merge_bases, iter->item,
3651 NULL, &merged_merge_bases) < 0)
de8946de 3652 return -1;
259ccb6c
EN
3653 opt->branch1 = saved_b1;
3654 opt->branch2 = saved_b2;
5bf7e577 3655 opt->priv->call_depth--;
9047ebbc 3656
ff1bfa2c 3657 if (!merged_merge_bases)
259ccb6c 3658 return err(opt, _("merge returned no commit"));
9047ebbc
MV
3659 }
3660
816147e7
EN
3661 /*
3662 * FIXME: Since merge_recursive_internal() is only ever called by
3663 * places that ensure the index is loaded first
3664 * (e.g. builtin/merge.c, rebase/sequencer, etc.), in the common
3665 * case where the merge base was unique that means when we get here
3666 * we immediately discard the index and re-read it, which is a
3667 * complete waste of time. We should only be discarding and
3668 * re-reading if we were forced to recurse.
3669 */
259ccb6c 3670 discard_index(opt->repo->index);
5bf7e577 3671 if (!opt->priv->call_depth)
259ccb6c 3672 repo_read_index(opt->repo);
9047ebbc 3673
743474cb 3674 opt->ancestor = ancestor_name;
98a1d3d8
EN
3675 clean = merge_trees_internal(opt,
3676 repo_get_commit_tree(opt->repo, h1),
3677 repo_get_commit_tree(opt->repo, h2),
3678 repo_get_commit_tree(opt->repo,
ff1bfa2c 3679 merged_merge_bases),
bab56877 3680 &result_tree);
743474cb 3681 strbuf_release(&merge_base_abbrev);
b6570477 3682 opt->ancestor = NULL; /* avoid accidental re-use of opt->ancestor */
6999bc70 3683 if (clean < 0) {
259ccb6c 3684 flush_output(opt);
de8946de 3685 return clean;
6999bc70 3686 }
9047ebbc 3687
5bf7e577 3688 if (opt->priv->call_depth) {
bab56877
EN
3689 *result = make_virtual_commit(opt->repo, result_tree,
3690 "merged tree");
9047ebbc
MV
3691 commit_list_insert(h1, &(*result)->parents);
3692 commit_list_insert(h2, &(*result)->parents->next);
3693 }
9047ebbc
MV
3694 return clean;
3695}
3696
98a1d3d8
EN
3697static int merge_start(struct merge_options *opt, struct tree *head)
3698{
3699 struct strbuf sb = STRBUF_INIT;
3700
45ef16f7
EN
3701 /* Sanity checks on opt */
3702 assert(opt->repo);
3703
3704 assert(opt->branch1 && opt->branch2);
3705
3706 assert(opt->detect_renames >= -1 &&
3707 opt->detect_renames <= DIFF_DETECT_COPY);
3708 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
3709 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
3710 assert(opt->rename_limit >= -1);
3711 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
3712 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
3713
3714 assert(opt->xdl_opts >= 0);
3715 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
3716 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
3717
3718 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
3719 assert(opt->buffer_output <= 2);
3720 assert(opt->obuf.len == 0);
3721
3722 assert(opt->priv == NULL);
3723
6054d1aa
EN
3724 /* Not supported; option specific to merge-ort */
3725 assert(!opt->record_conflict_msgs_as_headers);
3726 assert(!opt->msg_header_prefix);
3727
45ef16f7 3728 /* Sanity check on repo state; index must match head */
98a1d3d8
EN
3729 if (repo_index_has_changes(opt->repo, head, &sb)) {
3730 err(opt, _("Your local changes to the following files would be overwritten by merge:\n %s"),
3731 sb.buf);
3732 strbuf_release(&sb);
3733 return -1;
3734 }
3735
ca56dadb 3736 CALLOC_ARRAY(opt->priv, 1);
bc40dfb1 3737 string_list_init_dup(&opt->priv->df_conflict_file_set);
98a1d3d8
EN
3738 return 0;
3739}
3740
3741static void merge_finalize(struct merge_options *opt)
3742{
259ccb6c 3743 flush_output(opt);
5bf7e577 3744 if (!opt->priv->call_depth && opt->buffer_output < 2)
259ccb6c
EN
3745 strbuf_release(&opt->obuf);
3746 if (show(opt, 2))
f31027c9 3747 diff_warn_rename_limit("merge.renamelimit",
5bf7e577
EN
3748 opt->priv->needed_rename_limit, 0);
3749 FREE_AND_NULL(opt->priv);
98a1d3d8
EN
3750}
3751
3752int merge_trees(struct merge_options *opt,
3753 struct tree *head,
3754 struct tree *merge,
ff1bfa2c 3755 struct tree *merge_base)
98a1d3d8
EN
3756{
3757 int clean;
b4db8a2b 3758 struct tree *ignored;
98a1d3d8
EN
3759
3760 assert(opt->ancestor != NULL);
3761
3762 if (merge_start(opt, head))
3763 return -1;
ff1bfa2c 3764 clean = merge_trees_internal(opt, head, merge, merge_base, &ignored);
98a1d3d8
EN
3765 merge_finalize(opt);
3766
3767 return clean;
3768}
3769
3770int merge_recursive(struct merge_options *opt,
3771 struct commit *h1,
3772 struct commit *h2,
ff1bfa2c 3773 struct commit_list *merge_bases,
98a1d3d8
EN
3774 struct commit **result)
3775{
3776 int clean;
3777
8e4ec337
EN
3778 assert(opt->ancestor == NULL ||
3779 !strcmp(opt->ancestor, "constructed merge base"));
98a1d3d8 3780
a3380639
DS
3781 prepare_repo_settings(opt->repo);
3782 opt->repo->settings.command_requires_full_index = 1;
3783
98a1d3d8
EN
3784 if (merge_start(opt, repo_get_commit_tree(opt->repo, h1)))
3785 return -1;
ff1bfa2c 3786 clean = merge_recursive_internal(opt, h1, h2, merge_bases, result);
98a1d3d8
EN
3787 merge_finalize(opt);
3788
9047ebbc
MV
3789 return clean;
3790}
3791
4d7101e2
EN
3792static struct commit *get_ref(struct repository *repo,
3793 const struct object_id *oid,
d7cf3a96 3794 const char *name)
73118f89
SB
3795{
3796 struct object *object;
3797
d7cf3a96
NTND
3798 object = deref_tag(repo, parse_object(repo, oid),
3799 name, strlen(name));
73118f89
SB
3800 if (!object)
3801 return NULL;
3802 if (object->type == OBJ_TREE)
d7cf3a96 3803 return make_virtual_commit(repo, (struct tree*)object, name);
73118f89
SB
3804 if (object->type != OBJ_COMMIT)
3805 return NULL;
4a93b899 3806 if (repo_parse_commit(repo, (struct commit *)object))
73118f89
SB
3807 return NULL;
3808 return (struct commit *)object;
3809}
3810
259ccb6c 3811int merge_recursive_generic(struct merge_options *opt,
4e8161a8 3812 const struct object_id *head,
3813 const struct object_id *merge,
ff1bfa2c
EN
3814 int num_merge_bases,
3815 const struct object_id **merge_bases,
8a2fce18 3816 struct commit **result)
73118f89 3817{
03b86647 3818 int clean;
837e34eb 3819 struct lock_file lock = LOCK_INIT;
259ccb6c
EN
3820 struct commit *head_commit = get_ref(opt->repo, head, opt->branch1);
3821 struct commit *next_commit = get_ref(opt->repo, merge, opt->branch2);
73118f89
SB
3822 struct commit_list *ca = NULL;
3823
ff1bfa2c 3824 if (merge_bases) {
73118f89 3825 int i;
ff1bfa2c 3826 for (i = 0; i < num_merge_bases; ++i) {
73118f89 3827 struct commit *base;
ff1bfa2c
EN
3828 if (!(base = get_ref(opt->repo, merge_bases[i],
3829 oid_to_hex(merge_bases[i]))))
259ccb6c 3830 return err(opt, _("Could not parse object '%s'"),
ff1bfa2c 3831 oid_to_hex(merge_bases[i]));
73118f89
SB
3832 commit_list_insert(base, &ca);
3833 }
8e4ec337
EN
3834 if (num_merge_bases == 1)
3835 opt->ancestor = "constructed merge base";
73118f89
SB
3836 }
3837
259ccb6c
EN
3838 repo_hold_locked_index(opt->repo, &lock, LOCK_DIE_ON_ERROR);
3839 clean = merge_recursive(opt, head_commit, next_commit, ca,
d90e759f 3840 result);
51d3f43d
3841 if (clean < 0) {
3842 rollback_lock_file(&lock);
de8946de 3843 return clean;
51d3f43d 3844 }
de8946de 3845
259ccb6c 3846 if (write_locked_index(opt->repo->index, &lock,
61000814 3847 COMMIT_LOCK | SKIP_IF_UNCHANGED))
259ccb6c 3848 return err(opt, _("Unable to write index."));
73118f89
SB
3849
3850 return clean ? 0 : 1;
3851}
3852
259ccb6c 3853static void merge_recursive_config(struct merge_options *opt)
9047ebbc 3854{
85b46030 3855 char *value = NULL;
8d552258 3856 int renormalize = 0;
259ccb6c 3857 git_config_get_int("merge.verbosity", &opt->verbosity);
8599ab45
EN
3858 git_config_get_int("diff.renamelimit", &opt->rename_limit);
3859 git_config_get_int("merge.renamelimit", &opt->rename_limit);
8d552258
EN
3860 git_config_get_bool("merge.renormalize", &renormalize);
3861 opt->renormalize = renormalize;
85b46030 3862 if (!git_config_get_string("diff.renames", &value)) {
8599ab45 3863 opt->detect_renames = git_config_rename("diff.renames", value);
85b46030
BP
3864 free(value);
3865 }
3866 if (!git_config_get_string("merge.renames", &value)) {
8599ab45 3867 opt->detect_renames = git_config_rename("merge.renames", value);
85b46030
BP
3868 free(value);
3869 }
8c8e5bd6
EN
3870 if (!git_config_get_string("merge.directoryrenames", &value)) {
3871 int boolval = git_parse_maybe_bool(value);
3872 if (0 <= boolval) {
8e012516
DS
3873 opt->detect_directory_renames = boolval ?
3874 MERGE_DIRECTORY_RENAMES_TRUE :
3875 MERGE_DIRECTORY_RENAMES_NONE;
8c8e5bd6 3876 } else if (!strcasecmp(value, "conflict")) {
8e012516
DS
3877 opt->detect_directory_renames =
3878 MERGE_DIRECTORY_RENAMES_CONFLICT;
8c8e5bd6 3879 } /* avoid erroring on values from future versions of git */
85b46030
BP
3880 free(value);
3881 }
0e7bcb1b 3882 git_config(git_xmerge_config, NULL);
9047ebbc
MV
3883}
3884
259ccb6c 3885void init_merge_options(struct merge_options *opt,
0d6caa2d 3886 struct repository *repo)
9047ebbc 3887{
80486220 3888 const char *merge_verbosity;
259ccb6c 3889 memset(opt, 0, sizeof(struct merge_options));
a779fb82 3890
259ccb6c 3891 opt->repo = repo;
a779fb82
EN
3892
3893 opt->detect_renames = -1;
3894 opt->detect_directory_renames = MERGE_DIRECTORY_RENAMES_CONFLICT;
3895 opt->rename_limit = -1;
3896
259ccb6c
EN
3897 opt->verbosity = 2;
3898 opt->buffer_output = 1;
a779fb82
EN
3899 strbuf_init(&opt->obuf, 0);
3900
259ccb6c 3901 opt->renormalize = 0;
a779fb82 3902
259ccb6c 3903 merge_recursive_config(opt);
80486220
AO
3904 merge_verbosity = getenv("GIT_MERGE_VERBOSITY");
3905 if (merge_verbosity)
259ccb6c
EN
3906 opt->verbosity = strtol(merge_verbosity, NULL, 10);
3907 if (opt->verbosity >= 5)
3908 opt->buffer_output = 0;
9047ebbc 3909}
635a7bb1 3910
259ccb6c 3911int parse_merge_opt(struct merge_options *opt, const char *s)
635a7bb1 3912{
95b567c7
JK
3913 const char *arg;
3914
635a7bb1
JN
3915 if (!s || !*s)
3916 return -1;
3917 if (!strcmp(s, "ours"))
f3081dae 3918 opt->recursive_variant = MERGE_VARIANT_OURS;
635a7bb1 3919 else if (!strcmp(s, "theirs"))
f3081dae 3920 opt->recursive_variant = MERGE_VARIANT_THEIRS;
635a7bb1 3921 else if (!strcmp(s, "subtree"))
259ccb6c 3922 opt->subtree_shift = "";
95b567c7 3923 else if (skip_prefix(s, "subtree=", &arg))
259ccb6c 3924 opt->subtree_shift = arg;
58a1ece4 3925 else if (!strcmp(s, "patience"))
259ccb6c 3926 opt->xdl_opts = DIFF_WITH_ALG(opt, PATIENCE_DIFF);
8c912eea 3927 else if (!strcmp(s, "histogram"))
259ccb6c 3928 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
95b567c7
JK
3929 else if (skip_prefix(s, "diff-algorithm=", &arg)) {
3930 long value = parse_algorithm_value(arg);
07924d4d
MP
3931 if (value < 0)
3932 return -1;
3933 /* clear out previous settings */
259ccb6c
EN
3934 DIFF_XDL_CLR(opt, NEED_MINIMAL);
3935 opt->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3936 opt->xdl_opts |= value;
07924d4d 3937 }
4e5dd044 3938 else if (!strcmp(s, "ignore-space-change"))
259ccb6c 3939 DIFF_XDL_SET(opt, IGNORE_WHITESPACE_CHANGE);
4e5dd044 3940 else if (!strcmp(s, "ignore-all-space"))
259ccb6c 3941 DIFF_XDL_SET(opt, IGNORE_WHITESPACE);
4e5dd044 3942 else if (!strcmp(s, "ignore-space-at-eol"))
259ccb6c 3943 DIFF_XDL_SET(opt, IGNORE_WHITESPACE_AT_EOL);
e9282f02 3944 else if (!strcmp(s, "ignore-cr-at-eol"))
259ccb6c 3945 DIFF_XDL_SET(opt, IGNORE_CR_AT_EOL);
635a7bb1 3946 else if (!strcmp(s, "renormalize"))
259ccb6c 3947 opt->renormalize = 1;
635a7bb1 3948 else if (!strcmp(s, "no-renormalize"))
259ccb6c 3949 opt->renormalize = 0;
d2b11eca 3950 else if (!strcmp(s, "no-renames"))
8599ab45 3951 opt->detect_renames = 0;
87892f60 3952 else if (!strcmp(s, "find-renames")) {
8599ab45 3953 opt->detect_renames = 1;
259ccb6c 3954 opt->rename_score = 0;
87892f60 3955 }
1b47ad16
FGA
3956 else if (skip_prefix(s, "find-renames=", &arg) ||
3957 skip_prefix(s, "rename-threshold=", &arg)) {
259ccb6c 3958 if ((opt->rename_score = parse_rename_score(&arg)) == -1 || *arg != 0)
10ae7526 3959 return -1;
8599ab45 3960 opt->detect_renames = 1;
10ae7526 3961 }
5a59a230
NTND
3962 /*
3963 * Please update $__git_merge_strategy_options in
3964 * git-completion.bash when you add new options
3965 */
635a7bb1
JN
3966 else
3967 return -1;
3968 return 0;
3969}