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