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