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