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