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