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