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