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