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