ssh signing: fmt-merge-msg tests & config parse
[git.git] / merge-recursive.c
blob5a2d8a60c0d23272cd0258270fd1c24d81eccac6
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,
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 == NULL)
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 *unused_cmp_data,
93 const struct hashmap_entry *eptr,
94 const struct hashmap_entry *entry_or_key,
95 const void *unused_keydata)
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 *unused_cmp_data,
138 const struct hashmap_entry *eptr,
139 const struct hashmap_entry *entry_or_key,
140 const void *unused_keydata)
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 output_commit_title(struct merge_options *opt, struct commit *commit)
339 struct merge_remote_desc *desc;
341 strbuf_addchars(&opt->obuf, ' ', opt->priv->call_depth * 2);
342 desc = merge_remote_util(commit);
343 if (desc)
344 strbuf_addf(&opt->obuf, "virtual %s\n", desc->name);
345 else {
346 strbuf_add_unique_abbrev(&opt->obuf, &commit->object.oid,
347 DEFAULT_ABBREV);
348 strbuf_addch(&opt->obuf, ' ');
349 if (parse_commit(commit) != 0)
350 strbuf_addstr(&opt->obuf, _("(bad commit)\n"));
351 else {
352 const char *title;
353 const char *msg = get_commit_buffer(commit, NULL);
354 int len = find_commit_subject(msg, &title);
355 if (len)
356 strbuf_addf(&opt->obuf, "%.*s\n", len, title);
357 unuse_commit_buffer(commit, msg);
360 flush_output(opt);
363 static int add_cacheinfo(struct merge_options *opt,
364 const struct diff_filespec *blob,
365 const char *path, int stage, int refresh, int options)
367 struct index_state *istate = opt->repo->index;
368 struct cache_entry *ce;
369 int ret;
371 ce = make_cache_entry(istate, blob->mode, &blob->oid, path, stage, 0);
372 if (!ce)
373 return err(opt, _("add_cacheinfo failed for path '%s'; merge aborting."), path);
375 ret = add_index_entry(istate, ce, options);
376 if (refresh) {
377 struct cache_entry *nce;
379 nce = refresh_cache_entry(istate, ce,
380 CE_MATCH_REFRESH | CE_MATCH_IGNORE_MISSING);
381 if (!nce)
382 return err(opt, _("add_cacheinfo failed to refresh for path '%s'; merge aborting."), path);
383 if (nce != ce)
384 ret = add_index_entry(istate, nce, options);
386 return ret;
389 static inline int merge_detect_rename(struct merge_options *opt)
391 return (opt->detect_renames >= 0) ? opt->detect_renames : 1;
394 static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree)
396 parse_tree(tree);
397 init_tree_desc(desc, tree->buffer, tree->size);
400 static int unpack_trees_start(struct merge_options *opt,
401 struct tree *common,
402 struct tree *head,
403 struct tree *merge)
405 int rc;
406 struct tree_desc t[3];
407 struct index_state tmp_index = { NULL };
409 memset(&opt->priv->unpack_opts, 0, sizeof(opt->priv->unpack_opts));
410 if (opt->priv->call_depth)
411 opt->priv->unpack_opts.index_only = 1;
412 else
413 opt->priv->unpack_opts.update = 1;
414 opt->priv->unpack_opts.merge = 1;
415 opt->priv->unpack_opts.head_idx = 2;
416 opt->priv->unpack_opts.fn = threeway_merge;
417 opt->priv->unpack_opts.src_index = opt->repo->index;
418 opt->priv->unpack_opts.dst_index = &tmp_index;
419 opt->priv->unpack_opts.aggressive = !merge_detect_rename(opt);
420 setup_unpack_trees_porcelain(&opt->priv->unpack_opts, "merge");
422 init_tree_desc_from_tree(t+0, common);
423 init_tree_desc_from_tree(t+1, head);
424 init_tree_desc_from_tree(t+2, merge);
426 rc = unpack_trees(3, t, &opt->priv->unpack_opts);
427 cache_tree_free(&opt->repo->index->cache_tree);
430 * Update opt->repo->index to match the new results, AFTER saving a
431 * copy in opt->priv->orig_index. Update src_index to point to the
432 * saved copy. (verify_uptodate() checks src_index, and the original
433 * index is the one that had the necessary modification timestamps.)
435 opt->priv->orig_index = *opt->repo->index;
436 *opt->repo->index = tmp_index;
437 opt->priv->unpack_opts.src_index = &opt->priv->orig_index;
439 return rc;
442 static void unpack_trees_finish(struct merge_options *opt)
444 discard_index(&opt->priv->orig_index);
445 clear_unpack_trees_porcelain(&opt->priv->unpack_opts);
448 static int save_files_dirs(const struct object_id *oid,
449 struct strbuf *base, const char *path,
450 unsigned int mode, void *context)
452 struct path_hashmap_entry *entry;
453 int baselen = base->len;
454 struct merge_options *opt = context;
456 strbuf_addstr(base, path);
458 FLEX_ALLOC_MEM(entry, path, base->buf, base->len);
459 hashmap_entry_init(&entry->e, fspathhash(entry->path));
460 hashmap_add(&opt->priv->current_file_dir_set, &entry->e);
462 strbuf_setlen(base, baselen);
463 return (S_ISDIR(mode) ? READ_TREE_RECURSIVE : 0);
466 static void get_files_dirs(struct merge_options *opt, struct tree *tree)
468 struct pathspec match_all;
469 memset(&match_all, 0, sizeof(match_all));
470 read_tree(opt->repo, tree,
471 &match_all, save_files_dirs, opt);
474 static int get_tree_entry_if_blob(struct repository *r,
475 const struct object_id *tree,
476 const char *path,
477 struct diff_filespec *dfs)
479 int ret;
481 ret = get_tree_entry(r, tree, path, &dfs->oid, &dfs->mode);
482 if (S_ISDIR(dfs->mode)) {
483 oidcpy(&dfs->oid, null_oid());
484 dfs->mode = 0;
486 return ret;
490 * Returns an index_entry instance which doesn't have to correspond to
491 * a real cache entry in Git's index.
493 static struct stage_data *insert_stage_data(struct repository *r,
494 const char *path,
495 struct tree *o, struct tree *a, struct tree *b,
496 struct string_list *entries)
498 struct string_list_item *item;
499 struct stage_data *e = xcalloc(1, sizeof(struct stage_data));
500 get_tree_entry_if_blob(r, &o->object.oid, path, &e->stages[1]);
501 get_tree_entry_if_blob(r, &a->object.oid, path, &e->stages[2]);
502 get_tree_entry_if_blob(r, &b->object.oid, path, &e->stages[3]);
503 item = string_list_insert(entries, path);
504 item->util = e;
505 return e;
509 * Create a dictionary mapping file names to stage_data objects. The
510 * dictionary contains one entry for every path with a non-zero stage entry.
512 static struct string_list *get_unmerged(struct index_state *istate)
514 struct string_list *unmerged = xcalloc(1, sizeof(struct string_list));
515 int i;
517 unmerged->strdup_strings = 1;
519 /* TODO: audit for interaction with sparse-index. */
520 ensure_full_index(istate);
521 for (i = 0; i < istate->cache_nr; i++) {
522 struct string_list_item *item;
523 struct stage_data *e;
524 const struct cache_entry *ce = istate->cache[i];
525 if (!ce_stage(ce))
526 continue;
528 item = string_list_lookup(unmerged, ce->name);
529 if (!item) {
530 item = string_list_insert(unmerged, ce->name);
531 item->util = xcalloc(1, sizeof(struct stage_data));
533 e = item->util;
534 e->stages[ce_stage(ce)].mode = ce->ce_mode;
535 oidcpy(&e->stages[ce_stage(ce)].oid, &ce->oid);
538 return unmerged;
541 static int string_list_df_name_compare(const char *one, const char *two)
543 int onelen = strlen(one);
544 int twolen = strlen(two);
546 * Here we only care that entries for D/F conflicts are
547 * adjacent, in particular with the file of the D/F conflict
548 * appearing before files below the corresponding directory.
549 * The order of the rest of the list is irrelevant for us.
551 * To achieve this, we sort with df_name_compare and provide
552 * the mode S_IFDIR so that D/F conflicts will sort correctly.
553 * We use the mode S_IFDIR for everything else for simplicity,
554 * since in other cases any changes in their order due to
555 * sorting cause no problems for us.
557 int cmp = df_name_compare(one, onelen, S_IFDIR,
558 two, twolen, S_IFDIR);
560 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
561 * that 'foo' comes before 'foo/bar'.
563 if (cmp)
564 return cmp;
565 return onelen - twolen;
568 static void record_df_conflict_files(struct merge_options *opt,
569 struct string_list *entries)
571 /* If there is a D/F conflict and the file for such a conflict
572 * currently exists in the working tree, we want to allow it to be
573 * removed to make room for the corresponding directory if needed.
574 * The files underneath the directories of such D/F conflicts will
575 * be processed before the corresponding file involved in the D/F
576 * conflict. If the D/F directory ends up being removed by the
577 * merge, then we won't have to touch the D/F file. If the D/F
578 * directory needs to be written to the working copy, then the D/F
579 * file will simply be removed (in make_room_for_path()) to make
580 * room for the necessary paths. Note that if both the directory
581 * and the file need to be present, then the D/F file will be
582 * reinstated with a new unique name at the time it is processed.
584 struct string_list df_sorted_entries = STRING_LIST_INIT_NODUP;
585 const char *last_file = NULL;
586 int last_len = 0;
587 int i;
590 * If we're merging merge-bases, we don't want to bother with
591 * any working directory changes.
593 if (opt->priv->call_depth)
594 return;
596 /* Ensure D/F conflicts are adjacent in the entries list. */
597 for (i = 0; i < entries->nr; i++) {
598 struct string_list_item *next = &entries->items[i];
599 string_list_append(&df_sorted_entries, next->string)->util =
600 next->util;
602 df_sorted_entries.cmp = string_list_df_name_compare;
603 string_list_sort(&df_sorted_entries);
605 string_list_clear(&opt->priv->df_conflict_file_set, 1);
606 for (i = 0; i < df_sorted_entries.nr; i++) {
607 const char *path = df_sorted_entries.items[i].string;
608 int len = strlen(path);
609 struct stage_data *e = df_sorted_entries.items[i].util;
612 * Check if last_file & path correspond to a D/F conflict;
613 * i.e. whether path is last_file+'/'+<something>.
614 * If so, record that it's okay to remove last_file to make
615 * room for path and friends if needed.
617 if (last_file &&
618 len > last_len &&
619 memcmp(path, last_file, last_len) == 0 &&
620 path[last_len] == '/') {
621 string_list_insert(&opt->priv->df_conflict_file_set, last_file);
625 * Determine whether path could exist as a file in the
626 * working directory as a possible D/F conflict. This
627 * will only occur when it exists in stage 2 as a
628 * file.
630 if (S_ISREG(e->stages[2].mode) || S_ISLNK(e->stages[2].mode)) {
631 last_file = path;
632 last_len = len;
633 } else {
634 last_file = NULL;
637 string_list_clear(&df_sorted_entries, 0);
640 static int update_stages(struct merge_options *opt, const char *path,
641 const struct diff_filespec *o,
642 const struct diff_filespec *a,
643 const struct diff_filespec *b)
647 * NOTE: It is usually a bad idea to call update_stages on a path
648 * before calling update_file on that same path, since it can
649 * sometimes lead to spurious "refusing to lose untracked file..."
650 * messages from update_file (via make_room_for path via
651 * would_lose_untracked). Instead, reverse the order of the calls
652 * (executing update_file first and then update_stages).
654 int clear = 1;
655 int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_SKIP_DFCHECK;
656 if (clear)
657 if (remove_file_from_index(opt->repo->index, path))
658 return -1;
659 if (o)
660 if (add_cacheinfo(opt, o, path, 1, 0, options))
661 return -1;
662 if (a)
663 if (add_cacheinfo(opt, a, path, 2, 0, options))
664 return -1;
665 if (b)
666 if (add_cacheinfo(opt, b, path, 3, 0, options))
667 return -1;
668 return 0;
671 static void update_entry(struct stage_data *entry,
672 struct diff_filespec *o,
673 struct diff_filespec *a,
674 struct diff_filespec *b)
676 entry->processed = 0;
677 entry->stages[1].mode = o->mode;
678 entry->stages[2].mode = a->mode;
679 entry->stages[3].mode = b->mode;
680 oidcpy(&entry->stages[1].oid, &o->oid);
681 oidcpy(&entry->stages[2].oid, &a->oid);
682 oidcpy(&entry->stages[3].oid, &b->oid);
685 static int remove_file(struct merge_options *opt, int clean,
686 const char *path, int no_wd)
688 int update_cache = opt->priv->call_depth || clean;
689 int update_working_directory = !opt->priv->call_depth && !no_wd;
691 if (update_cache) {
692 if (remove_file_from_index(opt->repo->index, path))
693 return -1;
695 if (update_working_directory) {
696 if (ignore_case) {
697 struct cache_entry *ce;
698 ce = index_file_exists(opt->repo->index, path, strlen(path),
699 ignore_case);
700 if (ce && ce_stage(ce) == 0 && strcmp(path, ce->name))
701 return 0;
703 if (remove_path(path))
704 return -1;
706 return 0;
709 /* add a string to a strbuf, but converting "/" to "_" */
710 static void add_flattened_path(struct strbuf *out, const char *s)
712 size_t i = out->len;
713 strbuf_addstr(out, s);
714 for (; i < out->len; i++)
715 if (out->buf[i] == '/')
716 out->buf[i] = '_';
719 static char *unique_path(struct merge_options *opt,
720 const char *path,
721 const char *branch)
723 struct path_hashmap_entry *entry;
724 struct strbuf newpath = STRBUF_INIT;
725 int suffix = 0;
726 size_t base_len;
728 strbuf_addf(&newpath, "%s~", path);
729 add_flattened_path(&newpath, branch);
731 base_len = newpath.len;
732 while (hashmap_get_from_hash(&opt->priv->current_file_dir_set,
733 fspathhash(newpath.buf), newpath.buf) ||
734 (!opt->priv->call_depth && file_exists(newpath.buf))) {
735 strbuf_setlen(&newpath, base_len);
736 strbuf_addf(&newpath, "_%d", suffix++);
739 FLEX_ALLOC_MEM(entry, path, newpath.buf, newpath.len);
740 hashmap_entry_init(&entry->e, fspathhash(entry->path));
741 hashmap_add(&opt->priv->current_file_dir_set, &entry->e);
742 return strbuf_detach(&newpath, NULL);
746 * Check whether a directory in the index is in the way of an incoming
747 * file. Return 1 if so. If check_working_copy is non-zero, also
748 * check the working directory. If empty_ok is non-zero, also return
749 * 0 in the case where the working-tree dir exists but is empty.
751 static int dir_in_way(struct index_state *istate, const char *path,
752 int check_working_copy, int empty_ok)
754 int pos;
755 struct strbuf dirpath = STRBUF_INIT;
756 struct stat st;
758 strbuf_addstr(&dirpath, path);
759 strbuf_addch(&dirpath, '/');
761 pos = index_name_pos(istate, dirpath.buf, dirpath.len);
763 if (pos < 0)
764 pos = -1 - pos;
765 if (pos < istate->cache_nr &&
766 !strncmp(dirpath.buf, istate->cache[pos]->name, dirpath.len)) {
767 strbuf_release(&dirpath);
768 return 1;
771 strbuf_release(&dirpath);
772 return check_working_copy && !lstat(path, &st) && S_ISDIR(st.st_mode) &&
773 !(empty_ok && is_empty_dir(path)) &&
774 !has_symlink_leading_path(path, strlen(path));
778 * Returns whether path was tracked in the index before the merge started,
779 * and its oid and mode match the specified values
781 static int was_tracked_and_matches(struct merge_options *opt, const char *path,
782 const struct diff_filespec *blob)
784 int pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
785 struct cache_entry *ce;
787 if (0 > pos)
788 /* we were not tracking this path before the merge */
789 return 0;
791 /* See if the file we were tracking before matches */
792 ce = opt->priv->orig_index.cache[pos];
793 return (oideq(&ce->oid, &blob->oid) && ce->ce_mode == blob->mode);
797 * Returns whether path was tracked in the index before the merge started
799 static int was_tracked(struct merge_options *opt, const char *path)
801 int pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
803 if (0 <= pos)
804 /* we were tracking this path before the merge */
805 return 1;
807 return 0;
810 static int would_lose_untracked(struct merge_options *opt, const char *path)
812 struct index_state *istate = opt->repo->index;
815 * This may look like it can be simplified to:
816 * return !was_tracked(opt, path) && file_exists(path)
817 * but it can't. This function needs to know whether path was in
818 * the working tree due to EITHER having been tracked in the index
819 * before the merge OR having been put into the working copy and
820 * index by unpack_trees(). Due to that either-or requirement, we
821 * check the current index instead of the original one.
823 * Note that we do not need to worry about merge-recursive itself
824 * updating the index after unpack_trees() and before calling this
825 * function, because we strictly require all code paths in
826 * merge-recursive to update the working tree first and the index
827 * second. Doing otherwise would break
828 * update_file()/would_lose_untracked(); see every comment in this
829 * file which mentions "update_stages".
831 int pos = index_name_pos(istate, path, strlen(path));
833 if (pos < 0)
834 pos = -1 - pos;
835 while (pos < istate->cache_nr &&
836 !strcmp(path, istate->cache[pos]->name)) {
838 * If stage #0, it is definitely tracked.
839 * If it has stage #2 then it was tracked
840 * before this merge started. All other
841 * cases the path was not tracked.
843 switch (ce_stage(istate->cache[pos])) {
844 case 0:
845 case 2:
846 return 0;
848 pos++;
850 return file_exists(path);
853 static int was_dirty(struct merge_options *opt, const char *path)
855 struct cache_entry *ce;
856 int dirty = 1;
858 if (opt->priv->call_depth || !was_tracked(opt, path))
859 return !dirty;
861 ce = index_file_exists(opt->priv->unpack_opts.src_index,
862 path, strlen(path), ignore_case);
863 dirty = verify_uptodate(ce, &opt->priv->unpack_opts) != 0;
864 return dirty;
867 static int make_room_for_path(struct merge_options *opt, const char *path)
869 int status, i;
870 const char *msg = _("failed to create path '%s'%s");
872 /* Unlink any D/F conflict files that are in the way */
873 for (i = 0; i < opt->priv->df_conflict_file_set.nr; i++) {
874 const char *df_path = opt->priv->df_conflict_file_set.items[i].string;
875 size_t pathlen = strlen(path);
876 size_t df_pathlen = strlen(df_path);
877 if (df_pathlen < pathlen &&
878 path[df_pathlen] == '/' &&
879 strncmp(path, df_path, df_pathlen) == 0) {
880 output(opt, 3,
881 _("Removing %s to make room for subdirectory\n"),
882 df_path);
883 unlink(df_path);
884 unsorted_string_list_delete_item(&opt->priv->df_conflict_file_set,
885 i, 0);
886 break;
890 /* Make sure leading directories are created */
891 status = safe_create_leading_directories_const(path);
892 if (status) {
893 if (status == SCLD_EXISTS)
894 /* something else exists */
895 return err(opt, msg, path, _(": perhaps a D/F conflict?"));
896 return err(opt, msg, path, "");
900 * Do not unlink a file in the work tree if we are not
901 * tracking it.
903 if (would_lose_untracked(opt, path))
904 return err(opt, _("refusing to lose untracked file at '%s'"),
905 path);
907 /* Successful unlink is good.. */
908 if (!unlink(path))
909 return 0;
910 /* .. and so is no existing file */
911 if (errno == ENOENT)
912 return 0;
913 /* .. but not some other error (who really cares what?) */
914 return err(opt, msg, path, _(": perhaps a D/F conflict?"));
917 static int update_file_flags(struct merge_options *opt,
918 const struct diff_filespec *contents,
919 const char *path,
920 int update_cache,
921 int update_wd)
923 int ret = 0;
925 if (opt->priv->call_depth)
926 update_wd = 0;
928 if (update_wd) {
929 enum object_type type;
930 void *buf;
931 unsigned long size;
933 if (S_ISGITLINK(contents->mode)) {
935 * We may later decide to recursively descend into
936 * the submodule directory and update its index
937 * and/or work tree, but we do not do that now.
939 update_wd = 0;
940 goto update_index;
943 buf = read_object_file(&contents->oid, &type, &size);
944 if (!buf) {
945 ret = err(opt, _("cannot read object %s '%s'"),
946 oid_to_hex(&contents->oid), path);
947 goto free_buf;
949 if (type != OBJ_BLOB) {
950 ret = err(opt, _("blob expected for %s '%s'"),
951 oid_to_hex(&contents->oid), path);
952 goto free_buf;
954 if (S_ISREG(contents->mode)) {
955 struct strbuf strbuf = STRBUF_INIT;
956 if (convert_to_working_tree(opt->repo->index,
957 path, buf, size, &strbuf, NULL)) {
958 free(buf);
959 size = strbuf.len;
960 buf = strbuf_detach(&strbuf, NULL);
964 if (make_room_for_path(opt, path) < 0) {
965 update_wd = 0;
966 goto free_buf;
968 if (S_ISREG(contents->mode) ||
969 (!has_symlinks && S_ISLNK(contents->mode))) {
970 int fd;
971 int mode = (contents->mode & 0100 ? 0777 : 0666);
973 fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode);
974 if (fd < 0) {
975 ret = err(opt, _("failed to open '%s': %s"),
976 path, strerror(errno));
977 goto free_buf;
979 write_in_full(fd, buf, size);
980 close(fd);
981 } else if (S_ISLNK(contents->mode)) {
982 char *lnk = xmemdupz(buf, size);
983 safe_create_leading_directories_const(path);
984 unlink(path);
985 if (symlink(lnk, path))
986 ret = err(opt, _("failed to symlink '%s': %s"),
987 path, strerror(errno));
988 free(lnk);
989 } else
990 ret = err(opt,
991 _("do not know what to do with %06o %s '%s'"),
992 contents->mode, oid_to_hex(&contents->oid), path);
993 free_buf:
994 free(buf);
996 update_index:
997 if (!ret && update_cache) {
998 int refresh = (!opt->priv->call_depth &&
999 contents->mode != S_IFGITLINK);
1000 if (add_cacheinfo(opt, contents, path, 0, refresh,
1001 ADD_CACHE_OK_TO_ADD))
1002 return -1;
1004 return ret;
1007 static int update_file(struct merge_options *opt,
1008 int clean,
1009 const struct diff_filespec *contents,
1010 const char *path)
1012 return update_file_flags(opt, contents, path,
1013 opt->priv->call_depth || clean, !opt->priv->call_depth);
1016 /* Low level file merging, update and removal */
1018 struct merge_file_info {
1019 struct diff_filespec blob; /* mostly use oid & mode; sometimes path */
1020 unsigned clean:1,
1021 merge:1;
1024 static int merge_3way(struct merge_options *opt,
1025 mmbuffer_t *result_buf,
1026 const struct diff_filespec *o,
1027 const struct diff_filespec *a,
1028 const struct diff_filespec *b,
1029 const char *branch1,
1030 const char *branch2,
1031 const int extra_marker_size)
1033 mmfile_t orig, src1, src2;
1034 struct ll_merge_options ll_opts = {0};
1035 char *base, *name1, *name2;
1036 int merge_status;
1038 ll_opts.renormalize = opt->renormalize;
1039 ll_opts.extra_marker_size = extra_marker_size;
1040 ll_opts.xdl_opts = opt->xdl_opts;
1042 if (opt->priv->call_depth) {
1043 ll_opts.virtual_ancestor = 1;
1044 ll_opts.variant = 0;
1045 } else {
1046 switch (opt->recursive_variant) {
1047 case MERGE_VARIANT_OURS:
1048 ll_opts.variant = XDL_MERGE_FAVOR_OURS;
1049 break;
1050 case MERGE_VARIANT_THEIRS:
1051 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
1052 break;
1053 default:
1054 ll_opts.variant = 0;
1055 break;
1059 assert(a->path && b->path && o->path && opt->ancestor);
1060 if (strcmp(a->path, b->path) || strcmp(a->path, o->path) != 0) {
1061 base = mkpathdup("%s:%s", opt->ancestor, o->path);
1062 name1 = mkpathdup("%s:%s", branch1, a->path);
1063 name2 = mkpathdup("%s:%s", branch2, b->path);
1064 } else {
1065 base = mkpathdup("%s", opt->ancestor);
1066 name1 = mkpathdup("%s", branch1);
1067 name2 = mkpathdup("%s", branch2);
1070 read_mmblob(&orig, &o->oid);
1071 read_mmblob(&src1, &a->oid);
1072 read_mmblob(&src2, &b->oid);
1075 * FIXME: Using a->path for normalization rules in ll_merge could be
1076 * wrong if we renamed from a->path to b->path. We should use the
1077 * target path for where the file will be written.
1079 merge_status = ll_merge(result_buf, a->path, &orig, base,
1080 &src1, name1, &src2, name2,
1081 opt->repo->index, &ll_opts);
1083 free(base);
1084 free(name1);
1085 free(name2);
1086 free(orig.ptr);
1087 free(src1.ptr);
1088 free(src2.ptr);
1089 return merge_status;
1092 static int find_first_merges(struct repository *repo,
1093 struct object_array *result, const char *path,
1094 struct commit *a, struct commit *b)
1096 int i, j;
1097 struct object_array merges = OBJECT_ARRAY_INIT;
1098 struct commit *commit;
1099 int contains_another;
1101 char merged_revision[GIT_MAX_HEXSZ + 2];
1102 const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1103 "--all", merged_revision, NULL };
1104 struct rev_info revs;
1105 struct setup_revision_opt rev_opts;
1107 memset(result, 0, sizeof(struct object_array));
1108 memset(&rev_opts, 0, sizeof(rev_opts));
1110 /* get all revisions that merge commit a */
1111 xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
1112 oid_to_hex(&a->object.oid));
1113 repo_init_revisions(repo, &revs, NULL);
1114 /* FIXME: can't handle linked worktrees in submodules yet */
1115 revs.single_worktree = path != NULL;
1116 setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1118 /* save all revisions from the above list that contain b */
1119 if (prepare_revision_walk(&revs))
1120 die("revision walk setup failed");
1121 while ((commit = get_revision(&revs)) != NULL) {
1122 struct object *o = &(commit->object);
1123 if (repo_in_merge_bases(repo, b, commit))
1124 add_object_array(o, NULL, &merges);
1126 reset_revision_walk();
1128 /* Now we've got all merges that contain a and b. Prune all
1129 * merges that contain another found merge and save them in
1130 * result.
1132 for (i = 0; i < merges.nr; i++) {
1133 struct commit *m1 = (struct commit *) merges.objects[i].item;
1135 contains_another = 0;
1136 for (j = 0; j < merges.nr; j++) {
1137 struct commit *m2 = (struct commit *) merges.objects[j].item;
1138 if (i != j && repo_in_merge_bases(repo, m2, m1)) {
1139 contains_another = 1;
1140 break;
1144 if (!contains_another)
1145 add_object_array(merges.objects[i].item, NULL, result);
1148 object_array_clear(&merges);
1149 return result->nr;
1152 static void print_commit(struct commit *commit)
1154 struct strbuf sb = STRBUF_INIT;
1155 struct pretty_print_context ctx = {0};
1156 ctx.date_mode.type = DATE_NORMAL;
1157 /* FIXME: Merge this with output_commit_title() */
1158 assert(!merge_remote_util(commit));
1159 format_commit_message(commit, " %h: %m %s", &sb, &ctx);
1160 fprintf(stderr, "%s\n", sb.buf);
1161 strbuf_release(&sb);
1164 static int is_valid(const struct diff_filespec *dfs)
1166 return dfs->mode != 0 && !is_null_oid(&dfs->oid);
1169 static int merge_submodule(struct merge_options *opt,
1170 struct object_id *result, const char *path,
1171 const struct object_id *base, const struct object_id *a,
1172 const struct object_id *b)
1174 struct repository subrepo;
1175 int ret = 0;
1176 struct commit *commit_base, *commit_a, *commit_b;
1177 int parent_count;
1178 struct object_array merges;
1180 int i;
1181 int search = !opt->priv->call_depth;
1183 /* store a in result in case we fail */
1184 /* FIXME: This is the WRONG resolution for the recursive case when
1185 * we need to be careful to avoid accidentally matching either side.
1186 * Should probably use o instead there, much like we do for merging
1187 * binaries.
1189 oidcpy(result, a);
1191 /* we can not handle deletion conflicts */
1192 if (is_null_oid(base))
1193 return 0;
1194 if (is_null_oid(a))
1195 return 0;
1196 if (is_null_oid(b))
1197 return 0;
1200 * NEEDSWORK: Remove this when all submodule object accesses are
1201 * through explicitly specified repositores.
1203 if (add_submodule_odb(path)) {
1204 output(opt, 1, _("Failed to merge submodule %s (not checked out)"), path);
1205 return 0;
1208 if (repo_submodule_init(&subrepo, opt->repo, path, null_oid())) {
1209 output(opt, 1, _("Failed to merge submodule %s (not checked out)"), path);
1210 return 0;
1213 if (!(commit_base = lookup_commit_reference(&subrepo, base)) ||
1214 !(commit_a = lookup_commit_reference(&subrepo, a)) ||
1215 !(commit_b = lookup_commit_reference(&subrepo, b))) {
1216 output(opt, 1, _("Failed to merge submodule %s (commits not present)"), path);
1217 goto cleanup;
1220 /* check whether both changes are forward */
1221 if (!repo_in_merge_bases(&subrepo, commit_base, commit_a) ||
1222 !repo_in_merge_bases(&subrepo, commit_base, commit_b)) {
1223 output(opt, 1, _("Failed to merge submodule %s (commits don't follow merge-base)"), path);
1224 goto cleanup;
1227 /* Case #1: a is contained in b or vice versa */
1228 if (repo_in_merge_bases(&subrepo, commit_a, commit_b)) {
1229 oidcpy(result, b);
1230 if (show(opt, 3)) {
1231 output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
1232 output_commit_title(opt, commit_b);
1233 } else if (show(opt, 2))
1234 output(opt, 2, _("Fast-forwarding submodule %s"), path);
1235 else
1236 ; /* no output */
1238 ret = 1;
1239 goto cleanup;
1241 if (repo_in_merge_bases(&subrepo, commit_b, commit_a)) {
1242 oidcpy(result, a);
1243 if (show(opt, 3)) {
1244 output(opt, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
1245 output_commit_title(opt, commit_a);
1246 } else if (show(opt, 2))
1247 output(opt, 2, _("Fast-forwarding submodule %s"), path);
1248 else
1249 ; /* no output */
1251 ret = 1;
1252 goto cleanup;
1256 * Case #2: There are one or more merges that contain a and b in
1257 * the submodule. If there is only one, then present it as a
1258 * suggestion to the user, but leave it marked unmerged so the
1259 * user needs to confirm the resolution.
1262 /* Skip the search if makes no sense to the calling context. */
1263 if (!search)
1264 goto cleanup;
1266 /* find commit which merges them */
1267 parent_count = find_first_merges(&subrepo, &merges, path,
1268 commit_a, commit_b);
1269 switch (parent_count) {
1270 case 0:
1271 output(opt, 1, _("Failed to merge submodule %s (merge following commits not found)"), path);
1272 break;
1274 case 1:
1275 output(opt, 1, _("Failed to merge submodule %s (not fast-forward)"), path);
1276 output(opt, 2, _("Found a possible merge resolution for the submodule:\n"));
1277 print_commit((struct commit *) merges.objects[0].item);
1278 output(opt, 2, _(
1279 "If this is correct simply add it to the index "
1280 "for example\n"
1281 "by using:\n\n"
1282 " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1283 "which will accept this suggestion.\n"),
1284 oid_to_hex(&merges.objects[0].item->oid), path);
1285 break;
1287 default:
1288 output(opt, 1, _("Failed to merge submodule %s (multiple merges found)"), path);
1289 for (i = 0; i < merges.nr; i++)
1290 print_commit((struct commit *) merges.objects[i].item);
1293 object_array_clear(&merges);
1294 cleanup:
1295 repo_clear(&subrepo);
1296 return ret;
1299 static int merge_mode_and_contents(struct merge_options *opt,
1300 const struct diff_filespec *o,
1301 const struct diff_filespec *a,
1302 const struct diff_filespec *b,
1303 const char *filename,
1304 const char *branch1,
1305 const char *branch2,
1306 const int extra_marker_size,
1307 struct merge_file_info *result)
1309 if (opt->branch1 != branch1) {
1311 * It's weird getting a reverse merge with HEAD on the bottom
1312 * side of the conflict markers and the other branch on the
1313 * top. Fix that.
1315 return merge_mode_and_contents(opt, o, b, a,
1316 filename,
1317 branch2, branch1,
1318 extra_marker_size, result);
1321 result->merge = 0;
1322 result->clean = 1;
1324 if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) {
1325 result->clean = 0;
1327 * FIXME: This is a bad resolution for recursive case; for
1328 * the recursive case we want something that is unlikely to
1329 * accidentally match either side. Also, while it makes
1330 * sense to prefer regular files over symlinks, it doesn't
1331 * make sense to prefer regular files over submodules.
1333 if (S_ISREG(a->mode)) {
1334 result->blob.mode = a->mode;
1335 oidcpy(&result->blob.oid, &a->oid);
1336 } else {
1337 result->blob.mode = b->mode;
1338 oidcpy(&result->blob.oid, &b->oid);
1340 } else {
1341 if (!oideq(&a->oid, &o->oid) && !oideq(&b->oid, &o->oid))
1342 result->merge = 1;
1345 * Merge modes
1347 if (a->mode == b->mode || a->mode == o->mode)
1348 result->blob.mode = b->mode;
1349 else {
1350 result->blob.mode = a->mode;
1351 if (b->mode != o->mode) {
1352 result->clean = 0;
1353 result->merge = 1;
1357 if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
1358 oidcpy(&result->blob.oid, &b->oid);
1359 else if (oideq(&b->oid, &o->oid))
1360 oidcpy(&result->blob.oid, &a->oid);
1361 else if (S_ISREG(a->mode)) {
1362 mmbuffer_t result_buf;
1363 int ret = 0, merge_status;
1365 merge_status = merge_3way(opt, &result_buf, o, a, b,
1366 branch1, branch2,
1367 extra_marker_size);
1369 if ((merge_status < 0) || !result_buf.ptr)
1370 ret = err(opt, _("Failed to execute internal merge"));
1372 if (!ret &&
1373 write_object_file(result_buf.ptr, result_buf.size,
1374 blob_type, &result->blob.oid))
1375 ret = err(opt, _("Unable to add %s to database"),
1376 a->path);
1378 free(result_buf.ptr);
1379 if (ret)
1380 return ret;
1381 /* FIXME: bug, what if modes didn't match? */
1382 result->clean = (merge_status == 0);
1383 } else if (S_ISGITLINK(a->mode)) {
1384 result->clean = merge_submodule(opt, &result->blob.oid,
1385 o->path,
1386 &o->oid,
1387 &a->oid,
1388 &b->oid);
1389 } else if (S_ISLNK(a->mode)) {
1390 switch (opt->recursive_variant) {
1391 case MERGE_VARIANT_NORMAL:
1392 oidcpy(&result->blob.oid, &a->oid);
1393 if (!oideq(&a->oid, &b->oid))
1394 result->clean = 0;
1395 break;
1396 case MERGE_VARIANT_OURS:
1397 oidcpy(&result->blob.oid, &a->oid);
1398 break;
1399 case MERGE_VARIANT_THEIRS:
1400 oidcpy(&result->blob.oid, &b->oid);
1401 break;
1403 } else
1404 BUG("unsupported object type in the tree");
1407 if (result->merge)
1408 output(opt, 2, _("Auto-merging %s"), filename);
1410 return 0;
1413 static int handle_rename_via_dir(struct merge_options *opt,
1414 struct rename_conflict_info *ci)
1417 * Handle file adds that need to be renamed due to directory rename
1418 * detection. This differs from handle_rename_normal, because
1419 * there is no content merge to do; just move the file into the
1420 * desired final location.
1422 const struct rename *ren = ci->ren1;
1423 const struct diff_filespec *dest = ren->pair->two;
1424 char *file_path = dest->path;
1425 int mark_conflicted = (opt->detect_directory_renames ==
1426 MERGE_DIRECTORY_RENAMES_CONFLICT);
1427 assert(ren->dir_rename_original_dest);
1429 if (!opt->priv->call_depth && would_lose_untracked(opt, dest->path)) {
1430 mark_conflicted = 1;
1431 file_path = unique_path(opt, dest->path, ren->branch);
1432 output(opt, 1, _("Error: Refusing to lose untracked file at %s; "
1433 "writing to %s instead."),
1434 dest->path, file_path);
1437 if (mark_conflicted) {
1439 * Write the file in worktree at file_path. In the index,
1440 * only record the file at dest->path in the appropriate
1441 * higher stage.
1443 if (update_file(opt, 0, dest, file_path))
1444 return -1;
1445 if (file_path != dest->path)
1446 free(file_path);
1447 if (update_stages(opt, dest->path, NULL,
1448 ren->branch == opt->branch1 ? dest : NULL,
1449 ren->branch == opt->branch1 ? NULL : dest))
1450 return -1;
1451 return 0; /* not clean, but conflicted */
1452 } else {
1453 /* Update dest->path both in index and in worktree */
1454 if (update_file(opt, 1, dest, dest->path))
1455 return -1;
1456 return 1; /* clean */
1460 static int handle_change_delete(struct merge_options *opt,
1461 const char *path, const char *old_path,
1462 const struct diff_filespec *o,
1463 const struct diff_filespec *changed,
1464 const char *change_branch,
1465 const char *delete_branch,
1466 const char *change, const char *change_past)
1468 char *alt_path = NULL;
1469 const char *update_path = path;
1470 int ret = 0;
1472 if (dir_in_way(opt->repo->index, path, !opt->priv->call_depth, 0) ||
1473 (!opt->priv->call_depth && would_lose_untracked(opt, path))) {
1474 update_path = alt_path = unique_path(opt, path, change_branch);
1477 if (opt->priv->call_depth) {
1479 * We cannot arbitrarily accept either a_sha or b_sha as
1480 * correct; since there is no true "middle point" between
1481 * them, simply reuse the base version for virtual merge base.
1483 ret = remove_file_from_index(opt->repo->index, path);
1484 if (!ret)
1485 ret = update_file(opt, 0, o, update_path);
1486 } else {
1488 * Despite the four nearly duplicate messages and argument
1489 * lists below and the ugliness of the nested if-statements,
1490 * having complete messages makes the job easier for
1491 * translators.
1493 * The slight variance among the cases is due to the fact
1494 * that:
1495 * 1) directory/file conflicts (in effect if
1496 * !alt_path) could cause us to need to write the
1497 * file to a different path.
1498 * 2) renames (in effect if !old_path) could mean that
1499 * there are two names for the path that the user
1500 * may know the file by.
1502 if (!alt_path) {
1503 if (!old_path) {
1504 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1505 "and %s in %s. Version %s of %s left in tree."),
1506 change, path, delete_branch, change_past,
1507 change_branch, change_branch, path);
1508 } else {
1509 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1510 "and %s to %s in %s. Version %s of %s left in tree."),
1511 change, old_path, delete_branch, change_past, path,
1512 change_branch, change_branch, path);
1514 } else {
1515 if (!old_path) {
1516 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1517 "and %s in %s. Version %s of %s left in tree at %s."),
1518 change, path, delete_branch, change_past,
1519 change_branch, change_branch, path, alt_path);
1520 } else {
1521 output(opt, 1, _("CONFLICT (%s/delete): %s deleted in %s "
1522 "and %s to %s in %s. Version %s of %s left in tree at %s."),
1523 change, old_path, delete_branch, change_past, path,
1524 change_branch, change_branch, path, alt_path);
1528 * No need to call update_file() on path when change_branch ==
1529 * opt->branch1 && !alt_path, since that would needlessly touch
1530 * path. We could call update_file_flags() with update_cache=0
1531 * and update_wd=0, but that's a no-op.
1533 if (change_branch != opt->branch1 || alt_path)
1534 ret = update_file(opt, 0, changed, update_path);
1536 free(alt_path);
1538 return ret;
1541 static int handle_rename_delete(struct merge_options *opt,
1542 struct rename_conflict_info *ci)
1544 const struct rename *ren = ci->ren1;
1545 const struct diff_filespec *orig = ren->pair->one;
1546 const struct diff_filespec *dest = ren->pair->two;
1547 const char *rename_branch = ren->branch;
1548 const char *delete_branch = (opt->branch1 == ren->branch ?
1549 opt->branch2 : opt->branch1);
1551 if (handle_change_delete(opt,
1552 opt->priv->call_depth ? orig->path : dest->path,
1553 opt->priv->call_depth ? NULL : orig->path,
1554 orig, dest,
1555 rename_branch, delete_branch,
1556 _("rename"), _("renamed")))
1557 return -1;
1559 if (opt->priv->call_depth)
1560 return remove_file_from_index(opt->repo->index, dest->path);
1561 else
1562 return update_stages(opt, dest->path, NULL,
1563 rename_branch == opt->branch1 ? dest : NULL,
1564 rename_branch == opt->branch1 ? NULL : dest);
1567 static int handle_file_collision(struct merge_options *opt,
1568 const char *collide_path,
1569 const char *prev_path1,
1570 const char *prev_path2,
1571 const char *branch1, const char *branch2,
1572 struct diff_filespec *a,
1573 struct diff_filespec *b)
1575 struct merge_file_info mfi;
1576 struct diff_filespec null;
1577 char *alt_path = NULL;
1578 const char *update_path = collide_path;
1581 * It's easiest to get the correct things into stage 2 and 3, and
1582 * to make sure that the content merge puts HEAD before the other
1583 * branch if we just ensure that branch1 == opt->branch1. So, simply
1584 * flip arguments around if we don't have that.
1586 if (branch1 != opt->branch1) {
1587 return handle_file_collision(opt, collide_path,
1588 prev_path2, prev_path1,
1589 branch2, branch1,
1590 b, a);
1593 /* Remove rename sources if rename/add or rename/rename(2to1) */
1594 if (prev_path1)
1595 remove_file(opt, 1, prev_path1,
1596 opt->priv->call_depth || would_lose_untracked(opt, prev_path1));
1597 if (prev_path2)
1598 remove_file(opt, 1, prev_path2,
1599 opt->priv->call_depth || would_lose_untracked(opt, prev_path2));
1602 * Remove the collision path, if it wouldn't cause dirty contents
1603 * or an untracked file to get lost. We'll either overwrite with
1604 * merged contents, or just write out to differently named files.
1606 if (was_dirty(opt, collide_path)) {
1607 output(opt, 1, _("Refusing to lose dirty file at %s"),
1608 collide_path);
1609 update_path = alt_path = unique_path(opt, collide_path, "merged");
1610 } else if (would_lose_untracked(opt, collide_path)) {
1612 * Only way we get here is if both renames were from
1613 * a directory rename AND user had an untracked file
1614 * at the location where both files end up after the
1615 * two directory renames. See testcase 10d of t6043.
1617 output(opt, 1, _("Refusing to lose untracked file at "
1618 "%s, even though it's in the way."),
1619 collide_path);
1620 update_path = alt_path = unique_path(opt, collide_path, "merged");
1621 } else {
1623 * FIXME: It's possible that the two files are identical
1624 * and that the current working copy happens to match, in
1625 * which case we are unnecessarily touching the working
1626 * tree file. It's not a likely enough scenario that I
1627 * want to code up the checks for it and a better fix is
1628 * available if we restructure how unpack_trees() and
1629 * merge-recursive interoperate anyway, so punting for
1630 * now...
1632 remove_file(opt, 0, collide_path, 0);
1635 /* Store things in diff_filespecs for functions that need it */
1636 null.path = (char *)collide_path;
1637 oidcpy(&null.oid, null_oid());
1638 null.mode = 0;
1640 if (merge_mode_and_contents(opt, &null, a, b, collide_path,
1641 branch1, branch2, opt->priv->call_depth * 2, &mfi))
1642 return -1;
1643 mfi.clean &= !alt_path;
1644 if (update_file(opt, mfi.clean, &mfi.blob, update_path))
1645 return -1;
1646 if (!mfi.clean && !opt->priv->call_depth &&
1647 update_stages(opt, collide_path, NULL, a, b))
1648 return -1;
1649 free(alt_path);
1651 * FIXME: If both a & b both started with conflicts (only possible
1652 * if they came from a rename/rename(2to1)), but had IDENTICAL
1653 * contents including those conflicts, then in the next line we claim
1654 * it was clean. If someone cares about this case, we should have the
1655 * caller notify us if we started with conflicts.
1657 return mfi.clean;
1660 static int handle_rename_add(struct merge_options *opt,
1661 struct rename_conflict_info *ci)
1663 /* a was renamed to c, and a separate c was added. */
1664 struct diff_filespec *a = ci->ren1->pair->one;
1665 struct diff_filespec *c = ci->ren1->pair->two;
1666 char *path = c->path;
1667 char *prev_path_desc;
1668 struct merge_file_info mfi;
1670 const char *rename_branch = ci->ren1->branch;
1671 const char *add_branch = (opt->branch1 == rename_branch ?
1672 opt->branch2 : opt->branch1);
1673 int other_stage = (ci->ren1->branch == opt->branch1 ? 3 : 2);
1675 output(opt, 1, _("CONFLICT (rename/add): "
1676 "Rename %s->%s in %s. Added %s in %s"),
1677 a->path, c->path, rename_branch,
1678 c->path, add_branch);
1680 prev_path_desc = xstrfmt("version of %s from %s", path, a->path);
1681 ci->ren1->src_entry->stages[other_stage].path = a->path;
1682 if (merge_mode_and_contents(opt, a, c,
1683 &ci->ren1->src_entry->stages[other_stage],
1684 prev_path_desc,
1685 opt->branch1, opt->branch2,
1686 1 + opt->priv->call_depth * 2, &mfi))
1687 return -1;
1688 free(prev_path_desc);
1690 ci->ren1->dst_entry->stages[other_stage].path = mfi.blob.path = c->path;
1691 return handle_file_collision(opt,
1692 c->path, a->path, NULL,
1693 rename_branch, add_branch,
1694 &mfi.blob,
1695 &ci->ren1->dst_entry->stages[other_stage]);
1698 static char *find_path_for_conflict(struct merge_options *opt,
1699 const char *path,
1700 const char *branch1,
1701 const char *branch2)
1703 char *new_path = NULL;
1704 if (dir_in_way(opt->repo->index, path, !opt->priv->call_depth, 0)) {
1705 new_path = unique_path(opt, path, branch1);
1706 output(opt, 1, _("%s is a directory in %s adding "
1707 "as %s instead"),
1708 path, branch2, new_path);
1709 } else if (would_lose_untracked(opt, path)) {
1710 new_path = unique_path(opt, path, branch1);
1711 output(opt, 1, _("Refusing to lose untracked file"
1712 " at %s; adding as %s instead"),
1713 path, new_path);
1716 return new_path;
1720 * Toggle the stage number between "ours" and "theirs" (2 and 3).
1722 static inline int flip_stage(int stage)
1724 return (2 + 3) - stage;
1727 static int handle_rename_rename_1to2(struct merge_options *opt,
1728 struct rename_conflict_info *ci)
1730 /* One file was renamed in both branches, but to different names. */
1731 struct merge_file_info mfi;
1732 struct diff_filespec *add;
1733 struct diff_filespec *o = ci->ren1->pair->one;
1734 struct diff_filespec *a = ci->ren1->pair->two;
1735 struct diff_filespec *b = ci->ren2->pair->two;
1736 char *path_desc;
1738 output(opt, 1, _("CONFLICT (rename/rename): "
1739 "Rename \"%s\"->\"%s\" in branch \"%s\" "
1740 "rename \"%s\"->\"%s\" in \"%s\"%s"),
1741 o->path, a->path, ci->ren1->branch,
1742 o->path, b->path, ci->ren2->branch,
1743 opt->priv->call_depth ? _(" (left unresolved)") : "");
1745 path_desc = xstrfmt("%s and %s, both renamed from %s",
1746 a->path, b->path, o->path);
1747 if (merge_mode_and_contents(opt, o, a, b, path_desc,
1748 ci->ren1->branch, ci->ren2->branch,
1749 opt->priv->call_depth * 2, &mfi))
1750 return -1;
1751 free(path_desc);
1753 if (opt->priv->call_depth)
1754 remove_file_from_index(opt->repo->index, o->path);
1757 * For each destination path, we need to see if there is a
1758 * rename/add collision. If not, we can write the file out
1759 * to the specified location.
1761 add = &ci->ren1->dst_entry->stages[flip_stage(2)];
1762 if (is_valid(add)) {
1763 add->path = mfi.blob.path = a->path;
1764 if (handle_file_collision(opt, a->path,
1765 NULL, NULL,
1766 ci->ren1->branch,
1767 ci->ren2->branch,
1768 &mfi.blob, add) < 0)
1769 return -1;
1770 } else {
1771 char *new_path = find_path_for_conflict(opt, a->path,
1772 ci->ren1->branch,
1773 ci->ren2->branch);
1774 if (update_file(opt, 0, &mfi.blob,
1775 new_path ? new_path : a->path))
1776 return -1;
1777 free(new_path);
1778 if (!opt->priv->call_depth &&
1779 update_stages(opt, a->path, NULL, a, NULL))
1780 return -1;
1783 if (!mfi.clean && mfi.blob.mode == a->mode &&
1784 oideq(&mfi.blob.oid, &a->oid)) {
1786 * Getting here means we were attempting to merge a binary
1787 * blob. Since we can't merge binaries, the merge algorithm
1788 * just takes one side. But we don't want to copy the
1789 * contents of one side to both paths; we'd rather use the
1790 * original content at the given path for each path.
1792 oidcpy(&mfi.blob.oid, &b->oid);
1793 mfi.blob.mode = b->mode;
1795 add = &ci->ren2->dst_entry->stages[flip_stage(3)];
1796 if (is_valid(add)) {
1797 add->path = mfi.blob.path = b->path;
1798 if (handle_file_collision(opt, b->path,
1799 NULL, NULL,
1800 ci->ren1->branch,
1801 ci->ren2->branch,
1802 add, &mfi.blob) < 0)
1803 return -1;
1804 } else {
1805 char *new_path = find_path_for_conflict(opt, b->path,
1806 ci->ren2->branch,
1807 ci->ren1->branch);
1808 if (update_file(opt, 0, &mfi.blob,
1809 new_path ? new_path : b->path))
1810 return -1;
1811 free(new_path);
1812 if (!opt->priv->call_depth &&
1813 update_stages(opt, b->path, NULL, NULL, b))
1814 return -1;
1817 return 0;
1820 static int handle_rename_rename_2to1(struct merge_options *opt,
1821 struct rename_conflict_info *ci)
1823 /* Two files, a & b, were renamed to the same thing, c. */
1824 struct diff_filespec *a = ci->ren1->pair->one;
1825 struct diff_filespec *b = ci->ren2->pair->one;
1826 struct diff_filespec *c1 = ci->ren1->pair->two;
1827 struct diff_filespec *c2 = ci->ren2->pair->two;
1828 char *path = c1->path; /* == c2->path */
1829 char *path_side_1_desc;
1830 char *path_side_2_desc;
1831 struct merge_file_info mfi_c1;
1832 struct merge_file_info mfi_c2;
1833 int ostage1, ostage2;
1835 output(opt, 1, _("CONFLICT (rename/rename): "
1836 "Rename %s->%s in %s. "
1837 "Rename %s->%s in %s"),
1838 a->path, c1->path, ci->ren1->branch,
1839 b->path, c2->path, ci->ren2->branch);
1841 path_side_1_desc = xstrfmt("version of %s from %s", path, a->path);
1842 path_side_2_desc = xstrfmt("version of %s from %s", path, b->path);
1843 ostage1 = ci->ren1->branch == opt->branch1 ? 3 : 2;
1844 ostage2 = flip_stage(ostage1);
1845 ci->ren1->src_entry->stages[ostage1].path = a->path;
1846 ci->ren2->src_entry->stages[ostage2].path = b->path;
1847 if (merge_mode_and_contents(opt, a, c1,
1848 &ci->ren1->src_entry->stages[ostage1],
1849 path_side_1_desc,
1850 opt->branch1, opt->branch2,
1851 1 + opt->priv->call_depth * 2, &mfi_c1) ||
1852 merge_mode_and_contents(opt, b,
1853 &ci->ren2->src_entry->stages[ostage2],
1854 c2, path_side_2_desc,
1855 opt->branch1, opt->branch2,
1856 1 + opt->priv->call_depth * 2, &mfi_c2))
1857 return -1;
1858 free(path_side_1_desc);
1859 free(path_side_2_desc);
1860 mfi_c1.blob.path = path;
1861 mfi_c2.blob.path = path;
1863 return handle_file_collision(opt, path, a->path, b->path,
1864 ci->ren1->branch, ci->ren2->branch,
1865 &mfi_c1.blob, &mfi_c2.blob);
1869 * Get the diff_filepairs changed between o_tree and tree.
1871 static struct diff_queue_struct *get_diffpairs(struct merge_options *opt,
1872 struct tree *o_tree,
1873 struct tree *tree)
1875 struct diff_queue_struct *ret;
1876 struct diff_options opts;
1878 repo_diff_setup(opt->repo, &opts);
1879 opts.flags.recursive = 1;
1880 opts.flags.rename_empty = 0;
1881 opts.detect_rename = merge_detect_rename(opt);
1883 * We do not have logic to handle the detection of copies. In
1884 * fact, it may not even make sense to add such logic: would we
1885 * really want a change to a base file to be propagated through
1886 * multiple other files by a merge?
1888 if (opts.detect_rename > DIFF_DETECT_RENAME)
1889 opts.detect_rename = DIFF_DETECT_RENAME;
1890 opts.rename_limit = (opt->rename_limit >= 0) ? opt->rename_limit : 7000;
1891 opts.rename_score = opt->rename_score;
1892 opts.show_rename_progress = opt->show_rename_progress;
1893 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1894 diff_setup_done(&opts);
1895 diff_tree_oid(&o_tree->object.oid, &tree->object.oid, "", &opts);
1896 diffcore_std(&opts);
1897 if (opts.needed_rename_limit > opt->priv->needed_rename_limit)
1898 opt->priv->needed_rename_limit = opts.needed_rename_limit;
1900 ret = xmalloc(sizeof(*ret));
1901 *ret = diff_queued_diff;
1903 opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1904 diff_queued_diff.nr = 0;
1905 diff_queued_diff.queue = NULL;
1906 diff_flush(&opts);
1907 return ret;
1910 static int tree_has_path(struct repository *r, struct tree *tree,
1911 const char *path)
1913 struct object_id hashy;
1914 unsigned short mode_o;
1916 return !get_tree_entry(r,
1917 &tree->object.oid, path,
1918 &hashy, &mode_o);
1922 * Return a new string that replaces the beginning portion (which matches
1923 * entry->dir), with entry->new_dir. In perl-speak:
1924 * new_path_name = (old_path =~ s/entry->dir/entry->new_dir/);
1925 * NOTE:
1926 * Caller must ensure that old_path starts with entry->dir + '/'.
1928 static char *apply_dir_rename(struct dir_rename_entry *entry,
1929 const char *old_path)
1931 struct strbuf new_path = STRBUF_INIT;
1932 int oldlen, newlen;
1934 if (entry->non_unique_new_dir)
1935 return NULL;
1937 oldlen = strlen(entry->dir);
1938 if (entry->new_dir.len == 0)
1940 * If someone renamed/merged a subdirectory into the root
1941 * directory (e.g. 'some/subdir' -> ''), then we want to
1942 * avoid returning
1943 * '' + '/filename'
1944 * as the rename; we need to make old_path + oldlen advance
1945 * past the '/' character.
1947 oldlen++;
1948 newlen = entry->new_dir.len + (strlen(old_path) - oldlen) + 1;
1949 strbuf_grow(&new_path, newlen);
1950 strbuf_addbuf(&new_path, &entry->new_dir);
1951 strbuf_addstr(&new_path, &old_path[oldlen]);
1953 return strbuf_detach(&new_path, NULL);
1956 static void get_renamed_dir_portion(const char *old_path, const char *new_path,
1957 char **old_dir, char **new_dir)
1959 char *end_of_old, *end_of_new;
1961 /* Default return values: NULL, meaning no rename */
1962 *old_dir = NULL;
1963 *new_dir = NULL;
1966 * For
1967 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
1968 * the "e/foo.c" part is the same, we just want to know that
1969 * "a/b/c/d" was renamed to "a/b/some/thing/else"
1970 * so, for this example, this function returns "a/b/c/d" in
1971 * *old_dir and "a/b/some/thing/else" in *new_dir.
1975 * If the basename of the file changed, we don't care. We want
1976 * to know which portion of the directory, if any, changed.
1978 end_of_old = strrchr(old_path, '/');
1979 end_of_new = strrchr(new_path, '/');
1982 * If end_of_old is NULL, old_path wasn't in a directory, so there
1983 * could not be a directory rename (our rule elsewhere that a
1984 * directory which still exists is not considered to have been
1985 * renamed means the root directory can never be renamed -- because
1986 * the root directory always exists).
1988 if (end_of_old == NULL)
1989 return; /* Note: *old_dir and *new_dir are still NULL */
1992 * If new_path contains no directory (end_of_new is NULL), then we
1993 * have a rename of old_path's directory to the root directory.
1995 if (end_of_new == NULL) {
1996 *old_dir = xstrndup(old_path, end_of_old - old_path);
1997 *new_dir = xstrdup("");
1998 return;
2001 /* Find the first non-matching character traversing backwards */
2002 while (*--end_of_new == *--end_of_old &&
2003 end_of_old != old_path &&
2004 end_of_new != new_path)
2005 ; /* Do nothing; all in the while loop */
2008 * If both got back to the beginning of their strings, then the
2009 * directory didn't change at all, only the basename did.
2011 if (end_of_old == old_path && end_of_new == new_path &&
2012 *end_of_old == *end_of_new)
2013 return; /* Note: *old_dir and *new_dir are still NULL */
2016 * If end_of_new got back to the beginning of its string, and
2017 * end_of_old got back to the beginning of some subdirectory, then
2018 * we have a rename/merge of a subdirectory into the root, which
2019 * needs slightly special handling.
2021 * Note: There is no need to consider the opposite case, with a
2022 * rename/merge of the root directory into some subdirectory
2023 * because as noted above the root directory always exists so it
2024 * cannot be considered to be renamed.
2026 if (end_of_new == new_path &&
2027 end_of_old != old_path && end_of_old[-1] == '/') {
2028 *old_dir = xstrndup(old_path, --end_of_old - old_path);
2029 *new_dir = xstrdup("");
2030 return;
2034 * We've found the first non-matching character in the directory
2035 * paths. That means the current characters we were looking at
2036 * were part of the first non-matching subdir name going back from
2037 * the end of the strings. Get the whole name by advancing both
2038 * end_of_old and end_of_new to the NEXT '/' character. That will
2039 * represent the entire directory rename.
2041 * The reason for the increment is cases like
2042 * a/b/star/foo/whatever.c -> a/b/tar/foo/random.c
2043 * After dropping the basename and going back to the first
2044 * non-matching character, we're now comparing:
2045 * a/b/s and a/b/
2046 * and we want to be comparing:
2047 * a/b/star/ and a/b/tar/
2048 * but without the pre-increment, the one on the right would stay
2049 * a/b/.
2051 end_of_old = strchr(++end_of_old, '/');
2052 end_of_new = strchr(++end_of_new, '/');
2054 /* Copy the old and new directories into *old_dir and *new_dir. */
2055 *old_dir = xstrndup(old_path, end_of_old - old_path);
2056 *new_dir = xstrndup(new_path, end_of_new - new_path);
2059 static void remove_hashmap_entries(struct hashmap *dir_renames,
2060 struct string_list *items_to_remove)
2062 int i;
2063 struct dir_rename_entry *entry;
2065 for (i = 0; i < items_to_remove->nr; i++) {
2066 entry = items_to_remove->items[i].util;
2067 hashmap_remove(dir_renames, &entry->ent, NULL);
2069 string_list_clear(items_to_remove, 0);
2073 * See if there is a directory rename for path, and if there are any file
2074 * level conflicts for the renamed location. If there is a rename and
2075 * there are no conflicts, return the new name. Otherwise, return NULL.
2077 static char *handle_path_level_conflicts(struct merge_options *opt,
2078 const char *path,
2079 struct dir_rename_entry *entry,
2080 struct hashmap *collisions,
2081 struct tree *tree)
2083 char *new_path = NULL;
2084 struct collision_entry *collision_ent;
2085 int clean = 1;
2086 struct strbuf collision_paths = STRBUF_INIT;
2089 * entry has the mapping of old directory name to new directory name
2090 * that we want to apply to path.
2092 new_path = apply_dir_rename(entry, path);
2094 if (!new_path) {
2095 /* This should only happen when entry->non_unique_new_dir set */
2096 if (!entry->non_unique_new_dir)
2097 BUG("entry->non_unqiue_dir not set and !new_path");
2098 output(opt, 1, _("CONFLICT (directory rename split): "
2099 "Unclear where to place %s because directory "
2100 "%s was renamed to multiple other directories, "
2101 "with no destination getting a majority of the "
2102 "files."),
2103 path, entry->dir);
2104 clean = 0;
2105 return NULL;
2109 * The caller needs to have ensured that it has pre-populated
2110 * collisions with all paths that map to new_path. Do a quick check
2111 * to ensure that's the case.
2113 collision_ent = collision_find_entry(collisions, new_path);
2114 if (collision_ent == NULL)
2115 BUG("collision_ent is NULL");
2118 * Check for one-sided add/add/.../add conflicts, i.e.
2119 * where implicit renames from the other side doing
2120 * directory rename(s) can affect this side of history
2121 * to put multiple paths into the same location. Warn
2122 * and bail on directory renames for such paths.
2124 if (collision_ent->reported_already) {
2125 clean = 0;
2126 } else if (tree_has_path(opt->repo, tree, new_path)) {
2127 collision_ent->reported_already = 1;
2128 strbuf_add_separated_string_list(&collision_paths, ", ",
2129 &collision_ent->source_files);
2130 output(opt, 1, _("CONFLICT (implicit dir rename): Existing "
2131 "file/dir at %s in the way of implicit "
2132 "directory rename(s) putting the following "
2133 "path(s) there: %s."),
2134 new_path, collision_paths.buf);
2135 clean = 0;
2136 } else if (collision_ent->source_files.nr > 1) {
2137 collision_ent->reported_already = 1;
2138 strbuf_add_separated_string_list(&collision_paths, ", ",
2139 &collision_ent->source_files);
2140 output(opt, 1, _("CONFLICT (implicit dir rename): Cannot map "
2141 "more than one path to %s; implicit directory "
2142 "renames tried to put these paths there: %s"),
2143 new_path, collision_paths.buf);
2144 clean = 0;
2147 /* Free memory we no longer need */
2148 strbuf_release(&collision_paths);
2149 if (!clean && new_path) {
2150 free(new_path);
2151 return NULL;
2154 return new_path;
2158 * There are a couple things we want to do at the directory level:
2159 * 1. Check for both sides renaming to the same thing, in order to avoid
2160 * implicit renaming of files that should be left in place. (See
2161 * testcase 6b in t6043 for details.)
2162 * 2. Prune directory renames if there are still files left in the
2163 * original directory. These represent a partial directory rename,
2164 * i.e. a rename where only some of the files within the directory
2165 * were renamed elsewhere. (Technically, this could be done earlier
2166 * in get_directory_renames(), except that would prevent us from
2167 * doing the previous check and thus failing testcase 6b.)
2168 * 3. Check for rename/rename(1to2) conflicts (at the directory level).
2169 * In the future, we could potentially record this info as well and
2170 * omit reporting rename/rename(1to2) conflicts for each path within
2171 * the affected directories, thus cleaning up the merge output.
2172 * NOTE: We do NOT check for rename/rename(2to1) conflicts at the
2173 * directory level, because merging directories is fine. If it
2174 * causes conflicts for files within those merged directories, then
2175 * that should be detected at the individual path level.
2177 static void handle_directory_level_conflicts(struct merge_options *opt,
2178 struct hashmap *dir_re_head,
2179 struct tree *head,
2180 struct hashmap *dir_re_merge,
2181 struct tree *merge)
2183 struct hashmap_iter iter;
2184 struct dir_rename_entry *head_ent;
2185 struct dir_rename_entry *merge_ent;
2187 struct string_list remove_from_head = STRING_LIST_INIT_NODUP;
2188 struct string_list remove_from_merge = STRING_LIST_INIT_NODUP;
2190 hashmap_for_each_entry(dir_re_head, &iter, head_ent,
2191 ent /* member name */) {
2192 merge_ent = dir_rename_find_entry(dir_re_merge, head_ent->dir);
2193 if (merge_ent &&
2194 !head_ent->non_unique_new_dir &&
2195 !merge_ent->non_unique_new_dir &&
2196 !strbuf_cmp(&head_ent->new_dir, &merge_ent->new_dir)) {
2197 /* 1. Renamed identically; remove it from both sides */
2198 string_list_append(&remove_from_head,
2199 head_ent->dir)->util = head_ent;
2200 strbuf_release(&head_ent->new_dir);
2201 string_list_append(&remove_from_merge,
2202 merge_ent->dir)->util = merge_ent;
2203 strbuf_release(&merge_ent->new_dir);
2204 } else if (tree_has_path(opt->repo, head, head_ent->dir)) {
2205 /* 2. This wasn't a directory rename after all */
2206 string_list_append(&remove_from_head,
2207 head_ent->dir)->util = head_ent;
2208 strbuf_release(&head_ent->new_dir);
2212 remove_hashmap_entries(dir_re_head, &remove_from_head);
2213 remove_hashmap_entries(dir_re_merge, &remove_from_merge);
2215 hashmap_for_each_entry(dir_re_merge, &iter, merge_ent,
2216 ent /* member name */) {
2217 head_ent = dir_rename_find_entry(dir_re_head, merge_ent->dir);
2218 if (tree_has_path(opt->repo, merge, merge_ent->dir)) {
2219 /* 2. This wasn't a directory rename after all */
2220 string_list_append(&remove_from_merge,
2221 merge_ent->dir)->util = merge_ent;
2222 } else if (head_ent &&
2223 !head_ent->non_unique_new_dir &&
2224 !merge_ent->non_unique_new_dir) {
2225 /* 3. rename/rename(1to2) */
2227 * We can assume it's not rename/rename(1to1) because
2228 * that was case (1), already checked above. So we
2229 * know that head_ent->new_dir and merge_ent->new_dir
2230 * are different strings.
2232 output(opt, 1, _("CONFLICT (rename/rename): "
2233 "Rename directory %s->%s in %s. "
2234 "Rename directory %s->%s in %s"),
2235 head_ent->dir, head_ent->new_dir.buf, opt->branch1,
2236 head_ent->dir, merge_ent->new_dir.buf, opt->branch2);
2237 string_list_append(&remove_from_head,
2238 head_ent->dir)->util = head_ent;
2239 strbuf_release(&head_ent->new_dir);
2240 string_list_append(&remove_from_merge,
2241 merge_ent->dir)->util = merge_ent;
2242 strbuf_release(&merge_ent->new_dir);
2246 remove_hashmap_entries(dir_re_head, &remove_from_head);
2247 remove_hashmap_entries(dir_re_merge, &remove_from_merge);
2250 static struct hashmap *get_directory_renames(struct diff_queue_struct *pairs)
2252 struct hashmap *dir_renames;
2253 struct hashmap_iter iter;
2254 struct dir_rename_entry *entry;
2255 int i;
2258 * Typically, we think of a directory rename as all files from a
2259 * certain directory being moved to a target directory. However,
2260 * what if someone first moved two files from the original
2261 * directory in one commit, and then renamed the directory
2262 * somewhere else in a later commit? At merge time, we just know
2263 * that files from the original directory went to two different
2264 * places, and that the bulk of them ended up in the same place.
2265 * We want each directory rename to represent where the bulk of the
2266 * files from that directory end up; this function exists to find
2267 * where the bulk of the files went.
2269 * The first loop below simply iterates through the list of file
2270 * renames, finding out how often each directory rename pair
2271 * possibility occurs.
2273 dir_renames = xmalloc(sizeof(*dir_renames));
2274 dir_rename_init(dir_renames);
2275 for (i = 0; i < pairs->nr; ++i) {
2276 struct string_list_item *item;
2277 int *count;
2278 struct diff_filepair *pair = pairs->queue[i];
2279 char *old_dir, *new_dir;
2281 /* File not part of directory rename if it wasn't renamed */
2282 if (pair->status != 'R')
2283 continue;
2285 get_renamed_dir_portion(pair->one->path, pair->two->path,
2286 &old_dir, &new_dir);
2287 if (!old_dir)
2288 /* Directory didn't change at all; ignore this one. */
2289 continue;
2291 entry = dir_rename_find_entry(dir_renames, old_dir);
2292 if (!entry) {
2293 entry = xmalloc(sizeof(*entry));
2294 dir_rename_entry_init(entry, old_dir);
2295 hashmap_put(dir_renames, &entry->ent);
2296 } else {
2297 free(old_dir);
2299 item = string_list_lookup(&entry->possible_new_dirs, new_dir);
2300 if (!item) {
2301 item = string_list_insert(&entry->possible_new_dirs,
2302 new_dir);
2303 item->util = xcalloc(1, sizeof(int));
2304 } else {
2305 free(new_dir);
2307 count = item->util;
2308 *count += 1;
2312 * For each directory with files moved out of it, we find out which
2313 * target directory received the most files so we can declare it to
2314 * be the "winning" target location for the directory rename. This
2315 * winner gets recorded in new_dir. If there is no winner
2316 * (multiple target directories received the same number of files),
2317 * we set non_unique_new_dir. Once we've determined the winner (or
2318 * that there is no winner), we no longer need possible_new_dirs.
2320 hashmap_for_each_entry(dir_renames, &iter, entry,
2321 ent /* member name */) {
2322 int max = 0;
2323 int bad_max = 0;
2324 char *best = NULL;
2326 for (i = 0; i < entry->possible_new_dirs.nr; i++) {
2327 int *count = entry->possible_new_dirs.items[i].util;
2329 if (*count == max)
2330 bad_max = max;
2331 else if (*count > max) {
2332 max = *count;
2333 best = entry->possible_new_dirs.items[i].string;
2336 if (bad_max == max)
2337 entry->non_unique_new_dir = 1;
2338 else {
2339 assert(entry->new_dir.len == 0);
2340 strbuf_addstr(&entry->new_dir, best);
2343 * The relevant directory sub-portion of the original full
2344 * filepaths were xstrndup'ed before inserting into
2345 * possible_new_dirs, and instead of manually iterating the
2346 * list and free'ing each, just lie and tell
2347 * possible_new_dirs that it did the strdup'ing so that it
2348 * will free them for us.
2350 entry->possible_new_dirs.strdup_strings = 1;
2351 string_list_clear(&entry->possible_new_dirs, 1);
2354 return dir_renames;
2357 static struct dir_rename_entry *check_dir_renamed(const char *path,
2358 struct hashmap *dir_renames)
2360 char *temp = xstrdup(path);
2361 char *end;
2362 struct dir_rename_entry *entry = NULL;
2364 while ((end = strrchr(temp, '/'))) {
2365 *end = '\0';
2366 entry = dir_rename_find_entry(dir_renames, temp);
2367 if (entry)
2368 break;
2370 free(temp);
2371 return entry;
2374 static void compute_collisions(struct hashmap *collisions,
2375 struct hashmap *dir_renames,
2376 struct diff_queue_struct *pairs)
2378 int i;
2381 * Multiple files can be mapped to the same path due to directory
2382 * renames done by the other side of history. Since that other
2383 * side of history could have merged multiple directories into one,
2384 * if our side of history added the same file basename to each of
2385 * those directories, then all N of them would get implicitly
2386 * renamed by the directory rename detection into the same path,
2387 * and we'd get an add/add/.../add conflict, and all those adds
2388 * from *this* side of history. This is not representable in the
2389 * index, and users aren't going to easily be able to make sense of
2390 * it. So we need to provide a good warning about what's
2391 * happening, and fall back to no-directory-rename detection
2392 * behavior for those paths.
2394 * See testcases 9e and all of section 5 from t6043 for examples.
2396 collision_init(collisions);
2398 for (i = 0; i < pairs->nr; ++i) {
2399 struct dir_rename_entry *dir_rename_ent;
2400 struct collision_entry *collision_ent;
2401 char *new_path;
2402 struct diff_filepair *pair = pairs->queue[i];
2404 if (pair->status != 'A' && pair->status != 'R')
2405 continue;
2406 dir_rename_ent = check_dir_renamed(pair->two->path,
2407 dir_renames);
2408 if (!dir_rename_ent)
2409 continue;
2411 new_path = apply_dir_rename(dir_rename_ent, pair->two->path);
2412 if (!new_path)
2414 * dir_rename_ent->non_unique_new_path is true, which
2415 * means there is no directory rename for us to use,
2416 * which means it won't cause us any additional
2417 * collisions.
2419 continue;
2420 collision_ent = collision_find_entry(collisions, new_path);
2421 if (!collision_ent) {
2422 CALLOC_ARRAY(collision_ent, 1);
2423 hashmap_entry_init(&collision_ent->ent,
2424 strhash(new_path));
2425 hashmap_put(collisions, &collision_ent->ent);
2426 collision_ent->target_file = new_path;
2427 } else {
2428 free(new_path);
2430 string_list_insert(&collision_ent->source_files,
2431 pair->two->path);
2435 static char *check_for_directory_rename(struct merge_options *opt,
2436 const char *path,
2437 struct tree *tree,
2438 struct hashmap *dir_renames,
2439 struct hashmap *dir_rename_exclusions,
2440 struct hashmap *collisions,
2441 int *clean_merge)
2443 char *new_path = NULL;
2444 struct dir_rename_entry *entry = check_dir_renamed(path, dir_renames);
2445 struct dir_rename_entry *oentry = NULL;
2447 if (!entry)
2448 return new_path;
2451 * This next part is a little weird. We do not want to do an
2452 * implicit rename into a directory we renamed on our side, because
2453 * that will result in a spurious rename/rename(1to2) conflict. An
2454 * example:
2455 * Base commit: dumbdir/afile, otherdir/bfile
2456 * Side 1: smrtdir/afile, otherdir/bfile
2457 * Side 2: dumbdir/afile, dumbdir/bfile
2458 * Here, while working on Side 1, we could notice that otherdir was
2459 * renamed/merged to dumbdir, and change the diff_filepair for
2460 * otherdir/bfile into a rename into dumbdir/bfile. However, Side
2461 * 2 will notice the rename from dumbdir to smrtdir, and do the
2462 * transitive rename to move it from dumbdir/bfile to
2463 * smrtdir/bfile. That gives us bfile in dumbdir vs being in
2464 * smrtdir, a rename/rename(1to2) conflict. We really just want
2465 * the file to end up in smrtdir. And the way to achieve that is
2466 * to not let Side1 do the rename to dumbdir, since we know that is
2467 * the source of one of our directory renames.
2469 * That's why oentry and dir_rename_exclusions is here.
2471 * As it turns out, this also prevents N-way transient rename
2472 * confusion; See testcases 9c and 9d of t6043.
2474 oentry = dir_rename_find_entry(dir_rename_exclusions, entry->new_dir.buf);
2475 if (oentry) {
2476 output(opt, 1, _("WARNING: Avoiding applying %s -> %s rename "
2477 "to %s, because %s itself was renamed."),
2478 entry->dir, entry->new_dir.buf, path, entry->new_dir.buf);
2479 } else {
2480 new_path = handle_path_level_conflicts(opt, path, entry,
2481 collisions, tree);
2482 *clean_merge &= (new_path != NULL);
2485 return new_path;
2488 static void apply_directory_rename_modifications(struct merge_options *opt,
2489 struct diff_filepair *pair,
2490 char *new_path,
2491 struct rename *re,
2492 struct tree *tree,
2493 struct tree *o_tree,
2494 struct tree *a_tree,
2495 struct tree *b_tree,
2496 struct string_list *entries)
2498 struct string_list_item *item;
2499 int stage = (tree == a_tree ? 2 : 3);
2500 int update_wd;
2503 * In all cases where we can do directory rename detection,
2504 * unpack_trees() will have read pair->two->path into the
2505 * index and the working copy. We need to remove it so that
2506 * we can instead place it at new_path. It is guaranteed to
2507 * not be untracked (unpack_trees() would have errored out
2508 * saying the file would have been overwritten), but it might
2509 * be dirty, though.
2511 update_wd = !was_dirty(opt, pair->two->path);
2512 if (!update_wd)
2513 output(opt, 1, _("Refusing to lose dirty file at %s"),
2514 pair->two->path);
2515 remove_file(opt, 1, pair->two->path, !update_wd);
2517 /* Find or create a new re->dst_entry */
2518 item = string_list_lookup(entries, new_path);
2519 if (item) {
2521 * Since we're renaming on this side of history, and it's
2522 * due to a directory rename on the other side of history
2523 * (which we only allow when the directory in question no
2524 * longer exists on the other side of history), the
2525 * original entry for re->dst_entry is no longer
2526 * necessary...
2528 re->dst_entry->processed = 1;
2531 * ...because we'll be using this new one.
2533 re->dst_entry = item->util;
2534 } else {
2536 * re->dst_entry is for the before-dir-rename path, and we
2537 * need it to hold information for the after-dir-rename
2538 * path. Before creating a new entry, we need to mark the
2539 * old one as unnecessary (...unless it is shared by
2540 * src_entry, i.e. this didn't use to be a rename, in which
2541 * case we can just allow the normal processing to happen
2542 * for it).
2544 if (pair->status == 'R')
2545 re->dst_entry->processed = 1;
2547 re->dst_entry = insert_stage_data(opt->repo, new_path,
2548 o_tree, a_tree, b_tree,
2549 entries);
2550 item = string_list_insert(entries, new_path);
2551 item->util = re->dst_entry;
2555 * Update the stage_data with the information about the path we are
2556 * moving into place. That slot will be empty and available for us
2557 * to write to because of the collision checks in
2558 * handle_path_level_conflicts(). In other words,
2559 * re->dst_entry->stages[stage].oid will be the null_oid, so it's
2560 * open for us to write to.
2562 * It may be tempting to actually update the index at this point as
2563 * well, using update_stages_for_stage_data(), but as per the big
2564 * "NOTE" in update_stages(), doing so will modify the current
2565 * in-memory index which will break calls to would_lose_untracked()
2566 * that we need to make. Instead, we need to just make sure that
2567 * the various handle_rename_*() functions update the index
2568 * explicitly rather than relying on unpack_trees() to have done it.
2570 get_tree_entry(opt->repo,
2571 &tree->object.oid,
2572 pair->two->path,
2573 &re->dst_entry->stages[stage].oid,
2574 &re->dst_entry->stages[stage].mode);
2577 * Record the original change status (or 'type' of change). If it
2578 * was originally an add ('A'), this lets us differentiate later
2579 * between a RENAME_DELETE conflict and RENAME_VIA_DIR (they
2580 * otherwise look the same). If it was originally a rename ('R'),
2581 * this lets us remember and report accurately about the transitive
2582 * renaming that occurred via the directory rename detection. Also,
2583 * record the original destination name.
2585 re->dir_rename_original_type = pair->status;
2586 re->dir_rename_original_dest = pair->two->path;
2589 * We don't actually look at pair->status again, but it seems
2590 * pedagogically correct to adjust it.
2592 pair->status = 'R';
2595 * Finally, record the new location.
2597 pair->two->path = new_path;
2601 * Get information of all renames which occurred in 'pairs', making use of
2602 * any implicit directory renames inferred from the other side of history.
2603 * We need the three trees in the merge ('o_tree', 'a_tree' and 'b_tree')
2604 * to be able to associate the correct cache entries with the rename
2605 * information; tree is always equal to either a_tree or b_tree.
2607 static struct string_list *get_renames(struct merge_options *opt,
2608 const char *branch,
2609 struct diff_queue_struct *pairs,
2610 struct hashmap *dir_renames,
2611 struct hashmap *dir_rename_exclusions,
2612 struct tree *tree,
2613 struct tree *o_tree,
2614 struct tree *a_tree,
2615 struct tree *b_tree,
2616 struct string_list *entries,
2617 int *clean_merge)
2619 int i;
2620 struct hashmap collisions;
2621 struct hashmap_iter iter;
2622 struct collision_entry *e;
2623 struct string_list *renames;
2625 compute_collisions(&collisions, dir_renames, pairs);
2626 CALLOC_ARRAY(renames, 1);
2628 for (i = 0; i < pairs->nr; ++i) {
2629 struct string_list_item *item;
2630 struct rename *re;
2631 struct diff_filepair *pair = pairs->queue[i];
2632 char *new_path; /* non-NULL only with directory renames */
2634 if (pair->status != 'A' && pair->status != 'R') {
2635 diff_free_filepair(pair);
2636 continue;
2638 new_path = check_for_directory_rename(opt, pair->two->path, tree,
2639 dir_renames,
2640 dir_rename_exclusions,
2641 &collisions,
2642 clean_merge);
2643 if (pair->status != 'R' && !new_path) {
2644 diff_free_filepair(pair);
2645 continue;
2648 re = xmalloc(sizeof(*re));
2649 re->processed = 0;
2650 re->pair = pair;
2651 re->branch = branch;
2652 re->dir_rename_original_type = '\0';
2653 re->dir_rename_original_dest = NULL;
2654 item = string_list_lookup(entries, re->pair->one->path);
2655 if (!item)
2656 re->src_entry = insert_stage_data(opt->repo,
2657 re->pair->one->path,
2658 o_tree, a_tree, b_tree, entries);
2659 else
2660 re->src_entry = item->util;
2662 item = string_list_lookup(entries, re->pair->two->path);
2663 if (!item)
2664 re->dst_entry = insert_stage_data(opt->repo,
2665 re->pair->two->path,
2666 o_tree, a_tree, b_tree, entries);
2667 else
2668 re->dst_entry = item->util;
2669 item = string_list_insert(renames, pair->one->path);
2670 item->util = re;
2671 if (new_path)
2672 apply_directory_rename_modifications(opt, pair, new_path,
2673 re, tree, o_tree,
2674 a_tree, b_tree,
2675 entries);
2678 hashmap_for_each_entry(&collisions, &iter, e,
2679 ent /* member name */) {
2680 free(e->target_file);
2681 string_list_clear(&e->source_files, 0);
2683 hashmap_clear_and_free(&collisions, struct collision_entry, ent);
2684 return renames;
2687 static int process_renames(struct merge_options *opt,
2688 struct string_list *a_renames,
2689 struct string_list *b_renames)
2691 int clean_merge = 1, i, j;
2692 struct string_list a_by_dst = STRING_LIST_INIT_NODUP;
2693 struct string_list b_by_dst = STRING_LIST_INIT_NODUP;
2694 const struct rename *sre;
2697 * FIXME: As string-list.h notes, it's O(n^2) to build a sorted
2698 * string_list one-by-one, but O(n log n) to build it unsorted and
2699 * then sort it. Note that as we build the list, we do not need to
2700 * check if the existing destination path is already in the list,
2701 * because the structure of diffcore_rename guarantees we won't
2702 * have duplicates.
2704 for (i = 0; i < a_renames->nr; i++) {
2705 sre = a_renames->items[i].util;
2706 string_list_insert(&a_by_dst, sre->pair->two->path)->util
2707 = (void *)sre;
2709 for (i = 0; i < b_renames->nr; i++) {
2710 sre = b_renames->items[i].util;
2711 string_list_insert(&b_by_dst, sre->pair->two->path)->util
2712 = (void *)sre;
2715 for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) {
2716 struct string_list *renames1, *renames2Dst;
2717 struct rename *ren1 = NULL, *ren2 = NULL;
2718 const char *ren1_src, *ren1_dst;
2719 struct string_list_item *lookup;
2721 if (i >= a_renames->nr) {
2722 ren2 = b_renames->items[j++].util;
2723 } else if (j >= b_renames->nr) {
2724 ren1 = a_renames->items[i++].util;
2725 } else {
2726 int compare = strcmp(a_renames->items[i].string,
2727 b_renames->items[j].string);
2728 if (compare <= 0)
2729 ren1 = a_renames->items[i++].util;
2730 if (compare >= 0)
2731 ren2 = b_renames->items[j++].util;
2734 /* TODO: refactor, so that 1/2 are not needed */
2735 if (ren1) {
2736 renames1 = a_renames;
2737 renames2Dst = &b_by_dst;
2738 } else {
2739 renames1 = b_renames;
2740 renames2Dst = &a_by_dst;
2741 SWAP(ren2, ren1);
2744 if (ren1->processed)
2745 continue;
2746 ren1->processed = 1;
2747 ren1->dst_entry->processed = 1;
2748 /* BUG: We should only mark src_entry as processed if we
2749 * are not dealing with a rename + add-source case.
2751 ren1->src_entry->processed = 1;
2753 ren1_src = ren1->pair->one->path;
2754 ren1_dst = ren1->pair->two->path;
2756 if (ren2) {
2757 /* One file renamed on both sides */
2758 const char *ren2_src = ren2->pair->one->path;
2759 const char *ren2_dst = ren2->pair->two->path;
2760 enum rename_type rename_type;
2761 if (strcmp(ren1_src, ren2_src) != 0)
2762 BUG("ren1_src != ren2_src");
2763 ren2->dst_entry->processed = 1;
2764 ren2->processed = 1;
2765 if (strcmp(ren1_dst, ren2_dst) != 0) {
2766 rename_type = RENAME_ONE_FILE_TO_TWO;
2767 clean_merge = 0;
2768 } else {
2769 rename_type = RENAME_ONE_FILE_TO_ONE;
2770 /* BUG: We should only remove ren1_src in
2771 * the base stage (think of rename +
2772 * add-source cases).
2774 remove_file(opt, 1, ren1_src, 1);
2775 update_entry(ren1->dst_entry,
2776 ren1->pair->one,
2777 ren1->pair->two,
2778 ren2->pair->two);
2780 setup_rename_conflict_info(rename_type, opt, ren1, ren2);
2781 } else if ((lookup = string_list_lookup(renames2Dst, ren1_dst))) {
2782 /* Two different files renamed to the same thing */
2783 char *ren2_dst;
2784 ren2 = lookup->util;
2785 ren2_dst = ren2->pair->two->path;
2786 if (strcmp(ren1_dst, ren2_dst) != 0)
2787 BUG("ren1_dst != ren2_dst");
2789 clean_merge = 0;
2790 ren2->processed = 1;
2792 * BUG: We should only mark src_entry as processed
2793 * if we are not dealing with a rename + add-source
2794 * case.
2796 ren2->src_entry->processed = 1;
2798 setup_rename_conflict_info(RENAME_TWO_FILES_TO_ONE,
2799 opt, ren1, ren2);
2800 } else {
2801 /* Renamed in 1, maybe changed in 2 */
2802 /* we only use sha1 and mode of these */
2803 struct diff_filespec src_other, dst_other;
2804 int try_merge;
2807 * unpack_trees loads entries from common-commit
2808 * into stage 1, from head-commit into stage 2, and
2809 * from merge-commit into stage 3. We keep track
2810 * of which side corresponds to the rename.
2812 int renamed_stage = a_renames == renames1 ? 2 : 3;
2813 int other_stage = a_renames == renames1 ? 3 : 2;
2816 * Directory renames have a funny corner case...
2818 int renamed_to_self = !strcmp(ren1_src, ren1_dst);
2820 /* BUG: We should only remove ren1_src in the base
2821 * stage and in other_stage (think of rename +
2822 * add-source case).
2824 if (!renamed_to_self)
2825 remove_file(opt, 1, ren1_src,
2826 renamed_stage == 2 ||
2827 !was_tracked(opt, ren1_src));
2829 oidcpy(&src_other.oid,
2830 &ren1->src_entry->stages[other_stage].oid);
2831 src_other.mode = ren1->src_entry->stages[other_stage].mode;
2832 oidcpy(&dst_other.oid,
2833 &ren1->dst_entry->stages[other_stage].oid);
2834 dst_other.mode = ren1->dst_entry->stages[other_stage].mode;
2835 try_merge = 0;
2837 if (oideq(&src_other.oid, null_oid()) &&
2838 ren1->dir_rename_original_type == 'A') {
2839 setup_rename_conflict_info(RENAME_VIA_DIR,
2840 opt, ren1, NULL);
2841 } else if (renamed_to_self) {
2842 setup_rename_conflict_info(RENAME_NORMAL,
2843 opt, ren1, NULL);
2844 } else if (oideq(&src_other.oid, null_oid())) {
2845 setup_rename_conflict_info(RENAME_DELETE,
2846 opt, ren1, NULL);
2847 } else if ((dst_other.mode == ren1->pair->two->mode) &&
2848 oideq(&dst_other.oid, &ren1->pair->two->oid)) {
2850 * Added file on the other side identical to
2851 * the file being renamed: clean merge.
2852 * Also, there is no need to overwrite the
2853 * file already in the working copy, so call
2854 * update_file_flags() instead of
2855 * update_file().
2857 if (update_file_flags(opt,
2858 ren1->pair->two,
2859 ren1_dst,
2860 1, /* update_cache */
2861 0 /* update_wd */))
2862 clean_merge = -1;
2863 } else if (!oideq(&dst_other.oid, null_oid())) {
2865 * Probably not a clean merge, but it's
2866 * premature to set clean_merge to 0 here,
2867 * because if the rename merges cleanly and
2868 * the merge exactly matches the newly added
2869 * file, then the merge will be clean.
2871 setup_rename_conflict_info(RENAME_ADD,
2872 opt, ren1, NULL);
2873 } else
2874 try_merge = 1;
2876 if (clean_merge < 0)
2877 goto cleanup_and_return;
2878 if (try_merge) {
2879 struct diff_filespec *o, *a, *b;
2880 src_other.path = (char *)ren1_src;
2882 o = ren1->pair->one;
2883 if (a_renames == renames1) {
2884 a = ren1->pair->two;
2885 b = &src_other;
2886 } else {
2887 b = ren1->pair->two;
2888 a = &src_other;
2890 update_entry(ren1->dst_entry, o, a, b);
2891 setup_rename_conflict_info(RENAME_NORMAL,
2892 opt, ren1, NULL);
2896 cleanup_and_return:
2897 string_list_clear(&a_by_dst, 0);
2898 string_list_clear(&b_by_dst, 0);
2900 return clean_merge;
2903 struct rename_info {
2904 struct string_list *head_renames;
2905 struct string_list *merge_renames;
2908 static void initial_cleanup_rename(struct diff_queue_struct *pairs,
2909 struct hashmap *dir_renames)
2911 struct hashmap_iter iter;
2912 struct dir_rename_entry *e;
2914 hashmap_for_each_entry(dir_renames, &iter, e,
2915 ent /* member name */) {
2916 free(e->dir);
2917 strbuf_release(&e->new_dir);
2918 /* possible_new_dirs already cleared in get_directory_renames */
2920 hashmap_clear_and_free(dir_renames, struct dir_rename_entry, ent);
2921 free(dir_renames);
2923 free(pairs->queue);
2924 free(pairs);
2927 static int detect_and_process_renames(struct merge_options *opt,
2928 struct tree *common,
2929 struct tree *head,
2930 struct tree *merge,
2931 struct string_list *entries,
2932 struct rename_info *ri)
2934 struct diff_queue_struct *head_pairs, *merge_pairs;
2935 struct hashmap *dir_re_head, *dir_re_merge;
2936 int clean = 1;
2938 ri->head_renames = NULL;
2939 ri->merge_renames = NULL;
2941 if (!merge_detect_rename(opt))
2942 return 1;
2944 head_pairs = get_diffpairs(opt, common, head);
2945 merge_pairs = get_diffpairs(opt, common, merge);
2947 if ((opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE) ||
2948 (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT &&
2949 !opt->priv->call_depth)) {
2950 dir_re_head = get_directory_renames(head_pairs);
2951 dir_re_merge = get_directory_renames(merge_pairs);
2953 handle_directory_level_conflicts(opt,
2954 dir_re_head, head,
2955 dir_re_merge, merge);
2956 } else {
2957 dir_re_head = xmalloc(sizeof(*dir_re_head));
2958 dir_re_merge = xmalloc(sizeof(*dir_re_merge));
2959 dir_rename_init(dir_re_head);
2960 dir_rename_init(dir_re_merge);
2963 ri->head_renames = get_renames(opt, opt->branch1, head_pairs,
2964 dir_re_merge, dir_re_head, head,
2965 common, head, merge, entries,
2966 &clean);
2967 if (clean < 0)
2968 goto cleanup;
2969 ri->merge_renames = get_renames(opt, opt->branch2, merge_pairs,
2970 dir_re_head, dir_re_merge, merge,
2971 common, head, merge, entries,
2972 &clean);
2973 if (clean < 0)
2974 goto cleanup;
2975 clean &= process_renames(opt, ri->head_renames, ri->merge_renames);
2977 cleanup:
2979 * Some cleanup is deferred until cleanup_renames() because the
2980 * data structures are still needed and referenced in
2981 * process_entry(). But there are a few things we can free now.
2983 initial_cleanup_rename(head_pairs, dir_re_head);
2984 initial_cleanup_rename(merge_pairs, dir_re_merge);
2986 return clean;
2989 static void final_cleanup_rename(struct string_list *rename)
2991 const struct rename *re;
2992 int i;
2994 if (rename == NULL)
2995 return;
2997 for (i = 0; i < rename->nr; i++) {
2998 re = rename->items[i].util;
2999 diff_free_filepair(re->pair);
3001 string_list_clear(rename, 1);
3002 free(rename);
3005 static void final_cleanup_renames(struct rename_info *re_info)
3007 final_cleanup_rename(re_info->head_renames);
3008 final_cleanup_rename(re_info->merge_renames);
3011 static int read_oid_strbuf(struct merge_options *opt,
3012 const struct object_id *oid,
3013 struct strbuf *dst)
3015 void *buf;
3016 enum object_type type;
3017 unsigned long size;
3018 buf = read_object_file(oid, &type, &size);
3019 if (!buf)
3020 return err(opt, _("cannot read object %s"), oid_to_hex(oid));
3021 if (type != OBJ_BLOB) {
3022 free(buf);
3023 return err(opt, _("object %s is not a blob"), oid_to_hex(oid));
3025 strbuf_attach(dst, buf, size, size + 1);
3026 return 0;
3029 static int blob_unchanged(struct merge_options *opt,
3030 const struct diff_filespec *o,
3031 const struct diff_filespec *a,
3032 int renormalize, const char *path)
3034 struct strbuf obuf = STRBUF_INIT;
3035 struct strbuf abuf = STRBUF_INIT;
3036 int ret = 0; /* assume changed for safety */
3037 struct index_state *idx = opt->repo->index;
3039 if (a->mode != o->mode)
3040 return 0;
3041 if (oideq(&o->oid, &a->oid))
3042 return 1;
3043 if (!renormalize)
3044 return 0;
3046 if (read_oid_strbuf(opt, &o->oid, &obuf) ||
3047 read_oid_strbuf(opt, &a->oid, &abuf))
3048 goto error_return;
3050 * Note: binary | is used so that both renormalizations are
3051 * performed. Comparison can be skipped if both files are
3052 * unchanged since their sha1s have already been compared.
3054 if (renormalize_buffer(idx, path, obuf.buf, obuf.len, &obuf) |
3055 renormalize_buffer(idx, path, abuf.buf, abuf.len, &abuf))
3056 ret = (obuf.len == abuf.len && !memcmp(obuf.buf, abuf.buf, obuf.len));
3058 error_return:
3059 strbuf_release(&obuf);
3060 strbuf_release(&abuf);
3061 return ret;
3064 static int handle_modify_delete(struct merge_options *opt,
3065 const char *path,
3066 const struct diff_filespec *o,
3067 const struct diff_filespec *a,
3068 const struct diff_filespec *b)
3070 const char *modify_branch, *delete_branch;
3071 const struct diff_filespec *changed;
3073 if (is_valid(a)) {
3074 modify_branch = opt->branch1;
3075 delete_branch = opt->branch2;
3076 changed = a;
3077 } else {
3078 modify_branch = opt->branch2;
3079 delete_branch = opt->branch1;
3080 changed = b;
3083 return handle_change_delete(opt,
3084 path, NULL,
3085 o, changed,
3086 modify_branch, delete_branch,
3087 _("modify"), _("modified"));
3090 static int handle_content_merge(struct merge_file_info *mfi,
3091 struct merge_options *opt,
3092 const char *path,
3093 int is_dirty,
3094 const struct diff_filespec *o,
3095 const struct diff_filespec *a,
3096 const struct diff_filespec *b,
3097 struct rename_conflict_info *ci)
3099 const char *reason = _("content");
3100 unsigned df_conflict_remains = 0;
3102 if (!is_valid(o))
3103 reason = _("add/add");
3105 assert(o->path && a->path && b->path);
3106 if (ci && dir_in_way(opt->repo->index, path, !opt->priv->call_depth,
3107 S_ISGITLINK(ci->ren1->pair->two->mode)))
3108 df_conflict_remains = 1;
3110 if (merge_mode_and_contents(opt, o, a, b, path,
3111 opt->branch1, opt->branch2,
3112 opt->priv->call_depth * 2, mfi))
3113 return -1;
3116 * We can skip updating the working tree file iff:
3117 * a) The merge is clean
3118 * b) The merge matches what was in HEAD (content, mode, pathname)
3119 * c) The target path is usable (i.e. not involved in D/F conflict)
3121 if (mfi->clean && was_tracked_and_matches(opt, path, &mfi->blob) &&
3122 !df_conflict_remains) {
3123 int pos;
3124 struct cache_entry *ce;
3126 output(opt, 3, _("Skipped %s (merged same as existing)"), path);
3127 if (add_cacheinfo(opt, &mfi->blob, path,
3128 0, (!opt->priv->call_depth && !is_dirty), 0))
3129 return -1;
3131 * However, add_cacheinfo() will delete the old cache entry
3132 * and add a new one. We need to copy over any skip_worktree
3133 * flag to avoid making the file appear as if it were
3134 * deleted by the user.
3136 pos = index_name_pos(&opt->priv->orig_index, path, strlen(path));
3137 ce = opt->priv->orig_index.cache[pos];
3138 if (ce_skip_worktree(ce)) {
3139 pos = index_name_pos(opt->repo->index, path, strlen(path));
3140 ce = opt->repo->index->cache[pos];
3141 ce->ce_flags |= CE_SKIP_WORKTREE;
3143 return mfi->clean;
3146 if (!mfi->clean) {
3147 if (S_ISGITLINK(mfi->blob.mode))
3148 reason = _("submodule");
3149 output(opt, 1, _("CONFLICT (%s): Merge conflict in %s"),
3150 reason, path);
3151 if (ci && !df_conflict_remains)
3152 if (update_stages(opt, path, o, a, b))
3153 return -1;
3156 if (df_conflict_remains || is_dirty) {
3157 char *new_path;
3158 if (opt->priv->call_depth) {
3159 remove_file_from_index(opt->repo->index, path);
3160 } else {
3161 if (!mfi->clean) {
3162 if (update_stages(opt, path, o, a, b))
3163 return -1;
3164 } else {
3165 int file_from_stage2 = was_tracked(opt, path);
3167 if (update_stages(opt, path, NULL,
3168 file_from_stage2 ? &mfi->blob : NULL,
3169 file_from_stage2 ? NULL : &mfi->blob))
3170 return -1;
3174 new_path = unique_path(opt, path, ci->ren1->branch);
3175 if (is_dirty) {
3176 output(opt, 1, _("Refusing to lose dirty file at %s"),
3177 path);
3179 output(opt, 1, _("Adding as %s instead"), new_path);
3180 if (update_file(opt, 0, &mfi->blob, new_path)) {
3181 free(new_path);
3182 return -1;
3184 free(new_path);
3185 mfi->clean = 0;
3186 } else if (update_file(opt, mfi->clean, &mfi->blob, path))
3187 return -1;
3188 return !is_dirty && mfi->clean;
3191 static int handle_rename_normal(struct merge_options *opt,
3192 const char *path,
3193 const struct diff_filespec *o,
3194 const struct diff_filespec *a,
3195 const struct diff_filespec *b,
3196 struct rename_conflict_info *ci)
3198 struct rename *ren = ci->ren1;
3199 struct merge_file_info mfi;
3200 int clean;
3202 /* Merge the content and write it out */
3203 clean = handle_content_merge(&mfi, opt, path, was_dirty(opt, path),
3204 o, a, b, ci);
3206 if (clean &&
3207 opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT &&
3208 ren->dir_rename_original_dest) {
3209 if (update_stages(opt, path,
3210 &mfi.blob, &mfi.blob, &mfi.blob))
3211 return -1;
3212 clean = 0; /* not clean, but conflicted */
3214 return clean;
3217 static void dir_rename_warning(const char *msg,
3218 int is_add,
3219 int clean,
3220 struct merge_options *opt,
3221 struct rename *ren)
3223 const char *other_branch;
3224 other_branch = (ren->branch == opt->branch1 ?
3225 opt->branch2 : opt->branch1);
3226 if (is_add) {
3227 output(opt, clean ? 2 : 1, msg,
3228 ren->pair->one->path, ren->branch,
3229 other_branch, ren->pair->two->path);
3230 return;
3232 output(opt, clean ? 2 : 1, msg,
3233 ren->pair->one->path, ren->dir_rename_original_dest, ren->branch,
3234 other_branch, ren->pair->two->path);
3236 static int warn_about_dir_renamed_entries(struct merge_options *opt,
3237 struct rename *ren)
3239 const char *msg;
3240 int clean = 1, is_add;
3242 if (!ren)
3243 return clean;
3245 /* Return early if ren was not affected/created by a directory rename */
3246 if (!ren->dir_rename_original_dest)
3247 return clean;
3249 /* Sanity checks */
3250 assert(opt->detect_directory_renames > MERGE_DIRECTORY_RENAMES_NONE);
3251 assert(ren->dir_rename_original_type == 'A' ||
3252 ren->dir_rename_original_type == 'R');
3254 /* Check whether to treat directory renames as a conflict */
3255 clean = (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE);
3257 is_add = (ren->dir_rename_original_type == 'A');
3258 if (ren->dir_rename_original_type == 'A' && clean) {
3259 msg = _("Path updated: %s added in %s inside a "
3260 "directory that was renamed in %s; moving it to %s.");
3261 } else if (ren->dir_rename_original_type == 'A' && !clean) {
3262 msg = _("CONFLICT (file location): %s added in %s "
3263 "inside a directory that was renamed in %s, "
3264 "suggesting it should perhaps be moved to %s.");
3265 } else if (ren->dir_rename_original_type == 'R' && clean) {
3266 msg = _("Path updated: %s renamed to %s in %s, inside a "
3267 "directory that was renamed in %s; moving it to %s.");
3268 } else if (ren->dir_rename_original_type == 'R' && !clean) {
3269 msg = _("CONFLICT (file location): %s renamed to %s in %s, "
3270 "inside a directory that was renamed in %s, "
3271 "suggesting it should perhaps be moved to %s.");
3272 } else {
3273 BUG("Impossible dir_rename_original_type/clean combination");
3275 dir_rename_warning(msg, is_add, clean, opt, ren);
3277 return clean;
3280 /* Per entry merge function */
3281 static int process_entry(struct merge_options *opt,
3282 const char *path, struct stage_data *entry)
3284 int clean_merge = 1;
3285 int normalize = opt->renormalize;
3287 struct diff_filespec *o = &entry->stages[1];
3288 struct diff_filespec *a = &entry->stages[2];
3289 struct diff_filespec *b = &entry->stages[3];
3290 int o_valid = is_valid(o);
3291 int a_valid = is_valid(a);
3292 int b_valid = is_valid(b);
3293 o->path = a->path = b->path = (char*)path;
3295 entry->processed = 1;
3296 if (entry->rename_conflict_info) {
3297 struct rename_conflict_info *ci = entry->rename_conflict_info;
3298 struct diff_filespec *temp;
3299 int path_clean;
3301 path_clean = warn_about_dir_renamed_entries(opt, ci->ren1);
3302 path_clean &= warn_about_dir_renamed_entries(opt, ci->ren2);
3305 * For cases with a single rename, {o,a,b}->path have all been
3306 * set to the rename target path; we need to set two of these
3307 * back to the rename source.
3308 * For rename/rename conflicts, we'll manually fix paths below.
3310 temp = (opt->branch1 == ci->ren1->branch) ? b : a;
3311 o->path = temp->path = ci->ren1->pair->one->path;
3312 if (ci->ren2) {
3313 assert(opt->branch1 == ci->ren1->branch);
3316 switch (ci->rename_type) {
3317 case RENAME_NORMAL:
3318 case RENAME_ONE_FILE_TO_ONE:
3319 clean_merge = handle_rename_normal(opt, path, o, a, b,
3320 ci);
3321 break;
3322 case RENAME_VIA_DIR:
3323 clean_merge = handle_rename_via_dir(opt, ci);
3324 break;
3325 case RENAME_ADD:
3327 * Probably unclean merge, but if the renamed file
3328 * merges cleanly and the result can then be
3329 * two-way merged cleanly with the added file, I
3330 * guess it's a clean merge?
3332 clean_merge = handle_rename_add(opt, ci);
3333 break;
3334 case RENAME_DELETE:
3335 clean_merge = 0;
3336 if (handle_rename_delete(opt, ci))
3337 clean_merge = -1;
3338 break;
3339 case RENAME_ONE_FILE_TO_TWO:
3341 * Manually fix up paths; note:
3342 * ren[12]->pair->one->path are equal.
3344 o->path = ci->ren1->pair->one->path;
3345 a->path = ci->ren1->pair->two->path;
3346 b->path = ci->ren2->pair->two->path;
3348 clean_merge = 0;
3349 if (handle_rename_rename_1to2(opt, ci))
3350 clean_merge = -1;
3351 break;
3352 case RENAME_TWO_FILES_TO_ONE:
3354 * Manually fix up paths; note,
3355 * ren[12]->pair->two->path are actually equal.
3357 o->path = NULL;
3358 a->path = ci->ren1->pair->two->path;
3359 b->path = ci->ren2->pair->two->path;
3362 * Probably unclean merge, but if the two renamed
3363 * files merge cleanly and the two resulting files
3364 * can then be two-way merged cleanly, I guess it's
3365 * a clean merge?
3367 clean_merge = handle_rename_rename_2to1(opt, ci);
3368 break;
3369 default:
3370 entry->processed = 0;
3371 break;
3373 if (path_clean < clean_merge)
3374 clean_merge = path_clean;
3375 } else if (o_valid && (!a_valid || !b_valid)) {
3376 /* Case A: Deleted in one */
3377 if ((!a_valid && !b_valid) ||
3378 (!b_valid && blob_unchanged(opt, o, a, normalize, path)) ||
3379 (!a_valid && blob_unchanged(opt, o, b, normalize, path))) {
3380 /* Deleted in both or deleted in one and
3381 * unchanged in the other */
3382 if (a_valid)
3383 output(opt, 2, _("Removing %s"), path);
3384 /* do not touch working file if it did not exist */
3385 remove_file(opt, 1, path, !a_valid);
3386 } else {
3387 /* Modify/delete; deleted side may have put a directory in the way */
3388 clean_merge = 0;
3389 if (handle_modify_delete(opt, path, o, a, b))
3390 clean_merge = -1;
3392 } else if ((!o_valid && a_valid && !b_valid) ||
3393 (!o_valid && !a_valid && b_valid)) {
3394 /* Case B: Added in one. */
3395 /* [nothing|directory] -> ([nothing|directory], file) */
3397 const char *add_branch;
3398 const char *other_branch;
3399 const char *conf;
3400 const struct diff_filespec *contents;
3402 if (a_valid) {
3403 add_branch = opt->branch1;
3404 other_branch = opt->branch2;
3405 contents = a;
3406 conf = _("file/directory");
3407 } else {
3408 add_branch = opt->branch2;
3409 other_branch = opt->branch1;
3410 contents = b;
3411 conf = _("directory/file");
3413 if (dir_in_way(opt->repo->index, path,
3414 !opt->priv->call_depth && !S_ISGITLINK(a->mode),
3415 0)) {
3416 char *new_path = unique_path(opt, path, add_branch);
3417 clean_merge = 0;
3418 output(opt, 1, _("CONFLICT (%s): There is a directory with name %s in %s. "
3419 "Adding %s as %s"),
3420 conf, path, other_branch, path, new_path);
3421 if (update_file(opt, 0, contents, new_path))
3422 clean_merge = -1;
3423 else if (opt->priv->call_depth)
3424 remove_file_from_index(opt->repo->index, path);
3425 free(new_path);
3426 } else {
3427 output(opt, 2, _("Adding %s"), path);
3428 /* do not overwrite file if already present */
3429 if (update_file_flags(opt, contents, path, 1, !a_valid))
3430 clean_merge = -1;
3432 } else if (a_valid && b_valid) {
3433 if (!o_valid) {
3434 /* Case C: Added in both (check for same permissions) */
3435 output(opt, 1,
3436 _("CONFLICT (add/add): Merge conflict in %s"),
3437 path);
3438 clean_merge = handle_file_collision(opt,
3439 path, NULL, NULL,
3440 opt->branch1,
3441 opt->branch2,
3442 a, b);
3443 } else {
3444 /* case D: Modified in both, but differently. */
3445 struct merge_file_info mfi;
3446 int is_dirty = 0; /* unpack_trees would have bailed if dirty */
3447 clean_merge = handle_content_merge(&mfi, opt, path,
3448 is_dirty,
3449 o, a, b, NULL);
3451 } else if (!o_valid && !a_valid && !b_valid) {
3453 * this entry was deleted altogether. a_mode == 0 means
3454 * we had that path and want to actively remove it.
3456 remove_file(opt, 1, path, !a->mode);
3457 } else
3458 BUG("fatal merge failure, shouldn't happen.");
3460 return clean_merge;
3463 static int merge_trees_internal(struct merge_options *opt,
3464 struct tree *head,
3465 struct tree *merge,
3466 struct tree *merge_base,
3467 struct tree **result)
3469 struct index_state *istate = opt->repo->index;
3470 int code, clean;
3472 if (opt->subtree_shift) {
3473 merge = shift_tree_object(opt->repo, head, merge,
3474 opt->subtree_shift);
3475 merge_base = shift_tree_object(opt->repo, head, merge_base,
3476 opt->subtree_shift);
3479 if (oideq(&merge_base->object.oid, &merge->object.oid)) {
3480 output(opt, 0, _("Already up to date."));
3481 *result = head;
3482 return 1;
3485 code = unpack_trees_start(opt, merge_base, head, merge);
3487 if (code != 0) {
3488 if (show(opt, 4) || opt->priv->call_depth)
3489 err(opt, _("merging of trees %s and %s failed"),
3490 oid_to_hex(&head->object.oid),
3491 oid_to_hex(&merge->object.oid));
3492 unpack_trees_finish(opt);
3493 return -1;
3496 if (unmerged_index(istate)) {
3497 struct string_list *entries;
3498 struct rename_info re_info;
3499 int i;
3501 * Only need the hashmap while processing entries, so
3502 * initialize it here and free it when we are done running
3503 * through the entries. Keeping it in the merge_options as
3504 * opposed to decaring a local hashmap is for convenience
3505 * so that we don't have to pass it to around.
3507 hashmap_init(&opt->priv->current_file_dir_set, path_hashmap_cmp,
3508 NULL, 512);
3509 get_files_dirs(opt, head);
3510 get_files_dirs(opt, merge);
3512 entries = get_unmerged(opt->repo->index);
3513 clean = detect_and_process_renames(opt, merge_base, head, merge,
3514 entries, &re_info);
3515 record_df_conflict_files(opt, entries);
3516 if (clean < 0)
3517 goto cleanup;
3518 for (i = entries->nr-1; 0 <= i; i--) {
3519 const char *path = entries->items[i].string;
3520 struct stage_data *e = entries->items[i].util;
3521 if (!e->processed) {
3522 int ret = process_entry(opt, path, e);
3523 if (!ret)
3524 clean = 0;
3525 else if (ret < 0) {
3526 clean = ret;
3527 goto cleanup;
3531 for (i = 0; i < entries->nr; i++) {
3532 struct stage_data *e = entries->items[i].util;
3533 if (!e->processed)
3534 BUG("unprocessed path??? %s",
3535 entries->items[i].string);
3538 cleanup:
3539 final_cleanup_renames(&re_info);
3541 string_list_clear(entries, 1);
3542 free(entries);
3544 hashmap_clear_and_free(&opt->priv->current_file_dir_set,
3545 struct path_hashmap_entry, e);
3547 if (clean < 0) {
3548 unpack_trees_finish(opt);
3549 return clean;
3552 else
3553 clean = 1;
3555 unpack_trees_finish(opt);
3557 if (opt->priv->call_depth &&
3558 !(*result = write_in_core_index_as_tree(opt->repo)))
3559 return -1;
3561 return clean;
3565 * Merge the commits h1 and h2, returning a flag (int) indicating the
3566 * cleanness of the merge. Also, if opt->priv->call_depth, create a
3567 * virtual commit and write its location to *result.
3569 static int merge_recursive_internal(struct merge_options *opt,
3570 struct commit *h1,
3571 struct commit *h2,
3572 struct commit_list *merge_bases,
3573 struct commit **result)
3575 struct commit_list *iter;
3576 struct commit *merged_merge_bases;
3577 struct tree *result_tree;
3578 int clean;
3579 const char *ancestor_name;
3580 struct strbuf merge_base_abbrev = STRBUF_INIT;
3582 if (show(opt, 4)) {
3583 output(opt, 4, _("Merging:"));
3584 output_commit_title(opt, h1);
3585 output_commit_title(opt, h2);
3588 if (!merge_bases) {
3589 merge_bases = get_merge_bases(h1, h2);
3590 merge_bases = reverse_commit_list(merge_bases);
3593 if (show(opt, 5)) {
3594 unsigned cnt = commit_list_count(merge_bases);
3596 output(opt, 5, Q_("found %u common ancestor:",
3597 "found %u common ancestors:", cnt), cnt);
3598 for (iter = merge_bases; iter; iter = iter->next)
3599 output_commit_title(opt, iter->item);
3602 merged_merge_bases = pop_commit(&merge_bases);
3603 if (merged_merge_bases == NULL) {
3604 /* if there is no common ancestor, use an empty tree */
3605 struct tree *tree;
3607 tree = lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);
3608 merged_merge_bases = make_virtual_commit(opt->repo, tree,
3609 "ancestor");
3610 ancestor_name = "empty tree";
3611 } else if (opt->ancestor && !opt->priv->call_depth) {
3612 ancestor_name = opt->ancestor;
3613 } else if (merge_bases) {
3614 ancestor_name = "merged common ancestors";
3615 } else {
3616 strbuf_add_unique_abbrev(&merge_base_abbrev,
3617 &merged_merge_bases->object.oid,
3618 DEFAULT_ABBREV);
3619 ancestor_name = merge_base_abbrev.buf;
3622 for (iter = merge_bases; iter; iter = iter->next) {
3623 const char *saved_b1, *saved_b2;
3624 opt->priv->call_depth++;
3626 * When the merge fails, the result contains files
3627 * with conflict markers. The cleanness flag is
3628 * ignored (unless indicating an error), it was never
3629 * actually used, as result of merge_trees has always
3630 * overwritten it: the committed "conflicts" were
3631 * already resolved.
3633 discard_index(opt->repo->index);
3634 saved_b1 = opt->branch1;
3635 saved_b2 = opt->branch2;
3636 opt->branch1 = "Temporary merge branch 1";
3637 opt->branch2 = "Temporary merge branch 2";
3638 if (merge_recursive_internal(opt, merged_merge_bases, iter->item,
3639 NULL, &merged_merge_bases) < 0)
3640 return -1;
3641 opt->branch1 = saved_b1;
3642 opt->branch2 = saved_b2;
3643 opt->priv->call_depth--;
3645 if (!merged_merge_bases)
3646 return err(opt, _("merge returned no commit"));
3650 * FIXME: Since merge_recursive_internal() is only ever called by
3651 * places that ensure the index is loaded first
3652 * (e.g. builtin/merge.c, rebase/sequencer, etc.), in the common
3653 * case where the merge base was unique that means when we get here
3654 * we immediately discard the index and re-read it, which is a
3655 * complete waste of time. We should only be discarding and
3656 * re-reading if we were forced to recurse.
3658 discard_index(opt->repo->index);
3659 if (!opt->priv->call_depth)
3660 repo_read_index(opt->repo);
3662 opt->ancestor = ancestor_name;
3663 clean = merge_trees_internal(opt,
3664 repo_get_commit_tree(opt->repo, h1),
3665 repo_get_commit_tree(opt->repo, h2),
3666 repo_get_commit_tree(opt->repo,
3667 merged_merge_bases),
3668 &result_tree);
3669 strbuf_release(&merge_base_abbrev);
3670 opt->ancestor = NULL; /* avoid accidental re-use of opt->ancestor */
3671 if (clean < 0) {
3672 flush_output(opt);
3673 return clean;
3676 if (opt->priv->call_depth) {
3677 *result = make_virtual_commit(opt->repo, result_tree,
3678 "merged tree");
3679 commit_list_insert(h1, &(*result)->parents);
3680 commit_list_insert(h2, &(*result)->parents->next);
3682 return clean;
3685 static int merge_start(struct merge_options *opt, struct tree *head)
3687 struct strbuf sb = STRBUF_INIT;
3689 /* Sanity checks on opt */
3690 assert(opt->repo);
3692 assert(opt->branch1 && opt->branch2);
3694 assert(opt->detect_renames >= -1 &&
3695 opt->detect_renames <= DIFF_DETECT_COPY);
3696 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
3697 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
3698 assert(opt->rename_limit >= -1);
3699 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
3700 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
3702 assert(opt->xdl_opts >= 0);
3703 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
3704 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
3706 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
3707 assert(opt->buffer_output <= 2);
3708 assert(opt->obuf.len == 0);
3710 assert(opt->priv == NULL);
3712 /* Sanity check on repo state; index must match head */
3713 if (repo_index_has_changes(opt->repo, head, &sb)) {
3714 err(opt, _("Your local changes to the following files would be overwritten by merge:\n %s"),
3715 sb.buf);
3716 strbuf_release(&sb);
3717 return -1;
3720 CALLOC_ARRAY(opt->priv, 1);
3721 string_list_init_dup(&opt->priv->df_conflict_file_set);
3722 return 0;
3725 static void merge_finalize(struct merge_options *opt)
3727 flush_output(opt);
3728 if (!opt->priv->call_depth && opt->buffer_output < 2)
3729 strbuf_release(&opt->obuf);
3730 if (show(opt, 2))
3731 diff_warn_rename_limit("merge.renamelimit",
3732 opt->priv->needed_rename_limit, 0);
3733 FREE_AND_NULL(opt->priv);
3736 int merge_trees(struct merge_options *opt,
3737 struct tree *head,
3738 struct tree *merge,
3739 struct tree *merge_base)
3741 int clean;
3742 struct tree *ignored;
3744 assert(opt->ancestor != NULL);
3746 if (merge_start(opt, head))
3747 return -1;
3748 clean = merge_trees_internal(opt, head, merge, merge_base, &ignored);
3749 merge_finalize(opt);
3751 return clean;
3754 int merge_recursive(struct merge_options *opt,
3755 struct commit *h1,
3756 struct commit *h2,
3757 struct commit_list *merge_bases,
3758 struct commit **result)
3760 int clean;
3762 assert(opt->ancestor == NULL ||
3763 !strcmp(opt->ancestor, "constructed merge base"));
3765 prepare_repo_settings(opt->repo);
3766 opt->repo->settings.command_requires_full_index = 1;
3768 if (merge_start(opt, repo_get_commit_tree(opt->repo, h1)))
3769 return -1;
3770 clean = merge_recursive_internal(opt, h1, h2, merge_bases, result);
3771 merge_finalize(opt);
3773 return clean;
3776 static struct commit *get_ref(struct repository *repo,
3777 const struct object_id *oid,
3778 const char *name)
3780 struct object *object;
3782 object = deref_tag(repo, parse_object(repo, oid),
3783 name, strlen(name));
3784 if (!object)
3785 return NULL;
3786 if (object->type == OBJ_TREE)
3787 return make_virtual_commit(repo, (struct tree*)object, name);
3788 if (object->type != OBJ_COMMIT)
3789 return NULL;
3790 if (parse_commit((struct commit *)object))
3791 return NULL;
3792 return (struct commit *)object;
3795 int merge_recursive_generic(struct merge_options *opt,
3796 const struct object_id *head,
3797 const struct object_id *merge,
3798 int num_merge_bases,
3799 const struct object_id **merge_bases,
3800 struct commit **result)
3802 int clean;
3803 struct lock_file lock = LOCK_INIT;
3804 struct commit *head_commit = get_ref(opt->repo, head, opt->branch1);
3805 struct commit *next_commit = get_ref(opt->repo, merge, opt->branch2);
3806 struct commit_list *ca = NULL;
3808 if (merge_bases) {
3809 int i;
3810 for (i = 0; i < num_merge_bases; ++i) {
3811 struct commit *base;
3812 if (!(base = get_ref(opt->repo, merge_bases[i],
3813 oid_to_hex(merge_bases[i]))))
3814 return err(opt, _("Could not parse object '%s'"),
3815 oid_to_hex(merge_bases[i]));
3816 commit_list_insert(base, &ca);
3818 if (num_merge_bases == 1)
3819 opt->ancestor = "constructed merge base";
3822 repo_hold_locked_index(opt->repo, &lock, LOCK_DIE_ON_ERROR);
3823 clean = merge_recursive(opt, head_commit, next_commit, ca,
3824 result);
3825 if (clean < 0) {
3826 rollback_lock_file(&lock);
3827 return clean;
3830 if (write_locked_index(opt->repo->index, &lock,
3831 COMMIT_LOCK | SKIP_IF_UNCHANGED))
3832 return err(opt, _("Unable to write index."));
3834 return clean ? 0 : 1;
3837 static void merge_recursive_config(struct merge_options *opt)
3839 char *value = NULL;
3840 int renormalize = 0;
3841 git_config_get_int("merge.verbosity", &opt->verbosity);
3842 git_config_get_int("diff.renamelimit", &opt->rename_limit);
3843 git_config_get_int("merge.renamelimit", &opt->rename_limit);
3844 git_config_get_bool("merge.renormalize", &renormalize);
3845 opt->renormalize = renormalize;
3846 if (!git_config_get_string("diff.renames", &value)) {
3847 opt->detect_renames = git_config_rename("diff.renames", value);
3848 free(value);
3850 if (!git_config_get_string("merge.renames", &value)) {
3851 opt->detect_renames = git_config_rename("merge.renames", value);
3852 free(value);
3854 if (!git_config_get_string("merge.directoryrenames", &value)) {
3855 int boolval = git_parse_maybe_bool(value);
3856 if (0 <= boolval) {
3857 opt->detect_directory_renames = boolval ?
3858 MERGE_DIRECTORY_RENAMES_TRUE :
3859 MERGE_DIRECTORY_RENAMES_NONE;
3860 } else if (!strcasecmp(value, "conflict")) {
3861 opt->detect_directory_renames =
3862 MERGE_DIRECTORY_RENAMES_CONFLICT;
3863 } /* avoid erroring on values from future versions of git */
3864 free(value);
3866 git_config(git_xmerge_config, NULL);
3869 void init_merge_options(struct merge_options *opt,
3870 struct repository *repo)
3872 const char *merge_verbosity;
3873 memset(opt, 0, sizeof(struct merge_options));
3875 opt->repo = repo;
3877 opt->detect_renames = -1;
3878 opt->detect_directory_renames = MERGE_DIRECTORY_RENAMES_CONFLICT;
3879 opt->rename_limit = -1;
3881 opt->verbosity = 2;
3882 opt->buffer_output = 1;
3883 strbuf_init(&opt->obuf, 0);
3885 opt->renormalize = 0;
3887 merge_recursive_config(opt);
3888 merge_verbosity = getenv("GIT_MERGE_VERBOSITY");
3889 if (merge_verbosity)
3890 opt->verbosity = strtol(merge_verbosity, NULL, 10);
3891 if (opt->verbosity >= 5)
3892 opt->buffer_output = 0;
3895 int parse_merge_opt(struct merge_options *opt, const char *s)
3897 const char *arg;
3899 if (!s || !*s)
3900 return -1;
3901 if (!strcmp(s, "ours"))
3902 opt->recursive_variant = MERGE_VARIANT_OURS;
3903 else if (!strcmp(s, "theirs"))
3904 opt->recursive_variant = MERGE_VARIANT_THEIRS;
3905 else if (!strcmp(s, "subtree"))
3906 opt->subtree_shift = "";
3907 else if (skip_prefix(s, "subtree=", &arg))
3908 opt->subtree_shift = arg;
3909 else if (!strcmp(s, "patience"))
3910 opt->xdl_opts = DIFF_WITH_ALG(opt, PATIENCE_DIFF);
3911 else if (!strcmp(s, "histogram"))
3912 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
3913 else if (skip_prefix(s, "diff-algorithm=", &arg)) {
3914 long value = parse_algorithm_value(arg);
3915 if (value < 0)
3916 return -1;
3917 /* clear out previous settings */
3918 DIFF_XDL_CLR(opt, NEED_MINIMAL);
3919 opt->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3920 opt->xdl_opts |= value;
3922 else if (!strcmp(s, "ignore-space-change"))
3923 DIFF_XDL_SET(opt, IGNORE_WHITESPACE_CHANGE);
3924 else if (!strcmp(s, "ignore-all-space"))
3925 DIFF_XDL_SET(opt, IGNORE_WHITESPACE);
3926 else if (!strcmp(s, "ignore-space-at-eol"))
3927 DIFF_XDL_SET(opt, IGNORE_WHITESPACE_AT_EOL);
3928 else if (!strcmp(s, "ignore-cr-at-eol"))
3929 DIFF_XDL_SET(opt, IGNORE_CR_AT_EOL);
3930 else if (!strcmp(s, "renormalize"))
3931 opt->renormalize = 1;
3932 else if (!strcmp(s, "no-renormalize"))
3933 opt->renormalize = 0;
3934 else if (!strcmp(s, "no-renames"))
3935 opt->detect_renames = 0;
3936 else if (!strcmp(s, "find-renames")) {
3937 opt->detect_renames = 1;
3938 opt->rename_score = 0;
3940 else if (skip_prefix(s, "find-renames=", &arg) ||
3941 skip_prefix(s, "rename-threshold=", &arg)) {
3942 if ((opt->rename_score = parse_rename_score(&arg)) == -1 || *arg != 0)
3943 return -1;
3944 opt->detect_renames = 1;
3947 * Please update $__git_merge_strategy_options in
3948 * git-completion.bash when you add new options
3950 else
3951 return -1;
3952 return 0;