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