The eighth batch
[git.git] / merge-ort.c
blob55decb2587e03374be843b218507f3c752652ea0
1 /*
2 * "Ostensibly Recursive's Twin" merge strategy, or "ort" for short. Meant
3 * as a drop-in replacement for the "recursive" merge strategy, allowing one
4 * to replace
6 * git merge [-s recursive]
8 * with
10 * git merge -s ort
12 * Note: git's parser allows the space between '-s' and its argument to be
13 * missing. (Should I have backronymed "ham", "alsa", "kip", "nap, "alvo",
14 * "cale", "peedy", or "ins" instead of "ort"?)
17 #include "cache.h"
18 #include "merge-ort.h"
20 #include "alloc.h"
21 #include "attr.h"
22 #include "blob.h"
23 #include "cache-tree.h"
24 #include "commit.h"
25 #include "commit-reach.h"
26 #include "diff.h"
27 #include "diffcore.h"
28 #include "dir.h"
29 #include "entry.h"
30 #include "ll-merge.h"
31 #include "object-store.h"
32 #include "promisor-remote.h"
33 #include "revision.h"
34 #include "strmap.h"
35 #include "submodule-config.h"
36 #include "submodule.h"
37 #include "tree.h"
38 #include "unpack-trees.h"
39 #include "xdiff-interface.h"
42 * We have many arrays of size 3. Whenever we have such an array, the
43 * indices refer to one of the sides of the three-way merge. This is so
44 * pervasive that the constants 0, 1, and 2 are used in many places in the
45 * code (especially in arithmetic operations to find the other side's index
46 * or to compute a relevant mask), but sometimes these enum names are used
47 * to aid code clarity.
49 * See also 'filemask' and 'dirmask' in struct conflict_info; the "ith side"
50 * referred to there is one of these three sides.
52 enum merge_side {
53 MERGE_BASE = 0,
54 MERGE_SIDE1 = 1,
55 MERGE_SIDE2 = 2
58 static unsigned RESULT_INITIALIZED = 0x1abe11ed; /* unlikely accidental value */
60 struct traversal_callback_data {
61 unsigned long mask;
62 unsigned long dirmask;
63 struct name_entry names[3];
66 struct deferred_traversal_data {
68 * possible_trivial_merges: directories to be explored only when needed
70 * possible_trivial_merges is a map of directory names to
71 * dir_rename_mask. When we detect that a directory is unchanged on
72 * one side, we can sometimes resolve the directory without recursing
73 * into it. Renames are the only things that can prevent such an
74 * optimization. However, for rename sources:
75 * - If no parent directory needed directory rename detection, then
76 * no path under such a directory can be a relevant_source.
77 * and for rename destinations:
78 * - If no cached rename has a target path under the directory AND
79 * - If there are no unpaired relevant_sources elsewhere in the
80 * repository
81 * then we don't need any path under this directory for a rename
82 * destination. The only way to know the last item above is to defer
83 * handling such directories until the end of collect_merge_info(),
84 * in handle_deferred_entries().
86 * For each we store dir_rename_mask, since that's the only bit of
87 * information we need, other than the path, to resume the recursive
88 * traversal.
90 struct strintmap possible_trivial_merges;
93 * trivial_merges_okay: if trivial directory merges are okay
95 * See possible_trivial_merges above. The "no unpaired
96 * relevant_sources elsewhere in the repository" is a single boolean
97 * per merge side, which we store here. Note that while 0 means no,
98 * 1 only means "maybe" rather than "yes"; we optimistically set it
99 * to 1 initially and only clear when we determine it is unsafe to
100 * do trivial directory merges.
102 unsigned trivial_merges_okay;
105 * target_dirs: ancestor directories of rename targets
107 * target_dirs contains all directory names that are an ancestor of
108 * any rename destination.
110 struct strset target_dirs;
113 struct rename_info {
115 * All variables that are arrays of size 3 correspond to data tracked
116 * for the sides in enum merge_side. Index 0 is almost always unused
117 * because we often only need to track information for MERGE_SIDE1 and
118 * MERGE_SIDE2 (MERGE_BASE can't have rename information since renames
119 * are determined relative to what changed since the MERGE_BASE).
123 * pairs: pairing of filenames from diffcore_rename()
125 struct diff_queue_struct pairs[3];
128 * dirs_removed: directories removed on a given side of history.
130 * The keys of dirs_removed[side] are the directories that were removed
131 * on the given side of history. The value of the strintmap for each
132 * directory is a value from enum dir_rename_relevance.
134 struct strintmap dirs_removed[3];
137 * dir_rename_count: tracking where parts of a directory were renamed to
139 * When files in a directory are renamed, they may not all go to the
140 * same location. Each strmap here tracks:
141 * old_dir => {new_dir => int}
142 * That is, dir_rename_count[side] is a strmap to a strintmap.
144 struct strmap dir_rename_count[3];
147 * dir_renames: computed directory renames
149 * This is a map of old_dir => new_dir and is derived in part from
150 * dir_rename_count.
152 struct strmap dir_renames[3];
155 * relevant_sources: deleted paths wanted in rename detection, and why
157 * relevant_sources is a set of deleted paths on each side of
158 * history for which we need rename detection. If a path is deleted
159 * on one side of history, we need to detect if it is part of a
160 * rename if either
161 * * the file is modified/deleted on the other side of history
162 * * we need to detect renames for an ancestor directory
163 * If neither of those are true, we can skip rename detection for
164 * that path. The reason is stored as a value from enum
165 * file_rename_relevance, as the reason can inform the algorithm in
166 * diffcore_rename_extended().
168 struct strintmap relevant_sources[3];
170 struct deferred_traversal_data deferred[3];
173 * dir_rename_mask:
174 * 0: optimization removing unmodified potential rename source okay
175 * 2 or 4: optimization okay, but must check for files added to dir
176 * 7: optimization forbidden; need rename source in case of dir rename
178 unsigned dir_rename_mask:3;
181 * callback_data_*: supporting data structures for alternate traversal
183 * We sometimes need to be able to traverse through all the files
184 * in a given tree before all immediate subdirectories within that
185 * tree. Since traverse_trees() doesn't do that naturally, we have
186 * a traverse_trees_wrapper() that stores any immediate
187 * subdirectories while traversing files, then traverses the
188 * immediate subdirectories later. These callback_data* variables
189 * store the information for the subdirectories so that we can do
190 * that traversal order.
192 struct traversal_callback_data *callback_data;
193 int callback_data_nr, callback_data_alloc;
194 char *callback_data_traverse_path;
197 * merge_trees: trees passed to the merge algorithm for the merge
199 * merge_trees records the trees passed to the merge algorithm. But,
200 * this data also is stored in merge_result->priv. If a sequence of
201 * merges are being done (such as when cherry-picking or rebasing),
202 * the next merge can look at this and re-use information from
203 * previous merges under certain circumstances.
205 * See also all the cached_* variables.
207 struct tree *merge_trees[3];
210 * cached_pairs_valid_side: which side's cached info can be reused
212 * See the description for merge_trees. For repeated merges, at most
213 * only one side's cached information can be used. Valid values:
214 * MERGE_SIDE2: cached data from side2 can be reused
215 * MERGE_SIDE1: cached data from side1 can be reused
216 * 0: no cached data can be reused
217 * -1: See redo_after_renames; both sides can be reused.
219 int cached_pairs_valid_side;
222 * cached_pairs: Caching of renames and deletions.
224 * These are mappings recording renames and deletions of individual
225 * files (not directories). They are thus a map from an old
226 * filename to either NULL (for deletions) or a new filename (for
227 * renames).
229 struct strmap cached_pairs[3];
232 * cached_target_names: just the destinations from cached_pairs
234 * We sometimes want a fast lookup to determine if a given filename
235 * is one of the destinations in cached_pairs. cached_target_names
236 * is thus duplicative information, but it provides a fast lookup.
238 struct strset cached_target_names[3];
241 * cached_irrelevant: Caching of rename_sources that aren't relevant.
243 * If we try to detect a rename for a source path and succeed, it's
244 * part of a rename. If we try to detect a rename for a source path
245 * and fail, then it's a delete. If we do not try to detect a rename
246 * for a path, then we don't know if it's a rename or a delete. If
247 * merge-ort doesn't think the path is relevant, then we just won't
248 * cache anything for that path. But there's a slight problem in
249 * that merge-ort can think a path is RELEVANT_LOCATION, but due to
250 * commit 9bd342137e ("diffcore-rename: determine which
251 * relevant_sources are no longer relevant", 2021-03-13),
252 * diffcore-rename can downgrade the path to RELEVANT_NO_MORE. To
253 * avoid excessive calls to diffcore_rename_extended() we still need
254 * to cache such paths, though we cannot record them as either
255 * renames or deletes. So we cache them here as a "turned out to be
256 * irrelevant *for this commit*" as they are often also irrelevant
257 * for subsequent commits, though we will have to do some extra
258 * checking to see whether such paths become relevant for rename
259 * detection when cherry-picking/rebasing subsequent commits.
261 struct strset cached_irrelevant[3];
264 * redo_after_renames: optimization flag for "restarting" the merge
266 * Sometimes it pays to detect renames, cache them, and then
267 * restart the merge operation from the beginning. The reason for
268 * this is that when we know where all the renames are, we know
269 * whether a certain directory has any paths under it affected --
270 * and if a directory is not affected then it permits us to do
271 * trivial tree merging in more cases. Doing trivial tree merging
272 * prevents the need to run process_entry() on every path
273 * underneath trees that can be trivially merged, and
274 * process_entry() is more expensive than collect_merge_info() --
275 * plus, the second collect_merge_info() will be much faster since
276 * it doesn't have to recurse into the relevant trees.
278 * Values for this flag:
279 * 0 = don't bother, not worth it (or conditions not yet checked)
280 * 1 = conditions for optimization met, optimization worthwhile
281 * 2 = we already did it (don't restart merge yet again)
283 unsigned redo_after_renames;
286 * needed_limit: value needed for inexact rename detection to run
288 * If the current rename limit wasn't high enough for inexact
289 * rename detection to run, this records the limit needed. Otherwise,
290 * this value remains 0.
292 int needed_limit;
295 struct merge_options_internal {
297 * paths: primary data structure in all of merge ort.
299 * The keys of paths:
300 * * are full relative paths from the toplevel of the repository
301 * (e.g. "drivers/firmware/raspberrypi.c").
302 * * store all relevant paths in the repo, both directories and
303 * files (e.g. drivers, drivers/firmware would also be included)
304 * * these keys serve to intern all the path strings, which allows
305 * us to do pointer comparison on directory names instead of
306 * strcmp; we just have to be careful to use the interned strings.
308 * The values of paths:
309 * * either a pointer to a merged_info, or a conflict_info struct
310 * * merged_info contains all relevant information for a
311 * non-conflicted entry.
312 * * conflict_info contains a merged_info, plus any additional
313 * information about a conflict such as the higher orders stages
314 * involved and the names of the paths those came from (handy
315 * once renames get involved).
316 * * a path may start "conflicted" (i.e. point to a conflict_info)
317 * and then a later step (e.g. three-way content merge) determines
318 * it can be cleanly merged, at which point it'll be marked clean
319 * and the algorithm will ignore any data outside the contained
320 * merged_info for that entry
321 * * If an entry remains conflicted, the merged_info portion of a
322 * conflict_info will later be filled with whatever version of
323 * the file should be placed in the working directory (e.g. an
324 * as-merged-as-possible variation that contains conflict markers).
326 struct strmap paths;
329 * conflicted: a subset of keys->values from "paths"
331 * conflicted is basically an optimization between process_entries()
332 * and record_conflicted_index_entries(); the latter could loop over
333 * ALL the entries in paths AGAIN and look for the ones that are
334 * still conflicted, but since process_entries() has to loop over
335 * all of them, it saves the ones it couldn't resolve in this strmap
336 * so that record_conflicted_index_entries() can iterate just the
337 * relevant entries.
339 struct strmap conflicted;
342 * pool: memory pool for fast allocation/deallocation
344 * We allocate room for lots of filenames and auxiliary data
345 * structures in merge_options_internal, and it tends to all be
346 * freed together too. Using a memory pool for these provides a
347 * nice speedup.
349 struct mem_pool pool;
352 * output: special messages and conflict notices for various paths
354 * This is a map of pathnames (a subset of the keys in "paths" above)
355 * to strbufs. It gathers various warning/conflict/notice messages
356 * for later processing.
358 struct strmap output;
361 * renames: various data relating to rename detection
363 struct rename_info renames;
366 * attr_index: hacky minimal index used for renormalization
368 * renormalization code _requires_ an index, though it only needs to
369 * find a .gitattributes file within the index. So, when
370 * renormalization is important, we create a special index with just
371 * that one file.
373 struct index_state attr_index;
376 * current_dir_name, toplevel_dir: temporary vars
378 * These are used in collect_merge_info_callback(), and will set the
379 * various merged_info.directory_name for the various paths we get;
380 * see documentation for that variable and the requirements placed on
381 * that field.
383 const char *current_dir_name;
384 const char *toplevel_dir;
386 /* call_depth: recursion level counter for merging merge bases */
387 int call_depth;
390 struct version_info {
391 struct object_id oid;
392 unsigned short mode;
395 struct merged_info {
396 /* if is_null, ignore result. otherwise result has oid & mode */
397 struct version_info result;
398 unsigned is_null:1;
401 * clean: whether the path in question is cleanly merged.
403 * see conflict_info.merged for more details.
405 unsigned clean:1;
408 * basename_offset: offset of basename of path.
410 * perf optimization to avoid recomputing offset of final '/'
411 * character in pathname (0 if no '/' in pathname).
413 size_t basename_offset;
416 * directory_name: containing directory name.
418 * Note that we assume directory_name is constructed such that
419 * strcmp(dir1_name, dir2_name) == 0 iff dir1_name == dir2_name,
420 * i.e. string equality is equivalent to pointer equality. For this
421 * to hold, we have to be careful setting directory_name.
423 const char *directory_name;
426 struct conflict_info {
428 * merged: the version of the path that will be written to working tree
430 * WARNING: It is critical to check merged.clean and ensure it is 0
431 * before reading any conflict_info fields outside of merged.
432 * Allocated merge_info structs will always have clean set to 1.
433 * Allocated conflict_info structs will have merged.clean set to 0
434 * initially. The merged.clean field is how we know if it is safe
435 * to access other parts of conflict_info besides merged; if a
436 * conflict_info's merged.clean is changed to 1, the rest of the
437 * algorithm is not allowed to look at anything outside of the
438 * merged member anymore.
440 struct merged_info merged;
442 /* oids & modes from each of the three trees for this path */
443 struct version_info stages[3];
445 /* pathnames for each stage; may differ due to rename detection */
446 const char *pathnames[3];
448 /* Whether this path is/was involved in a directory/file conflict */
449 unsigned df_conflict:1;
452 * Whether this path is/was involved in a non-content conflict other
453 * than a directory/file conflict (e.g. rename/rename, rename/delete,
454 * file location based on possible directory rename).
456 unsigned path_conflict:1;
459 * For filemask and dirmask, the ith bit corresponds to whether the
460 * ith entry is a file (filemask) or a directory (dirmask). Thus,
461 * filemask & dirmask is always zero, and filemask | dirmask is at
462 * most 7 but can be less when a path does not appear as either a
463 * file or a directory on at least one side of history.
465 * Note that these masks are related to enum merge_side, as the ith
466 * entry corresponds to side i.
468 * These values come from a traverse_trees() call; more info may be
469 * found looking at tree-walk.h's struct traverse_info,
470 * particularly the documentation above the "fn" member (note that
471 * filemask = mask & ~dirmask from that documentation).
473 unsigned filemask:3;
474 unsigned dirmask:3;
477 * Optimization to track which stages match, to avoid the need to
478 * recompute it in multiple steps. Either 0 or at least 2 bits are
479 * set; if at least 2 bits are set, their corresponding stages match.
481 unsigned match_mask:3;
484 /*** Function Grouping: various utility functions ***/
487 * For the next three macros, see warning for conflict_info.merged.
489 * In each of the below, mi is a struct merged_info*, and ci was defined
490 * as a struct conflict_info* (but we need to verify ci isn't actually
491 * pointed at a struct merged_info*).
493 * INITIALIZE_CI: Assign ci to mi but only if it's safe; set to NULL otherwise.
494 * VERIFY_CI: Ensure that something we assigned to a conflict_info* is one.
495 * ASSIGN_AND_VERIFY_CI: Similar to VERIFY_CI but do assignment first.
497 #define INITIALIZE_CI(ci, mi) do { \
498 (ci) = (!(mi) || (mi)->clean) ? NULL : (struct conflict_info *)(mi); \
499 } while (0)
500 #define VERIFY_CI(ci) assert(ci && !ci->merged.clean);
501 #define ASSIGN_AND_VERIFY_CI(ci, mi) do { \
502 (ci) = (struct conflict_info *)(mi); \
503 assert((ci) && !(mi)->clean); \
504 } while (0)
506 static void free_strmap_strings(struct strmap *map)
508 struct hashmap_iter iter;
509 struct strmap_entry *entry;
511 strmap_for_each_entry(map, &iter, entry) {
512 free((char*)entry->key);
516 static void clear_or_reinit_internal_opts(struct merge_options_internal *opti,
517 int reinitialize)
519 struct rename_info *renames = &opti->renames;
520 int i;
521 void (*strmap_clear_func)(struct strmap *, int) =
522 reinitialize ? strmap_partial_clear : strmap_clear;
523 void (*strintmap_clear_func)(struct strintmap *) =
524 reinitialize ? strintmap_partial_clear : strintmap_clear;
525 void (*strset_clear_func)(struct strset *) =
526 reinitialize ? strset_partial_clear : strset_clear;
528 strmap_clear_func(&opti->paths, 0);
531 * All keys and values in opti->conflicted are a subset of those in
532 * opti->paths. We don't want to deallocate anything twice, so we
533 * don't free the keys and we pass 0 for free_values.
535 strmap_clear_func(&opti->conflicted, 0);
537 if (opti->attr_index.cache_nr) /* true iff opt->renormalize */
538 discard_index(&opti->attr_index);
540 /* Free memory used by various renames maps */
541 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; ++i) {
542 strintmap_clear_func(&renames->dirs_removed[i]);
543 strmap_clear_func(&renames->dir_renames[i], 0);
544 strintmap_clear_func(&renames->relevant_sources[i]);
545 if (!reinitialize)
546 assert(renames->cached_pairs_valid_side == 0);
547 if (i != renames->cached_pairs_valid_side &&
548 -1 != renames->cached_pairs_valid_side) {
549 strset_clear_func(&renames->cached_target_names[i]);
550 strmap_clear_func(&renames->cached_pairs[i], 1);
551 strset_clear_func(&renames->cached_irrelevant[i]);
552 partial_clear_dir_rename_count(&renames->dir_rename_count[i]);
553 if (!reinitialize)
554 strmap_clear(&renames->dir_rename_count[i], 1);
557 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; ++i) {
558 strintmap_clear_func(&renames->deferred[i].possible_trivial_merges);
559 strset_clear_func(&renames->deferred[i].target_dirs);
560 renames->deferred[i].trivial_merges_okay = 1; /* 1 == maybe */
562 renames->cached_pairs_valid_side = 0;
563 renames->dir_rename_mask = 0;
565 if (!reinitialize) {
566 struct hashmap_iter iter;
567 struct strmap_entry *e;
569 /* Release and free each strbuf found in output */
570 strmap_for_each_entry(&opti->output, &iter, e) {
571 struct strbuf *sb = e->value;
572 strbuf_release(sb);
574 * While strictly speaking we don't need to free(sb)
575 * here because we could pass free_values=1 when
576 * calling strmap_clear() on opti->output, that would
577 * require strmap_clear to do another
578 * strmap_for_each_entry() loop, so we just free it
579 * while we're iterating anyway.
581 free(sb);
583 strmap_clear(&opti->output, 0);
586 mem_pool_discard(&opti->pool, 0);
588 /* Clean out callback_data as well. */
589 FREE_AND_NULL(renames->callback_data);
590 renames->callback_data_nr = renames->callback_data_alloc = 0;
593 __attribute__((format (printf, 2, 3)))
594 static int err(struct merge_options *opt, const char *err, ...)
596 va_list params;
597 struct strbuf sb = STRBUF_INIT;
599 strbuf_addstr(&sb, "error: ");
600 va_start(params, err);
601 strbuf_vaddf(&sb, err, params);
602 va_end(params);
604 error("%s", sb.buf);
605 strbuf_release(&sb);
607 return -1;
610 static void format_commit(struct strbuf *sb,
611 int indent,
612 struct repository *repo,
613 struct commit *commit)
615 struct merge_remote_desc *desc;
616 struct pretty_print_context ctx = {0};
617 ctx.abbrev = DEFAULT_ABBREV;
619 strbuf_addchars(sb, ' ', indent);
620 desc = merge_remote_util(commit);
621 if (desc) {
622 strbuf_addf(sb, "virtual %s\n", desc->name);
623 return;
626 repo_format_commit_message(repo, commit, "%h %s", sb, &ctx);
627 strbuf_addch(sb, '\n');
630 __attribute__((format (printf, 4, 5)))
631 static void path_msg(struct merge_options *opt,
632 const char *path,
633 int omittable_hint, /* skippable under --remerge-diff */
634 const char *fmt, ...)
636 va_list ap;
637 struct strbuf *sb, *dest;
638 struct strbuf tmp = STRBUF_INIT;
640 if (opt->record_conflict_msgs_as_headers && omittable_hint)
641 return; /* Do not record mere hints in headers */
642 if (opt->record_conflict_msgs_as_headers && opt->priv->call_depth)
643 return; /* Do not record inner merge issues in headers */
644 sb = strmap_get(&opt->priv->output, path);
645 if (!sb) {
646 sb = xmalloc(sizeof(*sb));
647 strbuf_init(sb, 0);
648 strmap_put(&opt->priv->output, path, sb);
651 dest = (opt->record_conflict_msgs_as_headers ? &tmp : sb);
653 va_start(ap, fmt);
654 if (opt->priv->call_depth) {
655 strbuf_addchars(dest, ' ', 2);
656 strbuf_addstr(dest, "From inner merge:");
657 strbuf_addchars(dest, ' ', opt->priv->call_depth * 2);
659 strbuf_vaddf(dest, fmt, ap);
660 va_end(ap);
662 if (opt->record_conflict_msgs_as_headers) {
663 int i_sb = 0, i_tmp = 0;
665 /* Start with the specified prefix */
666 if (opt->msg_header_prefix)
667 strbuf_addf(sb, "%s ", opt->msg_header_prefix);
669 /* Copy tmp to sb, adding spaces after newlines */
670 strbuf_grow(sb, sb->len + 2*tmp.len); /* more than sufficient */
671 for (; i_tmp < tmp.len; i_tmp++, i_sb++) {
672 /* Copy next character from tmp to sb */
673 sb->buf[sb->len + i_sb] = tmp.buf[i_tmp];
675 /* If we copied a newline, add a space */
676 if (tmp.buf[i_tmp] == '\n')
677 sb->buf[++i_sb] = ' ';
679 /* Update length and ensure it's NUL-terminated */
680 sb->len += i_sb;
681 sb->buf[sb->len] = '\0';
683 strbuf_release(&tmp);
686 /* Add final newline character to sb */
687 strbuf_addch(sb, '\n');
690 static struct diff_filespec *pool_alloc_filespec(struct mem_pool *pool,
691 const char *path)
693 /* Similar to alloc_filespec(), but allocate from pool and reuse path */
694 struct diff_filespec *spec;
696 spec = mem_pool_calloc(pool, 1, sizeof(*spec));
697 spec->path = (char*)path; /* spec won't modify it */
699 spec->count = 1;
700 spec->is_binary = -1;
701 return spec;
704 static struct diff_filepair *pool_diff_queue(struct mem_pool *pool,
705 struct diff_queue_struct *queue,
706 struct diff_filespec *one,
707 struct diff_filespec *two)
709 /* Same code as diff_queue(), except allocate from pool */
710 struct diff_filepair *dp;
712 dp = mem_pool_calloc(pool, 1, sizeof(*dp));
713 dp->one = one;
714 dp->two = two;
715 if (queue)
716 diff_q(queue, dp);
717 return dp;
720 /* add a string to a strbuf, but converting "/" to "_" */
721 static void add_flattened_path(struct strbuf *out, const char *s)
723 size_t i = out->len;
724 strbuf_addstr(out, s);
725 for (; i < out->len; i++)
726 if (out->buf[i] == '/')
727 out->buf[i] = '_';
730 static char *unique_path(struct strmap *existing_paths,
731 const char *path,
732 const char *branch)
734 struct strbuf newpath = STRBUF_INIT;
735 int suffix = 0;
736 size_t base_len;
738 strbuf_addf(&newpath, "%s~", path);
739 add_flattened_path(&newpath, branch);
741 base_len = newpath.len;
742 while (strmap_contains(existing_paths, newpath.buf)) {
743 strbuf_setlen(&newpath, base_len);
744 strbuf_addf(&newpath, "_%d", suffix++);
747 return strbuf_detach(&newpath, NULL);
750 /*** Function Grouping: functions related to collect_merge_info() ***/
752 static int traverse_trees_wrapper_callback(int n,
753 unsigned long mask,
754 unsigned long dirmask,
755 struct name_entry *names,
756 struct traverse_info *info)
758 struct merge_options *opt = info->data;
759 struct rename_info *renames = &opt->priv->renames;
760 unsigned filemask = mask & ~dirmask;
762 assert(n==3);
764 if (!renames->callback_data_traverse_path)
765 renames->callback_data_traverse_path = xstrdup(info->traverse_path);
767 if (filemask && filemask == renames->dir_rename_mask)
768 renames->dir_rename_mask = 0x07;
770 ALLOC_GROW(renames->callback_data, renames->callback_data_nr + 1,
771 renames->callback_data_alloc);
772 renames->callback_data[renames->callback_data_nr].mask = mask;
773 renames->callback_data[renames->callback_data_nr].dirmask = dirmask;
774 COPY_ARRAY(renames->callback_data[renames->callback_data_nr].names,
775 names, 3);
776 renames->callback_data_nr++;
778 return mask;
782 * Much like traverse_trees(), BUT:
783 * - read all the tree entries FIRST, saving them
784 * - note that the above step provides an opportunity to compute necessary
785 * additional details before the "real" traversal
786 * - loop through the saved entries and call the original callback on them
788 static int traverse_trees_wrapper(struct index_state *istate,
789 int n,
790 struct tree_desc *t,
791 struct traverse_info *info)
793 int ret, i, old_offset;
794 traverse_callback_t old_fn;
795 char *old_callback_data_traverse_path;
796 struct merge_options *opt = info->data;
797 struct rename_info *renames = &opt->priv->renames;
799 assert(renames->dir_rename_mask == 2 || renames->dir_rename_mask == 4);
801 old_callback_data_traverse_path = renames->callback_data_traverse_path;
802 old_fn = info->fn;
803 old_offset = renames->callback_data_nr;
805 renames->callback_data_traverse_path = NULL;
806 info->fn = traverse_trees_wrapper_callback;
807 ret = traverse_trees(istate, n, t, info);
808 if (ret < 0)
809 return ret;
811 info->traverse_path = renames->callback_data_traverse_path;
812 info->fn = old_fn;
813 for (i = old_offset; i < renames->callback_data_nr; ++i) {
814 info->fn(n,
815 renames->callback_data[i].mask,
816 renames->callback_data[i].dirmask,
817 renames->callback_data[i].names,
818 info);
821 renames->callback_data_nr = old_offset;
822 free(renames->callback_data_traverse_path);
823 renames->callback_data_traverse_path = old_callback_data_traverse_path;
824 info->traverse_path = NULL;
825 return 0;
828 static void setup_path_info(struct merge_options *opt,
829 struct string_list_item *result,
830 const char *current_dir_name,
831 int current_dir_name_len,
832 char *fullpath, /* we'll take over ownership */
833 struct name_entry *names,
834 struct name_entry *merged_version,
835 unsigned is_null, /* boolean */
836 unsigned df_conflict, /* boolean */
837 unsigned filemask,
838 unsigned dirmask,
839 int resolved /* boolean */)
841 /* result->util is void*, so mi is a convenience typed variable */
842 struct merged_info *mi;
844 assert(!is_null || resolved);
845 assert(!df_conflict || !resolved); /* df_conflict implies !resolved */
846 assert(resolved == (merged_version != NULL));
848 mi = mem_pool_calloc(&opt->priv->pool, 1,
849 resolved ? sizeof(struct merged_info) :
850 sizeof(struct conflict_info));
851 mi->directory_name = current_dir_name;
852 mi->basename_offset = current_dir_name_len;
853 mi->clean = !!resolved;
854 if (resolved) {
855 mi->result.mode = merged_version->mode;
856 oidcpy(&mi->result.oid, &merged_version->oid);
857 mi->is_null = !!is_null;
858 } else {
859 int i;
860 struct conflict_info *ci;
862 ASSIGN_AND_VERIFY_CI(ci, mi);
863 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
864 ci->pathnames[i] = fullpath;
865 ci->stages[i].mode = names[i].mode;
866 oidcpy(&ci->stages[i].oid, &names[i].oid);
868 ci->filemask = filemask;
869 ci->dirmask = dirmask;
870 ci->df_conflict = !!df_conflict;
871 if (dirmask)
873 * Assume is_null for now, but if we have entries
874 * under the directory then when it is complete in
875 * write_completed_directory() it'll update this.
876 * Also, for D/F conflicts, we have to handle the
877 * directory first, then clear this bit and process
878 * the file to see how it is handled -- that occurs
879 * near the top of process_entry().
881 mi->is_null = 1;
883 strmap_put(&opt->priv->paths, fullpath, mi);
884 result->string = fullpath;
885 result->util = mi;
888 static void add_pair(struct merge_options *opt,
889 struct name_entry *names,
890 const char *pathname,
891 unsigned side,
892 unsigned is_add /* if false, is_delete */,
893 unsigned match_mask,
894 unsigned dir_rename_mask)
896 struct diff_filespec *one, *two;
897 struct rename_info *renames = &opt->priv->renames;
898 int names_idx = is_add ? side : 0;
900 if (is_add) {
901 assert(match_mask == 0 || match_mask == 6);
902 if (strset_contains(&renames->cached_target_names[side],
903 pathname))
904 return;
905 } else {
906 unsigned content_relevant = (match_mask == 0);
907 unsigned location_relevant = (dir_rename_mask == 0x07);
909 assert(match_mask == 0 || match_mask == 3 || match_mask == 5);
912 * If pathname is found in cached_irrelevant[side] due to
913 * previous pick but for this commit content is relevant,
914 * then we need to remove it from cached_irrelevant.
916 if (content_relevant)
917 /* strset_remove is no-op if strset doesn't have key */
918 strset_remove(&renames->cached_irrelevant[side],
919 pathname);
922 * We do not need to re-detect renames for paths that we already
923 * know the pairing, i.e. for cached_pairs (or
924 * cached_irrelevant). However, handle_deferred_entries() needs
925 * to loop over the union of keys from relevant_sources[side] and
926 * cached_pairs[side], so for simplicity we set relevant_sources
927 * for all the cached_pairs too and then strip them back out in
928 * prune_cached_from_relevant() at the beginning of
929 * detect_regular_renames().
931 if (content_relevant || location_relevant) {
932 /* content_relevant trumps location_relevant */
933 strintmap_set(&renames->relevant_sources[side], pathname,
934 content_relevant ? RELEVANT_CONTENT : RELEVANT_LOCATION);
938 * Avoid creating pair if we've already cached rename results.
939 * Note that we do this after setting relevant_sources[side]
940 * as noted in the comment above.
942 if (strmap_contains(&renames->cached_pairs[side], pathname) ||
943 strset_contains(&renames->cached_irrelevant[side], pathname))
944 return;
947 one = pool_alloc_filespec(&opt->priv->pool, pathname);
948 two = pool_alloc_filespec(&opt->priv->pool, pathname);
949 fill_filespec(is_add ? two : one,
950 &names[names_idx].oid, 1, names[names_idx].mode);
951 pool_diff_queue(&opt->priv->pool, &renames->pairs[side], one, two);
954 static void collect_rename_info(struct merge_options *opt,
955 struct name_entry *names,
956 const char *dirname,
957 const char *fullname,
958 unsigned filemask,
959 unsigned dirmask,
960 unsigned match_mask)
962 struct rename_info *renames = &opt->priv->renames;
963 unsigned side;
966 * Update dir_rename_mask (determines ignore-rename-source validity)
968 * dir_rename_mask helps us keep track of when directory rename
969 * detection may be relevant. Basically, whenver a directory is
970 * removed on one side of history, and a file is added to that
971 * directory on the other side of history, directory rename
972 * detection is relevant (meaning we have to detect renames for all
973 * files within that directory to deduce where the directory
974 * moved). Also, whenever a directory needs directory rename
975 * detection, due to the "majority rules" choice for where to move
976 * it (see t6423 testcase 1f), we also need to detect renames for
977 * all files within subdirectories of that directory as well.
979 * Here we haven't looked at files within the directory yet, we are
980 * just looking at the directory itself. So, if we aren't yet in
981 * a case where a parent directory needed directory rename detection
982 * (i.e. dir_rename_mask != 0x07), and if the directory was removed
983 * on one side of history, record the mask of the other side of
984 * history in dir_rename_mask.
986 if (renames->dir_rename_mask != 0x07 &&
987 (dirmask == 3 || dirmask == 5)) {
988 /* simple sanity check */
989 assert(renames->dir_rename_mask == 0 ||
990 renames->dir_rename_mask == (dirmask & ~1));
991 /* update dir_rename_mask; have it record mask of new side */
992 renames->dir_rename_mask = (dirmask & ~1);
995 /* Update dirs_removed, as needed */
996 if (dirmask == 1 || dirmask == 3 || dirmask == 5) {
997 /* absent_mask = 0x07 - dirmask; sides = absent_mask/2 */
998 unsigned sides = (0x07 - dirmask)/2;
999 unsigned relevance = (renames->dir_rename_mask == 0x07) ?
1000 RELEVANT_FOR_ANCESTOR : NOT_RELEVANT;
1002 * Record relevance of this directory. However, note that
1003 * when collect_merge_info_callback() recurses into this
1004 * directory and calls collect_rename_info() on paths
1005 * within that directory, if we find a path that was added
1006 * to this directory on the other side of history, we will
1007 * upgrade this value to RELEVANT_FOR_SELF; see below.
1009 if (sides & 1)
1010 strintmap_set(&renames->dirs_removed[1], fullname,
1011 relevance);
1012 if (sides & 2)
1013 strintmap_set(&renames->dirs_removed[2], fullname,
1014 relevance);
1018 * Here's the block that potentially upgrades to RELEVANT_FOR_SELF.
1019 * When we run across a file added to a directory. In such a case,
1020 * find the directory of the file and upgrade its relevance.
1022 if (renames->dir_rename_mask == 0x07 &&
1023 (filemask == 2 || filemask == 4)) {
1025 * Need directory rename for parent directory on other side
1026 * of history from added file. Thus
1027 * side = (~filemask & 0x06) >> 1
1028 * or
1029 * side = 3 - (filemask/2).
1031 unsigned side = 3 - (filemask >> 1);
1032 strintmap_set(&renames->dirs_removed[side], dirname,
1033 RELEVANT_FOR_SELF);
1036 if (filemask == 0 || filemask == 7)
1037 return;
1039 for (side = MERGE_SIDE1; side <= MERGE_SIDE2; ++side) {
1040 unsigned side_mask = (1 << side);
1042 /* Check for deletion on side */
1043 if ((filemask & 1) && !(filemask & side_mask))
1044 add_pair(opt, names, fullname, side, 0 /* delete */,
1045 match_mask & filemask,
1046 renames->dir_rename_mask);
1048 /* Check for addition on side */
1049 if (!(filemask & 1) && (filemask & side_mask))
1050 add_pair(opt, names, fullname, side, 1 /* add */,
1051 match_mask & filemask,
1052 renames->dir_rename_mask);
1056 static int collect_merge_info_callback(int n,
1057 unsigned long mask,
1058 unsigned long dirmask,
1059 struct name_entry *names,
1060 struct traverse_info *info)
1063 * n is 3. Always.
1064 * common ancestor (mbase) has mask 1, and stored in index 0 of names
1065 * head of side 1 (side1) has mask 2, and stored in index 1 of names
1066 * head of side 2 (side2) has mask 4, and stored in index 2 of names
1068 struct merge_options *opt = info->data;
1069 struct merge_options_internal *opti = opt->priv;
1070 struct rename_info *renames = &opt->priv->renames;
1071 struct string_list_item pi; /* Path Info */
1072 struct conflict_info *ci; /* typed alias to pi.util (which is void*) */
1073 struct name_entry *p;
1074 size_t len;
1075 char *fullpath;
1076 const char *dirname = opti->current_dir_name;
1077 unsigned prev_dir_rename_mask = renames->dir_rename_mask;
1078 unsigned filemask = mask & ~dirmask;
1079 unsigned match_mask = 0; /* will be updated below */
1080 unsigned mbase_null = !(mask & 1);
1081 unsigned side1_null = !(mask & 2);
1082 unsigned side2_null = !(mask & 4);
1083 unsigned side1_matches_mbase = (!side1_null && !mbase_null &&
1084 names[0].mode == names[1].mode &&
1085 oideq(&names[0].oid, &names[1].oid));
1086 unsigned side2_matches_mbase = (!side2_null && !mbase_null &&
1087 names[0].mode == names[2].mode &&
1088 oideq(&names[0].oid, &names[2].oid));
1089 unsigned sides_match = (!side1_null && !side2_null &&
1090 names[1].mode == names[2].mode &&
1091 oideq(&names[1].oid, &names[2].oid));
1094 * Note: When a path is a file on one side of history and a directory
1095 * in another, we have a directory/file conflict. In such cases, if
1096 * the conflict doesn't resolve from renames and deletions, then we
1097 * always leave directories where they are and move files out of the
1098 * way. Thus, while struct conflict_info has a df_conflict field to
1099 * track such conflicts, we ignore that field for any directories at
1100 * a path and only pay attention to it for files at the given path.
1101 * The fact that we leave directories were they are also means that
1102 * we do not need to worry about getting additional df_conflict
1103 * information propagated from parent directories down to children
1104 * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
1105 * sets a newinfo.df_conflicts field specifically to propagate it).
1107 unsigned df_conflict = (filemask != 0) && (dirmask != 0);
1109 /* n = 3 is a fundamental assumption. */
1110 if (n != 3)
1111 BUG("Called collect_merge_info_callback wrong");
1114 * A bunch of sanity checks verifying that traverse_trees() calls
1115 * us the way I expect. Could just remove these at some point,
1116 * though maybe they are helpful to future code readers.
1118 assert(mbase_null == is_null_oid(&names[0].oid));
1119 assert(side1_null == is_null_oid(&names[1].oid));
1120 assert(side2_null == is_null_oid(&names[2].oid));
1121 assert(!mbase_null || !side1_null || !side2_null);
1122 assert(mask > 0 && mask < 8);
1124 /* Determine match_mask */
1125 if (side1_matches_mbase)
1126 match_mask = (side2_matches_mbase ? 7 : 3);
1127 else if (side2_matches_mbase)
1128 match_mask = 5;
1129 else if (sides_match)
1130 match_mask = 6;
1133 * Get the name of the relevant filepath, which we'll pass to
1134 * setup_path_info() for tracking.
1136 p = names;
1137 while (!p->mode)
1138 p++;
1139 len = traverse_path_len(info, p->pathlen);
1141 /* +1 in both of the following lines to include the NUL byte */
1142 fullpath = mem_pool_alloc(&opt->priv->pool, len + 1);
1143 make_traverse_path(fullpath, len + 1, info, p->path, p->pathlen);
1146 * If mbase, side1, and side2 all match, we can resolve early. Even
1147 * if these are trees, there will be no renames or anything
1148 * underneath.
1150 if (side1_matches_mbase && side2_matches_mbase) {
1151 /* mbase, side1, & side2 all match; use mbase as resolution */
1152 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1153 names, names+0, mbase_null, 0 /* df_conflict */,
1154 filemask, dirmask, 1 /* resolved */);
1155 return mask;
1159 * If the sides match, and all three paths are present and are
1160 * files, then we can take either as the resolution. We can't do
1161 * this with trees, because there may be rename sources from the
1162 * merge_base.
1164 if (sides_match && filemask == 0x07) {
1165 /* use side1 (== side2) version as resolution */
1166 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1167 names, names+1, side1_null, 0,
1168 filemask, dirmask, 1);
1169 return mask;
1173 * If side1 matches mbase and all three paths are present and are
1174 * files, then we can use side2 as the resolution. We cannot
1175 * necessarily do so this for trees, because there may be rename
1176 * destinations within side2.
1178 if (side1_matches_mbase && filemask == 0x07) {
1179 /* use side2 version as resolution */
1180 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1181 names, names+2, side2_null, 0,
1182 filemask, dirmask, 1);
1183 return mask;
1186 /* Similar to above but swapping sides 1 and 2 */
1187 if (side2_matches_mbase && filemask == 0x07) {
1188 /* use side1 version as resolution */
1189 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1190 names, names+1, side1_null, 0,
1191 filemask, dirmask, 1);
1192 return mask;
1196 * Sometimes we can tell that a source path need not be included in
1197 * rename detection -- namely, whenever either
1198 * side1_matches_mbase && side2_null
1199 * or
1200 * side2_matches_mbase && side1_null
1201 * However, we call collect_rename_info() even in those cases,
1202 * because exact renames are cheap and would let us remove both a
1203 * source and destination path. We'll cull the unneeded sources
1204 * later.
1206 collect_rename_info(opt, names, dirname, fullpath,
1207 filemask, dirmask, match_mask);
1210 * None of the special cases above matched, so we have a
1211 * provisional conflict. (Rename detection might allow us to
1212 * unconflict some more cases, but that comes later so all we can
1213 * do now is record the different non-null file hashes.)
1215 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1216 names, NULL, 0, df_conflict, filemask, dirmask, 0);
1218 ci = pi.util;
1219 VERIFY_CI(ci);
1220 ci->match_mask = match_mask;
1222 /* If dirmask, recurse into subdirectories */
1223 if (dirmask) {
1224 struct traverse_info newinfo;
1225 struct tree_desc t[3];
1226 void *buf[3] = {NULL, NULL, NULL};
1227 const char *original_dir_name;
1228 int i, ret, side;
1231 * Check for whether we can avoid recursing due to one side
1232 * matching the merge base. The side that does NOT match is
1233 * the one that might have a rename destination we need.
1235 assert(!side1_matches_mbase || !side2_matches_mbase);
1236 side = side1_matches_mbase ? MERGE_SIDE2 :
1237 side2_matches_mbase ? MERGE_SIDE1 : MERGE_BASE;
1238 if (filemask == 0 && (dirmask == 2 || dirmask == 4)) {
1240 * Also defer recursing into new directories; set up a
1241 * few variables to let us do so.
1243 ci->match_mask = (7 - dirmask);
1244 side = dirmask / 2;
1246 if (renames->dir_rename_mask != 0x07 &&
1247 side != MERGE_BASE &&
1248 renames->deferred[side].trivial_merges_okay &&
1249 !strset_contains(&renames->deferred[side].target_dirs,
1250 pi.string)) {
1251 strintmap_set(&renames->deferred[side].possible_trivial_merges,
1252 pi.string, renames->dir_rename_mask);
1253 renames->dir_rename_mask = prev_dir_rename_mask;
1254 return mask;
1257 /* We need to recurse */
1258 ci->match_mask &= filemask;
1259 newinfo = *info;
1260 newinfo.prev = info;
1261 newinfo.name = p->path;
1262 newinfo.namelen = p->pathlen;
1263 newinfo.pathlen = st_add3(newinfo.pathlen, p->pathlen, 1);
1265 * If this directory we are about to recurse into cared about
1266 * its parent directory (the current directory) having a D/F
1267 * conflict, then we'd propagate the masks in this way:
1268 * newinfo.df_conflicts |= (mask & ~dirmask);
1269 * But we don't worry about propagating D/F conflicts. (See
1270 * comment near setting of local df_conflict variable near
1271 * the beginning of this function).
1274 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1275 if (i == 1 && side1_matches_mbase)
1276 t[1] = t[0];
1277 else if (i == 2 && side2_matches_mbase)
1278 t[2] = t[0];
1279 else if (i == 2 && sides_match)
1280 t[2] = t[1];
1281 else {
1282 const struct object_id *oid = NULL;
1283 if (dirmask & 1)
1284 oid = &names[i].oid;
1285 buf[i] = fill_tree_descriptor(opt->repo,
1286 t + i, oid);
1288 dirmask >>= 1;
1291 original_dir_name = opti->current_dir_name;
1292 opti->current_dir_name = pi.string;
1293 if (renames->dir_rename_mask == 0 ||
1294 renames->dir_rename_mask == 0x07)
1295 ret = traverse_trees(NULL, 3, t, &newinfo);
1296 else
1297 ret = traverse_trees_wrapper(NULL, 3, t, &newinfo);
1298 opti->current_dir_name = original_dir_name;
1299 renames->dir_rename_mask = prev_dir_rename_mask;
1301 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
1302 free(buf[i]);
1304 if (ret < 0)
1305 return -1;
1308 return mask;
1311 static void resolve_trivial_directory_merge(struct conflict_info *ci, int side)
1313 VERIFY_CI(ci);
1314 assert((side == 1 && ci->match_mask == 5) ||
1315 (side == 2 && ci->match_mask == 3));
1316 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1317 ci->merged.result.mode = ci->stages[side].mode;
1318 ci->merged.is_null = is_null_oid(&ci->stages[side].oid);
1319 ci->match_mask = 0;
1320 ci->merged.clean = 1; /* (ci->filemask == 0); */
1323 static int handle_deferred_entries(struct merge_options *opt,
1324 struct traverse_info *info)
1326 struct rename_info *renames = &opt->priv->renames;
1327 struct hashmap_iter iter;
1328 struct strmap_entry *entry;
1329 int side, ret = 0;
1330 int path_count_before, path_count_after = 0;
1332 path_count_before = strmap_get_size(&opt->priv->paths);
1333 for (side = MERGE_SIDE1; side <= MERGE_SIDE2; side++) {
1334 unsigned optimization_okay = 1;
1335 struct strintmap copy;
1337 /* Loop over the set of paths we need to know rename info for */
1338 strset_for_each_entry(&renames->relevant_sources[side],
1339 &iter, entry) {
1340 char *rename_target, *dir, *dir_marker;
1341 struct strmap_entry *e;
1344 * If we don't know delete/rename info for this path,
1345 * then we need to recurse into all trees to get all
1346 * adds to make sure we have it.
1348 if (strset_contains(&renames->cached_irrelevant[side],
1349 entry->key))
1350 continue;
1351 e = strmap_get_entry(&renames->cached_pairs[side],
1352 entry->key);
1353 if (!e) {
1354 optimization_okay = 0;
1355 break;
1358 /* If this is a delete, we have enough info already */
1359 rename_target = e->value;
1360 if (!rename_target)
1361 continue;
1363 /* If we already walked the rename target, we're good */
1364 if (strmap_contains(&opt->priv->paths, rename_target))
1365 continue;
1368 * Otherwise, we need to get a list of directories that
1369 * will need to be recursed into to get this
1370 * rename_target.
1372 dir = xstrdup(rename_target);
1373 while ((dir_marker = strrchr(dir, '/'))) {
1374 *dir_marker = '\0';
1375 if (strset_contains(&renames->deferred[side].target_dirs,
1376 dir))
1377 break;
1378 strset_add(&renames->deferred[side].target_dirs,
1379 dir);
1381 free(dir);
1383 renames->deferred[side].trivial_merges_okay = optimization_okay;
1385 * We need to recurse into any directories in
1386 * possible_trivial_merges[side] found in target_dirs[side].
1387 * But when we recurse, we may need to queue up some of the
1388 * subdirectories for possible_trivial_merges[side]. Since
1389 * we can't safely iterate through a hashmap while also adding
1390 * entries, move the entries into 'copy', iterate over 'copy',
1391 * and then we'll also iterate anything added into
1392 * possible_trivial_merges[side] once this loop is done.
1394 copy = renames->deferred[side].possible_trivial_merges;
1395 strintmap_init_with_options(&renames->deferred[side].possible_trivial_merges,
1397 &opt->priv->pool,
1399 strintmap_for_each_entry(&copy, &iter, entry) {
1400 const char *path = entry->key;
1401 unsigned dir_rename_mask = (intptr_t)entry->value;
1402 struct conflict_info *ci;
1403 unsigned dirmask;
1404 struct tree_desc t[3];
1405 void *buf[3] = {NULL,};
1406 int i;
1408 ci = strmap_get(&opt->priv->paths, path);
1409 VERIFY_CI(ci);
1410 dirmask = ci->dirmask;
1412 if (optimization_okay &&
1413 !strset_contains(&renames->deferred[side].target_dirs,
1414 path)) {
1415 resolve_trivial_directory_merge(ci, side);
1416 continue;
1419 info->name = path;
1420 info->namelen = strlen(path);
1421 info->pathlen = info->namelen + 1;
1423 for (i = 0; i < 3; i++, dirmask >>= 1) {
1424 if (i == 1 && ci->match_mask == 3)
1425 t[1] = t[0];
1426 else if (i == 2 && ci->match_mask == 5)
1427 t[2] = t[0];
1428 else if (i == 2 && ci->match_mask == 6)
1429 t[2] = t[1];
1430 else {
1431 const struct object_id *oid = NULL;
1432 if (dirmask & 1)
1433 oid = &ci->stages[i].oid;
1434 buf[i] = fill_tree_descriptor(opt->repo,
1435 t+i, oid);
1439 ci->match_mask &= ci->filemask;
1440 opt->priv->current_dir_name = path;
1441 renames->dir_rename_mask = dir_rename_mask;
1442 if (renames->dir_rename_mask == 0 ||
1443 renames->dir_rename_mask == 0x07)
1444 ret = traverse_trees(NULL, 3, t, info);
1445 else
1446 ret = traverse_trees_wrapper(NULL, 3, t, info);
1448 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
1449 free(buf[i]);
1451 if (ret < 0)
1452 return ret;
1454 strintmap_clear(&copy);
1455 strintmap_for_each_entry(&renames->deferred[side].possible_trivial_merges,
1456 &iter, entry) {
1457 const char *path = entry->key;
1458 struct conflict_info *ci;
1460 ci = strmap_get(&opt->priv->paths, path);
1461 VERIFY_CI(ci);
1463 assert(renames->deferred[side].trivial_merges_okay &&
1464 !strset_contains(&renames->deferred[side].target_dirs,
1465 path));
1466 resolve_trivial_directory_merge(ci, side);
1468 if (!optimization_okay || path_count_after)
1469 path_count_after = strmap_get_size(&opt->priv->paths);
1471 if (path_count_after) {
1473 * The choice of wanted_factor here does not affect
1474 * correctness, only performance. When the
1475 * path_count_after / path_count_before
1476 * ratio is high, redoing after renames is a big
1477 * performance boost. I suspect that redoing is a wash
1478 * somewhere near a value of 2, and below that redoing will
1479 * slow things down. I applied a fudge factor and picked
1480 * 3; see the commit message when this was introduced for
1481 * back of the envelope calculations for this ratio.
1483 const int wanted_factor = 3;
1485 /* We should only redo collect_merge_info one time */
1486 assert(renames->redo_after_renames == 0);
1488 if (path_count_after / path_count_before >= wanted_factor) {
1489 renames->redo_after_renames = 1;
1490 renames->cached_pairs_valid_side = -1;
1492 } else if (renames->redo_after_renames == 2)
1493 renames->redo_after_renames = 0;
1494 return ret;
1497 static int collect_merge_info(struct merge_options *opt,
1498 struct tree *merge_base,
1499 struct tree *side1,
1500 struct tree *side2)
1502 int ret;
1503 struct tree_desc t[3];
1504 struct traverse_info info;
1506 opt->priv->toplevel_dir = "";
1507 opt->priv->current_dir_name = opt->priv->toplevel_dir;
1508 setup_traverse_info(&info, opt->priv->toplevel_dir);
1509 info.fn = collect_merge_info_callback;
1510 info.data = opt;
1511 info.show_all_errors = 1;
1513 parse_tree(merge_base);
1514 parse_tree(side1);
1515 parse_tree(side2);
1516 init_tree_desc(t + 0, merge_base->buffer, merge_base->size);
1517 init_tree_desc(t + 1, side1->buffer, side1->size);
1518 init_tree_desc(t + 2, side2->buffer, side2->size);
1520 trace2_region_enter("merge", "traverse_trees", opt->repo);
1521 ret = traverse_trees(NULL, 3, t, &info);
1522 if (ret == 0)
1523 ret = handle_deferred_entries(opt, &info);
1524 trace2_region_leave("merge", "traverse_trees", opt->repo);
1526 return ret;
1529 /*** Function Grouping: functions related to threeway content merges ***/
1531 static int find_first_merges(struct repository *repo,
1532 const char *path,
1533 struct commit *a,
1534 struct commit *b,
1535 struct object_array *result)
1537 int i, j;
1538 struct object_array merges = OBJECT_ARRAY_INIT;
1539 struct commit *commit;
1540 int contains_another;
1542 char merged_revision[GIT_MAX_HEXSZ + 2];
1543 const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1544 "--all", merged_revision, NULL };
1545 struct rev_info revs;
1546 struct setup_revision_opt rev_opts;
1548 memset(result, 0, sizeof(struct object_array));
1549 memset(&rev_opts, 0, sizeof(rev_opts));
1551 /* get all revisions that merge commit a */
1552 xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
1553 oid_to_hex(&a->object.oid));
1554 repo_init_revisions(repo, &revs, NULL);
1555 /* FIXME: can't handle linked worktrees in submodules yet */
1556 revs.single_worktree = path != NULL;
1557 setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1559 /* save all revisions from the above list that contain b */
1560 if (prepare_revision_walk(&revs))
1561 die("revision walk setup failed");
1562 while ((commit = get_revision(&revs)) != NULL) {
1563 struct object *o = &(commit->object);
1564 if (repo_in_merge_bases(repo, b, commit))
1565 add_object_array(o, NULL, &merges);
1567 reset_revision_walk();
1569 /* Now we've got all merges that contain a and b. Prune all
1570 * merges that contain another found merge and save them in
1571 * result.
1573 for (i = 0; i < merges.nr; i++) {
1574 struct commit *m1 = (struct commit *) merges.objects[i].item;
1576 contains_another = 0;
1577 for (j = 0; j < merges.nr; j++) {
1578 struct commit *m2 = (struct commit *) merges.objects[j].item;
1579 if (i != j && repo_in_merge_bases(repo, m2, m1)) {
1580 contains_another = 1;
1581 break;
1585 if (!contains_another)
1586 add_object_array(merges.objects[i].item, NULL, result);
1589 object_array_clear(&merges);
1590 return result->nr;
1593 static int merge_submodule(struct merge_options *opt,
1594 const char *path,
1595 const struct object_id *o,
1596 const struct object_id *a,
1597 const struct object_id *b,
1598 struct object_id *result)
1600 struct repository subrepo;
1601 struct strbuf sb = STRBUF_INIT;
1602 int ret = 0;
1603 struct commit *commit_o, *commit_a, *commit_b;
1604 int parent_count;
1605 struct object_array merges;
1607 int i;
1608 int search = !opt->priv->call_depth;
1610 /* store fallback answer in result in case we fail */
1611 oidcpy(result, opt->priv->call_depth ? o : a);
1613 /* we can not handle deletion conflicts */
1614 if (is_null_oid(o))
1615 return 0;
1616 if (is_null_oid(a))
1617 return 0;
1618 if (is_null_oid(b))
1619 return 0;
1621 if (repo_submodule_init(&subrepo, opt->repo, path, null_oid())) {
1622 path_msg(opt, path, 0,
1623 _("Failed to merge submodule %s (not checked out)"),
1624 path);
1625 return 0;
1628 if (!(commit_o = lookup_commit_reference(&subrepo, o)) ||
1629 !(commit_a = lookup_commit_reference(&subrepo, a)) ||
1630 !(commit_b = lookup_commit_reference(&subrepo, b))) {
1631 path_msg(opt, path, 0,
1632 _("Failed to merge submodule %s (commits not present)"),
1633 path);
1634 goto cleanup;
1637 /* check whether both changes are forward */
1638 if (!repo_in_merge_bases(&subrepo, commit_o, commit_a) ||
1639 !repo_in_merge_bases(&subrepo, commit_o, commit_b)) {
1640 path_msg(opt, path, 0,
1641 _("Failed to merge submodule %s "
1642 "(commits don't follow merge-base)"),
1643 path);
1644 goto cleanup;
1647 /* Case #1: a is contained in b or vice versa */
1648 if (repo_in_merge_bases(&subrepo, commit_a, commit_b)) {
1649 oidcpy(result, b);
1650 path_msg(opt, path, 1,
1651 _("Note: Fast-forwarding submodule %s to %s"),
1652 path, oid_to_hex(b));
1653 ret = 1;
1654 goto cleanup;
1656 if (repo_in_merge_bases(&subrepo, commit_b, commit_a)) {
1657 oidcpy(result, a);
1658 path_msg(opt, path, 1,
1659 _("Note: Fast-forwarding submodule %s to %s"),
1660 path, oid_to_hex(a));
1661 ret = 1;
1662 goto cleanup;
1666 * Case #2: There are one or more merges that contain a and b in
1667 * the submodule. If there is only one, then present it as a
1668 * suggestion to the user, but leave it marked unmerged so the
1669 * user needs to confirm the resolution.
1672 /* Skip the search if makes no sense to the calling context. */
1673 if (!search)
1674 goto cleanup;
1676 /* find commit which merges them */
1677 parent_count = find_first_merges(&subrepo, path, commit_a, commit_b,
1678 &merges);
1679 switch (parent_count) {
1680 case 0:
1681 path_msg(opt, path, 0, _("Failed to merge submodule %s"), path);
1682 break;
1684 case 1:
1685 format_commit(&sb, 4, &subrepo,
1686 (struct commit *)merges.objects[0].item);
1687 path_msg(opt, path, 0,
1688 _("Failed to merge submodule %s, but a possible merge "
1689 "resolution exists:\n%s\n"),
1690 path, sb.buf);
1691 path_msg(opt, path, 1,
1692 _("If this is correct simply add it to the index "
1693 "for example\n"
1694 "by using:\n\n"
1695 " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1696 "which will accept this suggestion.\n"),
1697 oid_to_hex(&merges.objects[0].item->oid), path);
1698 strbuf_release(&sb);
1699 break;
1700 default:
1701 for (i = 0; i < merges.nr; i++)
1702 format_commit(&sb, 4, &subrepo,
1703 (struct commit *)merges.objects[i].item);
1704 path_msg(opt, path, 0,
1705 _("Failed to merge submodule %s, but multiple "
1706 "possible merges exist:\n%s"), path, sb.buf);
1707 strbuf_release(&sb);
1710 object_array_clear(&merges);
1711 cleanup:
1712 repo_clear(&subrepo);
1713 return ret;
1716 static void initialize_attr_index(struct merge_options *opt)
1719 * The renormalize_buffer() functions require attributes, and
1720 * annoyingly those can only be read from the working tree or from
1721 * an index_state. merge-ort doesn't have an index_state, so we
1722 * generate a fake one containing only attribute information.
1724 struct merged_info *mi;
1725 struct index_state *attr_index = &opt->priv->attr_index;
1726 struct cache_entry *ce;
1728 attr_index->initialized = 1;
1730 if (!opt->renormalize)
1731 return;
1733 mi = strmap_get(&opt->priv->paths, GITATTRIBUTES_FILE);
1734 if (!mi)
1735 return;
1737 if (mi->clean) {
1738 int len = strlen(GITATTRIBUTES_FILE);
1739 ce = make_empty_cache_entry(attr_index, len);
1740 ce->ce_mode = create_ce_mode(mi->result.mode);
1741 ce->ce_flags = create_ce_flags(0);
1742 ce->ce_namelen = len;
1743 oidcpy(&ce->oid, &mi->result.oid);
1744 memcpy(ce->name, GITATTRIBUTES_FILE, len);
1745 add_index_entry(attr_index, ce,
1746 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
1747 get_stream_filter(attr_index, GITATTRIBUTES_FILE, &ce->oid);
1748 } else {
1749 int stage, len;
1750 struct conflict_info *ci;
1752 ASSIGN_AND_VERIFY_CI(ci, mi);
1753 for (stage = 0; stage < 3; stage++) {
1754 unsigned stage_mask = (1 << stage);
1756 if (!(ci->filemask & stage_mask))
1757 continue;
1758 len = strlen(GITATTRIBUTES_FILE);
1759 ce = make_empty_cache_entry(attr_index, len);
1760 ce->ce_mode = create_ce_mode(ci->stages[stage].mode);
1761 ce->ce_flags = create_ce_flags(stage);
1762 ce->ce_namelen = len;
1763 oidcpy(&ce->oid, &ci->stages[stage].oid);
1764 memcpy(ce->name, GITATTRIBUTES_FILE, len);
1765 add_index_entry(attr_index, ce,
1766 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
1767 get_stream_filter(attr_index, GITATTRIBUTES_FILE,
1768 &ce->oid);
1773 static int merge_3way(struct merge_options *opt,
1774 const char *path,
1775 const struct object_id *o,
1776 const struct object_id *a,
1777 const struct object_id *b,
1778 const char *pathnames[3],
1779 const int extra_marker_size,
1780 mmbuffer_t *result_buf)
1782 mmfile_t orig, src1, src2;
1783 struct ll_merge_options ll_opts = {0};
1784 char *base, *name1, *name2;
1785 enum ll_merge_result merge_status;
1787 if (!opt->priv->attr_index.initialized)
1788 initialize_attr_index(opt);
1790 ll_opts.renormalize = opt->renormalize;
1791 ll_opts.extra_marker_size = extra_marker_size;
1792 ll_opts.xdl_opts = opt->xdl_opts;
1794 if (opt->priv->call_depth) {
1795 ll_opts.virtual_ancestor = 1;
1796 ll_opts.variant = 0;
1797 } else {
1798 switch (opt->recursive_variant) {
1799 case MERGE_VARIANT_OURS:
1800 ll_opts.variant = XDL_MERGE_FAVOR_OURS;
1801 break;
1802 case MERGE_VARIANT_THEIRS:
1803 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
1804 break;
1805 default:
1806 ll_opts.variant = 0;
1807 break;
1811 assert(pathnames[0] && pathnames[1] && pathnames[2] && opt->ancestor);
1812 if (pathnames[0] == pathnames[1] && pathnames[1] == pathnames[2]) {
1813 base = mkpathdup("%s", opt->ancestor);
1814 name1 = mkpathdup("%s", opt->branch1);
1815 name2 = mkpathdup("%s", opt->branch2);
1816 } else {
1817 base = mkpathdup("%s:%s", opt->ancestor, pathnames[0]);
1818 name1 = mkpathdup("%s:%s", opt->branch1, pathnames[1]);
1819 name2 = mkpathdup("%s:%s", opt->branch2, pathnames[2]);
1822 read_mmblob(&orig, o);
1823 read_mmblob(&src1, a);
1824 read_mmblob(&src2, b);
1826 merge_status = ll_merge(result_buf, path, &orig, base,
1827 &src1, name1, &src2, name2,
1828 &opt->priv->attr_index, &ll_opts);
1829 if (merge_status == LL_MERGE_BINARY_CONFLICT)
1830 path_msg(opt, path, 0,
1831 "warning: Cannot merge binary files: %s (%s vs. %s)",
1832 path, name1, name2);
1834 free(base);
1835 free(name1);
1836 free(name2);
1837 free(orig.ptr);
1838 free(src1.ptr);
1839 free(src2.ptr);
1840 return merge_status;
1843 static int handle_content_merge(struct merge_options *opt,
1844 const char *path,
1845 const struct version_info *o,
1846 const struct version_info *a,
1847 const struct version_info *b,
1848 const char *pathnames[3],
1849 const int extra_marker_size,
1850 struct version_info *result)
1853 * path is the target location where we want to put the file, and
1854 * is used to determine any normalization rules in ll_merge.
1856 * The normal case is that path and all entries in pathnames are
1857 * identical, though renames can affect which path we got one of
1858 * the three blobs to merge on various sides of history.
1860 * extra_marker_size is the amount to extend conflict markers in
1861 * ll_merge; this is neeed if we have content merges of content
1862 * merges, which happens for example with rename/rename(2to1) and
1863 * rename/add conflicts.
1865 unsigned clean = 1;
1868 * handle_content_merge() needs both files to be of the same type, i.e.
1869 * both files OR both submodules OR both symlinks. Conflicting types
1870 * needs to be handled elsewhere.
1872 assert((S_IFMT & a->mode) == (S_IFMT & b->mode));
1874 /* Merge modes */
1875 if (a->mode == b->mode || a->mode == o->mode)
1876 result->mode = b->mode;
1877 else {
1878 /* must be the 100644/100755 case */
1879 assert(S_ISREG(a->mode));
1880 result->mode = a->mode;
1881 clean = (b->mode == o->mode);
1883 * FIXME: If opt->priv->call_depth && !clean, then we really
1884 * should not make result->mode match either a->mode or
1885 * b->mode; that causes t6036 "check conflicting mode for
1886 * regular file" to fail. It would be best to use some other
1887 * mode, but we'll confuse all kinds of stuff if we use one
1888 * where S_ISREG(result->mode) isn't true, and if we use
1889 * something like 0100666, then tree-walk.c's calls to
1890 * canon_mode() will just normalize that to 100644 for us and
1891 * thus not solve anything.
1893 * Figure out if there's some kind of way we can work around
1894 * this...
1899 * Trivial oid merge.
1901 * Note: While one might assume that the next four lines would
1902 * be unnecessary due to the fact that match_mask is often
1903 * setup and already handled, renames don't always take care
1904 * of that.
1906 if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
1907 oidcpy(&result->oid, &b->oid);
1908 else if (oideq(&b->oid, &o->oid))
1909 oidcpy(&result->oid, &a->oid);
1911 /* Remaining rules depend on file vs. submodule vs. symlink. */
1912 else if (S_ISREG(a->mode)) {
1913 mmbuffer_t result_buf;
1914 int ret = 0, merge_status;
1915 int two_way;
1918 * If 'o' is different type, treat it as null so we do a
1919 * two-way merge.
1921 two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
1923 merge_status = merge_3way(opt, path,
1924 two_way ? null_oid() : &o->oid,
1925 &a->oid, &b->oid,
1926 pathnames, extra_marker_size,
1927 &result_buf);
1929 if ((merge_status < 0) || !result_buf.ptr)
1930 ret = err(opt, _("Failed to execute internal merge"));
1932 if (!ret &&
1933 write_object_file(result_buf.ptr, result_buf.size,
1934 blob_type, &result->oid))
1935 ret = err(opt, _("Unable to add %s to database"),
1936 path);
1938 free(result_buf.ptr);
1939 if (ret)
1940 return -1;
1941 clean &= (merge_status == 0);
1942 path_msg(opt, path, 1, _("Auto-merging %s"), path);
1943 } else if (S_ISGITLINK(a->mode)) {
1944 int two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
1945 clean = merge_submodule(opt, pathnames[0],
1946 two_way ? null_oid() : &o->oid,
1947 &a->oid, &b->oid, &result->oid);
1948 if (opt->priv->call_depth && two_way && !clean) {
1949 result->mode = o->mode;
1950 oidcpy(&result->oid, &o->oid);
1952 } else if (S_ISLNK(a->mode)) {
1953 if (opt->priv->call_depth) {
1954 clean = 0;
1955 result->mode = o->mode;
1956 oidcpy(&result->oid, &o->oid);
1957 } else {
1958 switch (opt->recursive_variant) {
1959 case MERGE_VARIANT_NORMAL:
1960 clean = 0;
1961 oidcpy(&result->oid, &a->oid);
1962 break;
1963 case MERGE_VARIANT_OURS:
1964 oidcpy(&result->oid, &a->oid);
1965 break;
1966 case MERGE_VARIANT_THEIRS:
1967 oidcpy(&result->oid, &b->oid);
1968 break;
1971 } else
1972 BUG("unsupported object type in the tree: %06o for %s",
1973 a->mode, path);
1975 return clean;
1978 /*** Function Grouping: functions related to detect_and_process_renames(), ***
1979 *** which are split into directory and regular rename detection sections. ***/
1981 /*** Function Grouping: functions related to directory rename detection ***/
1983 struct collision_info {
1984 struct string_list source_files;
1985 unsigned reported_already:1;
1989 * Return a new string that replaces the beginning portion (which matches
1990 * rename_info->key), with rename_info->util.new_dir. In perl-speak:
1991 * new_path_name = (old_path =~ s/rename_info->key/rename_info->value/);
1992 * NOTE:
1993 * Caller must ensure that old_path starts with rename_info->key + '/'.
1995 static char *apply_dir_rename(struct strmap_entry *rename_info,
1996 const char *old_path)
1998 struct strbuf new_path = STRBUF_INIT;
1999 const char *old_dir = rename_info->key;
2000 const char *new_dir = rename_info->value;
2001 int oldlen, newlen, new_dir_len;
2003 oldlen = strlen(old_dir);
2004 if (*new_dir == '\0')
2006 * If someone renamed/merged a subdirectory into the root
2007 * directory (e.g. 'some/subdir' -> ''), then we want to
2008 * avoid returning
2009 * '' + '/filename'
2010 * as the rename; we need to make old_path + oldlen advance
2011 * past the '/' character.
2013 oldlen++;
2014 new_dir_len = strlen(new_dir);
2015 newlen = new_dir_len + (strlen(old_path) - oldlen) + 1;
2016 strbuf_grow(&new_path, newlen);
2017 strbuf_add(&new_path, new_dir, new_dir_len);
2018 strbuf_addstr(&new_path, &old_path[oldlen]);
2020 return strbuf_detach(&new_path, NULL);
2023 static int path_in_way(struct strmap *paths, const char *path, unsigned side_mask)
2025 struct merged_info *mi = strmap_get(paths, path);
2026 struct conflict_info *ci;
2027 if (!mi)
2028 return 0;
2029 INITIALIZE_CI(ci, mi);
2030 return mi->clean || (side_mask & (ci->filemask | ci->dirmask));
2034 * See if there is a directory rename for path, and if there are any file
2035 * level conflicts on the given side for the renamed location. If there is
2036 * a rename and there are no conflicts, return the new name. Otherwise,
2037 * return NULL.
2039 static char *handle_path_level_conflicts(struct merge_options *opt,
2040 const char *path,
2041 unsigned side_index,
2042 struct strmap_entry *rename_info,
2043 struct strmap *collisions)
2045 char *new_path = NULL;
2046 struct collision_info *c_info;
2047 int clean = 1;
2048 struct strbuf collision_paths = STRBUF_INIT;
2051 * entry has the mapping of old directory name to new directory name
2052 * that we want to apply to path.
2054 new_path = apply_dir_rename(rename_info, path);
2055 if (!new_path)
2056 BUG("Failed to apply directory rename!");
2059 * The caller needs to have ensured that it has pre-populated
2060 * collisions with all paths that map to new_path. Do a quick check
2061 * to ensure that's the case.
2063 c_info = strmap_get(collisions, new_path);
2064 if (c_info == NULL)
2065 BUG("c_info is NULL");
2068 * Check for one-sided add/add/.../add conflicts, i.e.
2069 * where implicit renames from the other side doing
2070 * directory rename(s) can affect this side of history
2071 * to put multiple paths into the same location. Warn
2072 * and bail on directory renames for such paths.
2074 if (c_info->reported_already) {
2075 clean = 0;
2076 } else if (path_in_way(&opt->priv->paths, new_path, 1 << side_index)) {
2077 c_info->reported_already = 1;
2078 strbuf_add_separated_string_list(&collision_paths, ", ",
2079 &c_info->source_files);
2080 path_msg(opt, new_path, 0,
2081 _("CONFLICT (implicit dir rename): Existing file/dir "
2082 "at %s in the way of implicit directory rename(s) "
2083 "putting the following path(s) there: %s."),
2084 new_path, collision_paths.buf);
2085 clean = 0;
2086 } else if (c_info->source_files.nr > 1) {
2087 c_info->reported_already = 1;
2088 strbuf_add_separated_string_list(&collision_paths, ", ",
2089 &c_info->source_files);
2090 path_msg(opt, new_path, 0,
2091 _("CONFLICT (implicit dir rename): Cannot map more "
2092 "than one path to %s; implicit directory renames "
2093 "tried to put these paths there: %s"),
2094 new_path, collision_paths.buf);
2095 clean = 0;
2098 /* Free memory we no longer need */
2099 strbuf_release(&collision_paths);
2100 if (!clean && new_path) {
2101 free(new_path);
2102 return NULL;
2105 return new_path;
2108 static void get_provisional_directory_renames(struct merge_options *opt,
2109 unsigned side,
2110 int *clean)
2112 struct hashmap_iter iter;
2113 struct strmap_entry *entry;
2114 struct rename_info *renames = &opt->priv->renames;
2117 * Collapse
2118 * dir_rename_count: old_directory -> {new_directory -> count}
2119 * down to
2120 * dir_renames: old_directory -> best_new_directory
2121 * where best_new_directory is the one with the unique highest count.
2123 strmap_for_each_entry(&renames->dir_rename_count[side], &iter, entry) {
2124 const char *source_dir = entry->key;
2125 struct strintmap *counts = entry->value;
2126 struct hashmap_iter count_iter;
2127 struct strmap_entry *count_entry;
2128 int max = 0;
2129 int bad_max = 0;
2130 const char *best = NULL;
2132 strintmap_for_each_entry(counts, &count_iter, count_entry) {
2133 const char *target_dir = count_entry->key;
2134 intptr_t count = (intptr_t)count_entry->value;
2136 if (count == max)
2137 bad_max = max;
2138 else if (count > max) {
2139 max = count;
2140 best = target_dir;
2144 if (max == 0)
2145 continue;
2147 if (bad_max == max) {
2148 path_msg(opt, source_dir, 0,
2149 _("CONFLICT (directory rename split): "
2150 "Unclear where to rename %s to; it was "
2151 "renamed to multiple other directories, with "
2152 "no destination getting a majority of the "
2153 "files."),
2154 source_dir);
2155 *clean = 0;
2156 } else {
2157 strmap_put(&renames->dir_renames[side],
2158 source_dir, (void*)best);
2163 static void handle_directory_level_conflicts(struct merge_options *opt)
2165 struct hashmap_iter iter;
2166 struct strmap_entry *entry;
2167 struct string_list duplicated = STRING_LIST_INIT_NODUP;
2168 struct rename_info *renames = &opt->priv->renames;
2169 struct strmap *side1_dir_renames = &renames->dir_renames[MERGE_SIDE1];
2170 struct strmap *side2_dir_renames = &renames->dir_renames[MERGE_SIDE2];
2171 int i;
2173 strmap_for_each_entry(side1_dir_renames, &iter, entry) {
2174 if (strmap_contains(side2_dir_renames, entry->key))
2175 string_list_append(&duplicated, entry->key);
2178 for (i = 0; i < duplicated.nr; i++) {
2179 strmap_remove(side1_dir_renames, duplicated.items[i].string, 0);
2180 strmap_remove(side2_dir_renames, duplicated.items[i].string, 0);
2182 string_list_clear(&duplicated, 0);
2185 static struct strmap_entry *check_dir_renamed(const char *path,
2186 struct strmap *dir_renames)
2188 char *temp = xstrdup(path);
2189 char *end;
2190 struct strmap_entry *e = NULL;
2192 while ((end = strrchr(temp, '/'))) {
2193 *end = '\0';
2194 e = strmap_get_entry(dir_renames, temp);
2195 if (e)
2196 break;
2198 free(temp);
2199 return e;
2202 static void compute_collisions(struct strmap *collisions,
2203 struct strmap *dir_renames,
2204 struct diff_queue_struct *pairs)
2206 int i;
2208 strmap_init_with_options(collisions, NULL, 0);
2209 if (strmap_empty(dir_renames))
2210 return;
2213 * Multiple files can be mapped to the same path due to directory
2214 * renames done by the other side of history. Since that other
2215 * side of history could have merged multiple directories into one,
2216 * if our side of history added the same file basename to each of
2217 * those directories, then all N of them would get implicitly
2218 * renamed by the directory rename detection into the same path,
2219 * and we'd get an add/add/.../add conflict, and all those adds
2220 * from *this* side of history. This is not representable in the
2221 * index, and users aren't going to easily be able to make sense of
2222 * it. So we need to provide a good warning about what's
2223 * happening, and fall back to no-directory-rename detection
2224 * behavior for those paths.
2226 * See testcases 9e and all of section 5 from t6043 for examples.
2228 for (i = 0; i < pairs->nr; ++i) {
2229 struct strmap_entry *rename_info;
2230 struct collision_info *collision_info;
2231 char *new_path;
2232 struct diff_filepair *pair = pairs->queue[i];
2234 if (pair->status != 'A' && pair->status != 'R')
2235 continue;
2236 rename_info = check_dir_renamed(pair->two->path, dir_renames);
2237 if (!rename_info)
2238 continue;
2240 new_path = apply_dir_rename(rename_info, pair->two->path);
2241 assert(new_path);
2242 collision_info = strmap_get(collisions, new_path);
2243 if (collision_info) {
2244 free(new_path);
2245 } else {
2246 CALLOC_ARRAY(collision_info, 1);
2247 string_list_init_nodup(&collision_info->source_files);
2248 strmap_put(collisions, new_path, collision_info);
2250 string_list_insert(&collision_info->source_files,
2251 pair->two->path);
2255 static char *check_for_directory_rename(struct merge_options *opt,
2256 const char *path,
2257 unsigned side_index,
2258 struct strmap *dir_renames,
2259 struct strmap *dir_rename_exclusions,
2260 struct strmap *collisions,
2261 int *clean_merge)
2263 char *new_path = NULL;
2264 struct strmap_entry *rename_info;
2265 struct strmap_entry *otherinfo = NULL;
2266 const char *new_dir;
2268 if (strmap_empty(dir_renames))
2269 return new_path;
2270 rename_info = check_dir_renamed(path, dir_renames);
2271 if (!rename_info)
2272 return new_path;
2273 /* old_dir = rename_info->key; */
2274 new_dir = rename_info->value;
2277 * This next part is a little weird. We do not want to do an
2278 * implicit rename into a directory we renamed on our side, because
2279 * that will result in a spurious rename/rename(1to2) conflict. An
2280 * example:
2281 * Base commit: dumbdir/afile, otherdir/bfile
2282 * Side 1: smrtdir/afile, otherdir/bfile
2283 * Side 2: dumbdir/afile, dumbdir/bfile
2284 * Here, while working on Side 1, we could notice that otherdir was
2285 * renamed/merged to dumbdir, and change the diff_filepair for
2286 * otherdir/bfile into a rename into dumbdir/bfile. However, Side
2287 * 2 will notice the rename from dumbdir to smrtdir, and do the
2288 * transitive rename to move it from dumbdir/bfile to
2289 * smrtdir/bfile. That gives us bfile in dumbdir vs being in
2290 * smrtdir, a rename/rename(1to2) conflict. We really just want
2291 * the file to end up in smrtdir. And the way to achieve that is
2292 * to not let Side1 do the rename to dumbdir, since we know that is
2293 * the source of one of our directory renames.
2295 * That's why otherinfo and dir_rename_exclusions is here.
2297 * As it turns out, this also prevents N-way transient rename
2298 * confusion; See testcases 9c and 9d of t6043.
2300 otherinfo = strmap_get_entry(dir_rename_exclusions, new_dir);
2301 if (otherinfo) {
2302 path_msg(opt, rename_info->key, 1,
2303 _("WARNING: Avoiding applying %s -> %s rename "
2304 "to %s, because %s itself was renamed."),
2305 rename_info->key, new_dir, path, new_dir);
2306 return NULL;
2309 new_path = handle_path_level_conflicts(opt, path, side_index,
2310 rename_info, collisions);
2311 *clean_merge &= (new_path != NULL);
2313 return new_path;
2316 static void apply_directory_rename_modifications(struct merge_options *opt,
2317 struct diff_filepair *pair,
2318 char *new_path)
2321 * The basic idea is to get the conflict_info from opt->priv->paths
2322 * at old path, and insert it into new_path; basically just this:
2323 * ci = strmap_get(&opt->priv->paths, old_path);
2324 * strmap_remove(&opt->priv->paths, old_path, 0);
2325 * strmap_put(&opt->priv->paths, new_path, ci);
2326 * However, there are some factors complicating this:
2327 * - opt->priv->paths may already have an entry at new_path
2328 * - Each ci tracks its containing directory, so we need to
2329 * update that
2330 * - If another ci has the same containing directory, then
2331 * the two char*'s MUST point to the same location. See the
2332 * comment in struct merged_info. strcmp equality is not
2333 * enough; we need pointer equality.
2334 * - opt->priv->paths must hold the parent directories of any
2335 * entries that are added. So, if this directory rename
2336 * causes entirely new directories, we must recursively add
2337 * parent directories.
2338 * - For each parent directory added to opt->priv->paths, we
2339 * also need to get its parent directory stored in its
2340 * conflict_info->merged.directory_name with all the same
2341 * requirements about pointer equality.
2343 struct string_list dirs_to_insert = STRING_LIST_INIT_NODUP;
2344 struct conflict_info *ci, *new_ci;
2345 struct strmap_entry *entry;
2346 const char *branch_with_new_path, *branch_with_dir_rename;
2347 const char *old_path = pair->two->path;
2348 const char *parent_name;
2349 const char *cur_path;
2350 int i, len;
2352 entry = strmap_get_entry(&opt->priv->paths, old_path);
2353 old_path = entry->key;
2354 ci = entry->value;
2355 VERIFY_CI(ci);
2357 /* Find parent directories missing from opt->priv->paths */
2358 cur_path = mem_pool_strdup(&opt->priv->pool, new_path);
2359 free((char*)new_path);
2360 new_path = (char *)cur_path;
2362 while (1) {
2363 /* Find the parent directory of cur_path */
2364 char *last_slash = strrchr(cur_path, '/');
2365 if (last_slash) {
2366 parent_name = mem_pool_strndup(&opt->priv->pool,
2367 cur_path,
2368 last_slash - cur_path);
2369 } else {
2370 parent_name = opt->priv->toplevel_dir;
2371 break;
2374 /* Look it up in opt->priv->paths */
2375 entry = strmap_get_entry(&opt->priv->paths, parent_name);
2376 if (entry) {
2377 parent_name = entry->key; /* reuse known pointer */
2378 break;
2381 /* Record this is one of the directories we need to insert */
2382 string_list_append(&dirs_to_insert, parent_name);
2383 cur_path = parent_name;
2386 /* Traverse dirs_to_insert and insert them into opt->priv->paths */
2387 for (i = dirs_to_insert.nr-1; i >= 0; --i) {
2388 struct conflict_info *dir_ci;
2389 char *cur_dir = dirs_to_insert.items[i].string;
2391 CALLOC_ARRAY(dir_ci, 1);
2393 dir_ci->merged.directory_name = parent_name;
2394 len = strlen(parent_name);
2395 /* len+1 because of trailing '/' character */
2396 dir_ci->merged.basename_offset = (len > 0 ? len+1 : len);
2397 dir_ci->dirmask = ci->filemask;
2398 strmap_put(&opt->priv->paths, cur_dir, dir_ci);
2400 parent_name = cur_dir;
2403 assert(ci->filemask == 2 || ci->filemask == 4);
2404 assert(ci->dirmask == 0);
2405 strmap_remove(&opt->priv->paths, old_path, 0);
2407 branch_with_new_path = (ci->filemask == 2) ? opt->branch1 : opt->branch2;
2408 branch_with_dir_rename = (ci->filemask == 2) ? opt->branch2 : opt->branch1;
2410 /* Now, finally update ci and stick it into opt->priv->paths */
2411 ci->merged.directory_name = parent_name;
2412 len = strlen(parent_name);
2413 ci->merged.basename_offset = (len > 0 ? len+1 : len);
2414 new_ci = strmap_get(&opt->priv->paths, new_path);
2415 if (!new_ci) {
2416 /* Place ci back into opt->priv->paths, but at new_path */
2417 strmap_put(&opt->priv->paths, new_path, ci);
2418 } else {
2419 int index;
2421 /* A few sanity checks */
2422 VERIFY_CI(new_ci);
2423 assert(ci->filemask == 2 || ci->filemask == 4);
2424 assert((new_ci->filemask & ci->filemask) == 0);
2425 assert(!new_ci->merged.clean);
2427 /* Copy stuff from ci into new_ci */
2428 new_ci->filemask |= ci->filemask;
2429 if (new_ci->dirmask)
2430 new_ci->df_conflict = 1;
2431 index = (ci->filemask >> 1);
2432 new_ci->pathnames[index] = ci->pathnames[index];
2433 new_ci->stages[index].mode = ci->stages[index].mode;
2434 oidcpy(&new_ci->stages[index].oid, &ci->stages[index].oid);
2436 ci = new_ci;
2439 if (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE) {
2440 /* Notify user of updated path */
2441 if (pair->status == 'A')
2442 path_msg(opt, new_path, 1,
2443 _("Path updated: %s added in %s inside a "
2444 "directory that was renamed in %s; moving "
2445 "it to %s."),
2446 old_path, branch_with_new_path,
2447 branch_with_dir_rename, new_path);
2448 else
2449 path_msg(opt, new_path, 1,
2450 _("Path updated: %s renamed to %s in %s, "
2451 "inside a directory that was renamed in %s; "
2452 "moving it to %s."),
2453 pair->one->path, old_path, branch_with_new_path,
2454 branch_with_dir_rename, new_path);
2455 } else {
2457 * opt->detect_directory_renames has the value
2458 * MERGE_DIRECTORY_RENAMES_CONFLICT, so mark these as conflicts.
2460 ci->path_conflict = 1;
2461 if (pair->status == 'A')
2462 path_msg(opt, new_path, 1,
2463 _("CONFLICT (file location): %s added in %s "
2464 "inside a directory that was renamed in %s, "
2465 "suggesting it should perhaps be moved to "
2466 "%s."),
2467 old_path, branch_with_new_path,
2468 branch_with_dir_rename, new_path);
2469 else
2470 path_msg(opt, new_path, 1,
2471 _("CONFLICT (file location): %s renamed to %s "
2472 "in %s, inside a directory that was renamed "
2473 "in %s, suggesting it should perhaps be "
2474 "moved to %s."),
2475 pair->one->path, old_path, branch_with_new_path,
2476 branch_with_dir_rename, new_path);
2480 * Finally, record the new location.
2482 pair->two->path = new_path;
2485 /*** Function Grouping: functions related to regular rename detection ***/
2487 static int process_renames(struct merge_options *opt,
2488 struct diff_queue_struct *renames)
2490 int clean_merge = 1, i;
2492 for (i = 0; i < renames->nr; ++i) {
2493 const char *oldpath = NULL, *newpath;
2494 struct diff_filepair *pair = renames->queue[i];
2495 struct conflict_info *oldinfo = NULL, *newinfo = NULL;
2496 struct strmap_entry *old_ent, *new_ent;
2497 unsigned int old_sidemask;
2498 int target_index, other_source_index;
2499 int source_deleted, collision, type_changed;
2500 const char *rename_branch = NULL, *delete_branch = NULL;
2502 old_ent = strmap_get_entry(&opt->priv->paths, pair->one->path);
2503 new_ent = strmap_get_entry(&opt->priv->paths, pair->two->path);
2504 if (old_ent) {
2505 oldpath = old_ent->key;
2506 oldinfo = old_ent->value;
2508 newpath = pair->two->path;
2509 if (new_ent) {
2510 newpath = new_ent->key;
2511 newinfo = new_ent->value;
2515 * If pair->one->path isn't in opt->priv->paths, that means
2516 * that either directory rename detection removed that
2517 * path, or a parent directory of oldpath was resolved and
2518 * we don't even need the rename; in either case, we can
2519 * skip it. If oldinfo->merged.clean, then the other side
2520 * of history had no changes to oldpath and we don't need
2521 * the rename and can skip it.
2523 if (!oldinfo || oldinfo->merged.clean)
2524 continue;
2527 * diff_filepairs have copies of pathnames, thus we have to
2528 * use standard 'strcmp()' (negated) instead of '=='.
2530 if (i + 1 < renames->nr &&
2531 !strcmp(oldpath, renames->queue[i+1]->one->path)) {
2532 /* Handle rename/rename(1to2) or rename/rename(1to1) */
2533 const char *pathnames[3];
2534 struct version_info merged;
2535 struct conflict_info *base, *side1, *side2;
2536 unsigned was_binary_blob = 0;
2538 pathnames[0] = oldpath;
2539 pathnames[1] = newpath;
2540 pathnames[2] = renames->queue[i+1]->two->path;
2542 base = strmap_get(&opt->priv->paths, pathnames[0]);
2543 side1 = strmap_get(&opt->priv->paths, pathnames[1]);
2544 side2 = strmap_get(&opt->priv->paths, pathnames[2]);
2546 VERIFY_CI(base);
2547 VERIFY_CI(side1);
2548 VERIFY_CI(side2);
2550 if (!strcmp(pathnames[1], pathnames[2])) {
2551 struct rename_info *ri = &opt->priv->renames;
2552 int j;
2554 /* Both sides renamed the same way */
2555 assert(side1 == side2);
2556 memcpy(&side1->stages[0], &base->stages[0],
2557 sizeof(merged));
2558 side1->filemask |= (1 << MERGE_BASE);
2559 /* Mark base as resolved by removal */
2560 base->merged.is_null = 1;
2561 base->merged.clean = 1;
2564 * Disable remembering renames optimization;
2565 * rename/rename(1to1) is incredibly rare, and
2566 * just disabling the optimization is easier
2567 * than purging cached_pairs,
2568 * cached_target_names, and dir_rename_counts.
2570 for (j = 0; j < 3; j++)
2571 ri->merge_trees[j] = NULL;
2573 /* We handled both renames, i.e. i+1 handled */
2574 i++;
2575 /* Move to next rename */
2576 continue;
2579 /* This is a rename/rename(1to2) */
2580 clean_merge = handle_content_merge(opt,
2581 pair->one->path,
2582 &base->stages[0],
2583 &side1->stages[1],
2584 &side2->stages[2],
2585 pathnames,
2586 1 + 2 * opt->priv->call_depth,
2587 &merged);
2588 if (!clean_merge &&
2589 merged.mode == side1->stages[1].mode &&
2590 oideq(&merged.oid, &side1->stages[1].oid))
2591 was_binary_blob = 1;
2592 memcpy(&side1->stages[1], &merged, sizeof(merged));
2593 if (was_binary_blob) {
2595 * Getting here means we were attempting to
2596 * merge a binary blob.
2598 * Since we can't merge binaries,
2599 * handle_content_merge() just takes one
2600 * side. But we don't want to copy the
2601 * contents of one side to both paths. We
2602 * used the contents of side1 above for
2603 * side1->stages, let's use the contents of
2604 * side2 for side2->stages below.
2606 oidcpy(&merged.oid, &side2->stages[2].oid);
2607 merged.mode = side2->stages[2].mode;
2609 memcpy(&side2->stages[2], &merged, sizeof(merged));
2611 side1->path_conflict = 1;
2612 side2->path_conflict = 1;
2614 * TODO: For renames we normally remove the path at the
2615 * old name. It would thus seem consistent to do the
2616 * same for rename/rename(1to2) cases, but we haven't
2617 * done so traditionally and a number of the regression
2618 * tests now encode an expectation that the file is
2619 * left there at stage 1. If we ever decide to change
2620 * this, add the following two lines here:
2621 * base->merged.is_null = 1;
2622 * base->merged.clean = 1;
2623 * and remove the setting of base->path_conflict to 1.
2625 base->path_conflict = 1;
2626 path_msg(opt, oldpath, 0,
2627 _("CONFLICT (rename/rename): %s renamed to "
2628 "%s in %s and to %s in %s."),
2629 pathnames[0],
2630 pathnames[1], opt->branch1,
2631 pathnames[2], opt->branch2);
2633 i++; /* We handled both renames, i.e. i+1 handled */
2634 continue;
2637 VERIFY_CI(oldinfo);
2638 VERIFY_CI(newinfo);
2639 target_index = pair->score; /* from collect_renames() */
2640 assert(target_index == 1 || target_index == 2);
2641 other_source_index = 3 - target_index;
2642 old_sidemask = (1 << other_source_index); /* 2 or 4 */
2643 source_deleted = (oldinfo->filemask == 1);
2644 collision = ((newinfo->filemask & old_sidemask) != 0);
2645 type_changed = !source_deleted &&
2646 (S_ISREG(oldinfo->stages[other_source_index].mode) !=
2647 S_ISREG(newinfo->stages[target_index].mode));
2648 if (type_changed && collision) {
2650 * special handling so later blocks can handle this...
2652 * if type_changed && collision are both true, then this
2653 * was really a double rename, but one side wasn't
2654 * detected due to lack of break detection. I.e.
2655 * something like
2656 * orig: has normal file 'foo'
2657 * side1: renames 'foo' to 'bar', adds 'foo' symlink
2658 * side2: renames 'foo' to 'bar'
2659 * In this case, the foo->bar rename on side1 won't be
2660 * detected because the new symlink named 'foo' is
2661 * there and we don't do break detection. But we detect
2662 * this here because we don't want to merge the content
2663 * of the foo symlink with the foo->bar file, so we
2664 * have some logic to handle this special case. The
2665 * easiest way to do that is make 'bar' on side1 not
2666 * be considered a colliding file but the other part
2667 * of a normal rename. If the file is very different,
2668 * well we're going to get content merge conflicts
2669 * anyway so it doesn't hurt. And if the colliding
2670 * file also has a different type, that'll be handled
2671 * by the content merge logic in process_entry() too.
2673 * See also t6430, 'rename vs. rename/symlink'
2675 collision = 0;
2677 if (source_deleted) {
2678 if (target_index == 1) {
2679 rename_branch = opt->branch1;
2680 delete_branch = opt->branch2;
2681 } else {
2682 rename_branch = opt->branch2;
2683 delete_branch = opt->branch1;
2687 assert(source_deleted || oldinfo->filemask & old_sidemask);
2689 /* Need to check for special types of rename conflicts... */
2690 if (collision && !source_deleted) {
2691 /* collision: rename/add or rename/rename(2to1) */
2692 const char *pathnames[3];
2693 struct version_info merged;
2695 struct conflict_info *base, *side1, *side2;
2696 unsigned clean;
2698 pathnames[0] = oldpath;
2699 pathnames[other_source_index] = oldpath;
2700 pathnames[target_index] = newpath;
2702 base = strmap_get(&opt->priv->paths, pathnames[0]);
2703 side1 = strmap_get(&opt->priv->paths, pathnames[1]);
2704 side2 = strmap_get(&opt->priv->paths, pathnames[2]);
2706 VERIFY_CI(base);
2707 VERIFY_CI(side1);
2708 VERIFY_CI(side2);
2710 clean = handle_content_merge(opt, pair->one->path,
2711 &base->stages[0],
2712 &side1->stages[1],
2713 &side2->stages[2],
2714 pathnames,
2715 1 + 2 * opt->priv->call_depth,
2716 &merged);
2718 memcpy(&newinfo->stages[target_index], &merged,
2719 sizeof(merged));
2720 if (!clean) {
2721 path_msg(opt, newpath, 0,
2722 _("CONFLICT (rename involved in "
2723 "collision): rename of %s -> %s has "
2724 "content conflicts AND collides "
2725 "with another path; this may result "
2726 "in nested conflict markers."),
2727 oldpath, newpath);
2729 } else if (collision && source_deleted) {
2731 * rename/add/delete or rename/rename(2to1)/delete:
2732 * since oldpath was deleted on the side that didn't
2733 * do the rename, there's not much of a content merge
2734 * we can do for the rename. oldinfo->merged.is_null
2735 * was already set, so we just leave things as-is so
2736 * they look like an add/add conflict.
2739 newinfo->path_conflict = 1;
2740 path_msg(opt, newpath, 0,
2741 _("CONFLICT (rename/delete): %s renamed "
2742 "to %s in %s, but deleted in %s."),
2743 oldpath, newpath, rename_branch, delete_branch);
2744 } else {
2746 * a few different cases...start by copying the
2747 * existing stage(s) from oldinfo over the newinfo
2748 * and update the pathname(s).
2750 memcpy(&newinfo->stages[0], &oldinfo->stages[0],
2751 sizeof(newinfo->stages[0]));
2752 newinfo->filemask |= (1 << MERGE_BASE);
2753 newinfo->pathnames[0] = oldpath;
2754 if (type_changed) {
2755 /* rename vs. typechange */
2756 /* Mark the original as resolved by removal */
2757 memcpy(&oldinfo->stages[0].oid, null_oid(),
2758 sizeof(oldinfo->stages[0].oid));
2759 oldinfo->stages[0].mode = 0;
2760 oldinfo->filemask &= 0x06;
2761 } else if (source_deleted) {
2762 /* rename/delete */
2763 newinfo->path_conflict = 1;
2764 path_msg(opt, newpath, 0,
2765 _("CONFLICT (rename/delete): %s renamed"
2766 " to %s in %s, but deleted in %s."),
2767 oldpath, newpath,
2768 rename_branch, delete_branch);
2769 } else {
2770 /* normal rename */
2771 memcpy(&newinfo->stages[other_source_index],
2772 &oldinfo->stages[other_source_index],
2773 sizeof(newinfo->stages[0]));
2774 newinfo->filemask |= (1 << other_source_index);
2775 newinfo->pathnames[other_source_index] = oldpath;
2779 if (!type_changed) {
2780 /* Mark the original as resolved by removal */
2781 oldinfo->merged.is_null = 1;
2782 oldinfo->merged.clean = 1;
2787 return clean_merge;
2790 static inline int possible_side_renames(struct rename_info *renames,
2791 unsigned side_index)
2793 return renames->pairs[side_index].nr > 0 &&
2794 !strintmap_empty(&renames->relevant_sources[side_index]);
2797 static inline int possible_renames(struct rename_info *renames)
2799 return possible_side_renames(renames, 1) ||
2800 possible_side_renames(renames, 2) ||
2801 !strmap_empty(&renames->cached_pairs[1]) ||
2802 !strmap_empty(&renames->cached_pairs[2]);
2805 static void resolve_diffpair_statuses(struct diff_queue_struct *q)
2808 * A simplified version of diff_resolve_rename_copy(); would probably
2809 * just use that function but it's static...
2811 int i;
2812 struct diff_filepair *p;
2814 for (i = 0; i < q->nr; ++i) {
2815 p = q->queue[i];
2816 p->status = 0; /* undecided */
2817 if (!DIFF_FILE_VALID(p->one))
2818 p->status = DIFF_STATUS_ADDED;
2819 else if (!DIFF_FILE_VALID(p->two))
2820 p->status = DIFF_STATUS_DELETED;
2821 else if (DIFF_PAIR_RENAME(p))
2822 p->status = DIFF_STATUS_RENAMED;
2826 static void prune_cached_from_relevant(struct rename_info *renames,
2827 unsigned side)
2829 /* Reason for this function described in add_pair() */
2830 struct hashmap_iter iter;
2831 struct strmap_entry *entry;
2833 /* Remove from relevant_sources all entries in cached_pairs[side] */
2834 strmap_for_each_entry(&renames->cached_pairs[side], &iter, entry) {
2835 strintmap_remove(&renames->relevant_sources[side],
2836 entry->key);
2838 /* Remove from relevant_sources all entries in cached_irrelevant[side] */
2839 strset_for_each_entry(&renames->cached_irrelevant[side], &iter, entry) {
2840 strintmap_remove(&renames->relevant_sources[side],
2841 entry->key);
2845 static void use_cached_pairs(struct merge_options *opt,
2846 struct strmap *cached_pairs,
2847 struct diff_queue_struct *pairs)
2849 struct hashmap_iter iter;
2850 struct strmap_entry *entry;
2853 * Add to side_pairs all entries from renames->cached_pairs[side_index].
2854 * (Info in cached_irrelevant[side_index] is not relevant here.)
2856 strmap_for_each_entry(cached_pairs, &iter, entry) {
2857 struct diff_filespec *one, *two;
2858 const char *old_name = entry->key;
2859 const char *new_name = entry->value;
2860 if (!new_name)
2861 new_name = old_name;
2864 * cached_pairs has *copies* of old_name and new_name,
2865 * because it has to persist across merges. Since
2866 * pool_alloc_filespec() will just re-use the existing
2867 * filenames, which will also get re-used by
2868 * opt->priv->paths if they become renames, and then
2869 * get freed at the end of the merge, that would leave
2870 * the copy in cached_pairs dangling. Avoid this by
2871 * making a copy here.
2873 old_name = mem_pool_strdup(&opt->priv->pool, old_name);
2874 new_name = mem_pool_strdup(&opt->priv->pool, new_name);
2876 /* We don't care about oid/mode, only filenames and status */
2877 one = pool_alloc_filespec(&opt->priv->pool, old_name);
2878 two = pool_alloc_filespec(&opt->priv->pool, new_name);
2879 pool_diff_queue(&opt->priv->pool, pairs, one, two);
2880 pairs->queue[pairs->nr-1]->status = entry->value ? 'R' : 'D';
2884 static void cache_new_pair(struct rename_info *renames,
2885 int side,
2886 char *old_path,
2887 char *new_path,
2888 int free_old_value)
2890 char *old_value;
2891 new_path = xstrdup(new_path);
2892 old_value = strmap_put(&renames->cached_pairs[side],
2893 old_path, new_path);
2894 strset_add(&renames->cached_target_names[side], new_path);
2895 if (free_old_value)
2896 free(old_value);
2897 else
2898 assert(!old_value);
2901 static void possibly_cache_new_pair(struct rename_info *renames,
2902 struct diff_filepair *p,
2903 unsigned side,
2904 char *new_path)
2906 int dir_renamed_side = 0;
2908 if (new_path) {
2910 * Directory renames happen on the other side of history from
2911 * the side that adds new files to the old directory.
2913 dir_renamed_side = 3 - side;
2914 } else {
2915 int val = strintmap_get(&renames->relevant_sources[side],
2916 p->one->path);
2917 if (val == RELEVANT_NO_MORE) {
2918 assert(p->status == 'D');
2919 strset_add(&renames->cached_irrelevant[side],
2920 p->one->path);
2922 if (val <= 0)
2923 return;
2926 if (p->status == 'D') {
2928 * If we already had this delete, we'll just set it's value
2929 * to NULL again, so no harm.
2931 strmap_put(&renames->cached_pairs[side], p->one->path, NULL);
2932 } else if (p->status == 'R') {
2933 if (!new_path)
2934 new_path = p->two->path;
2935 else
2936 cache_new_pair(renames, dir_renamed_side,
2937 p->two->path, new_path, 0);
2938 cache_new_pair(renames, side, p->one->path, new_path, 1);
2939 } else if (p->status == 'A' && new_path) {
2940 cache_new_pair(renames, dir_renamed_side,
2941 p->two->path, new_path, 0);
2945 static int compare_pairs(const void *a_, const void *b_)
2947 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
2948 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
2950 return strcmp(a->one->path, b->one->path);
2953 /* Call diffcore_rename() to update deleted/added pairs into rename pairs */
2954 static int detect_regular_renames(struct merge_options *opt,
2955 unsigned side_index)
2957 struct diff_options diff_opts;
2958 struct rename_info *renames = &opt->priv->renames;
2960 prune_cached_from_relevant(renames, side_index);
2961 if (!possible_side_renames(renames, side_index)) {
2963 * No rename detection needed for this side, but we still need
2964 * to make sure 'adds' are marked correctly in case the other
2965 * side had directory renames.
2967 resolve_diffpair_statuses(&renames->pairs[side_index]);
2968 return 0;
2971 partial_clear_dir_rename_count(&renames->dir_rename_count[side_index]);
2972 repo_diff_setup(opt->repo, &diff_opts);
2973 diff_opts.flags.recursive = 1;
2974 diff_opts.flags.rename_empty = 0;
2975 diff_opts.detect_rename = DIFF_DETECT_RENAME;
2976 diff_opts.rename_limit = opt->rename_limit;
2977 if (opt->rename_limit <= 0)
2978 diff_opts.rename_limit = 7000;
2979 diff_opts.rename_score = opt->rename_score;
2980 diff_opts.show_rename_progress = opt->show_rename_progress;
2981 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2982 diff_setup_done(&diff_opts);
2984 diff_queued_diff = renames->pairs[side_index];
2985 trace2_region_enter("diff", "diffcore_rename", opt->repo);
2986 diffcore_rename_extended(&diff_opts,
2987 &opt->priv->pool,
2988 &renames->relevant_sources[side_index],
2989 &renames->dirs_removed[side_index],
2990 &renames->dir_rename_count[side_index],
2991 &renames->cached_pairs[side_index]);
2992 trace2_region_leave("diff", "diffcore_rename", opt->repo);
2993 resolve_diffpair_statuses(&diff_queued_diff);
2995 if (diff_opts.needed_rename_limit > 0)
2996 renames->redo_after_renames = 0;
2997 if (diff_opts.needed_rename_limit > renames->needed_limit)
2998 renames->needed_limit = diff_opts.needed_rename_limit;
3000 renames->pairs[side_index] = diff_queued_diff;
3002 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
3003 diff_queued_diff.nr = 0;
3004 diff_queued_diff.queue = NULL;
3005 diff_flush(&diff_opts);
3007 return 1;
3011 * Get information of all renames which occurred in 'side_pairs', making use
3012 * of any implicit directory renames in side_dir_renames (also making use of
3013 * implicit directory renames rename_exclusions as needed by
3014 * check_for_directory_rename()). Add all (updated) renames into result.
3016 static int collect_renames(struct merge_options *opt,
3017 struct diff_queue_struct *result,
3018 unsigned side_index,
3019 struct strmap *dir_renames_for_side,
3020 struct strmap *rename_exclusions)
3022 int i, clean = 1;
3023 struct strmap collisions;
3024 struct diff_queue_struct *side_pairs;
3025 struct hashmap_iter iter;
3026 struct strmap_entry *entry;
3027 struct rename_info *renames = &opt->priv->renames;
3029 side_pairs = &renames->pairs[side_index];
3030 compute_collisions(&collisions, dir_renames_for_side, side_pairs);
3032 for (i = 0; i < side_pairs->nr; ++i) {
3033 struct diff_filepair *p = side_pairs->queue[i];
3034 char *new_path; /* non-NULL only with directory renames */
3036 if (p->status != 'A' && p->status != 'R') {
3037 possibly_cache_new_pair(renames, p, side_index, NULL);
3038 pool_diff_free_filepair(&opt->priv->pool, p);
3039 continue;
3042 new_path = check_for_directory_rename(opt, p->two->path,
3043 side_index,
3044 dir_renames_for_side,
3045 rename_exclusions,
3046 &collisions,
3047 &clean);
3049 possibly_cache_new_pair(renames, p, side_index, new_path);
3050 if (p->status != 'R' && !new_path) {
3051 pool_diff_free_filepair(&opt->priv->pool, p);
3052 continue;
3055 if (new_path)
3056 apply_directory_rename_modifications(opt, p, new_path);
3059 * p->score comes back from diffcore_rename_extended() with
3060 * the similarity of the renamed file. The similarity is
3061 * was used to determine that the two files were related
3062 * and are a rename, which we have already used, but beyond
3063 * that we have no use for the similarity. So p->score is
3064 * now irrelevant. However, process_renames() will need to
3065 * know which side of the merge this rename was associated
3066 * with, so overwrite p->score with that value.
3068 p->score = side_index;
3069 result->queue[result->nr++] = p;
3072 /* Free each value in the collisions map */
3073 strmap_for_each_entry(&collisions, &iter, entry) {
3074 struct collision_info *info = entry->value;
3075 string_list_clear(&info->source_files, 0);
3078 * In compute_collisions(), we set collisions.strdup_strings to 0
3079 * so that we wouldn't have to make another copy of the new_path
3080 * allocated by apply_dir_rename(). But now that we've used them
3081 * and have no other references to these strings, it is time to
3082 * deallocate them.
3084 free_strmap_strings(&collisions);
3085 strmap_clear(&collisions, 1);
3086 return clean;
3089 static int detect_and_process_renames(struct merge_options *opt,
3090 struct tree *merge_base,
3091 struct tree *side1,
3092 struct tree *side2)
3094 struct diff_queue_struct combined;
3095 struct rename_info *renames = &opt->priv->renames;
3096 int need_dir_renames, s, clean = 1;
3097 unsigned detection_run = 0;
3099 memset(&combined, 0, sizeof(combined));
3100 if (!possible_renames(renames))
3101 goto cleanup;
3103 trace2_region_enter("merge", "regular renames", opt->repo);
3104 detection_run |= detect_regular_renames(opt, MERGE_SIDE1);
3105 detection_run |= detect_regular_renames(opt, MERGE_SIDE2);
3106 if (renames->needed_limit) {
3107 renames->cached_pairs_valid_side = 0;
3108 renames->redo_after_renames = 0;
3110 if (renames->redo_after_renames && detection_run) {
3111 int i, side;
3112 struct diff_filepair *p;
3114 /* Cache the renames, we found */
3115 for (side = MERGE_SIDE1; side <= MERGE_SIDE2; side++) {
3116 for (i = 0; i < renames->pairs[side].nr; ++i) {
3117 p = renames->pairs[side].queue[i];
3118 possibly_cache_new_pair(renames, p, side, NULL);
3122 /* Restart the merge with the cached renames */
3123 renames->redo_after_renames = 2;
3124 trace2_region_leave("merge", "regular renames", opt->repo);
3125 goto cleanup;
3127 use_cached_pairs(opt, &renames->cached_pairs[1], &renames->pairs[1]);
3128 use_cached_pairs(opt, &renames->cached_pairs[2], &renames->pairs[2]);
3129 trace2_region_leave("merge", "regular renames", opt->repo);
3131 trace2_region_enter("merge", "directory renames", opt->repo);
3132 need_dir_renames =
3133 !opt->priv->call_depth &&
3134 (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE ||
3135 opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT);
3137 if (need_dir_renames) {
3138 get_provisional_directory_renames(opt, MERGE_SIDE1, &clean);
3139 get_provisional_directory_renames(opt, MERGE_SIDE2, &clean);
3140 handle_directory_level_conflicts(opt);
3143 ALLOC_GROW(combined.queue,
3144 renames->pairs[1].nr + renames->pairs[2].nr,
3145 combined.alloc);
3146 clean &= collect_renames(opt, &combined, MERGE_SIDE1,
3147 &renames->dir_renames[2],
3148 &renames->dir_renames[1]);
3149 clean &= collect_renames(opt, &combined, MERGE_SIDE2,
3150 &renames->dir_renames[1],
3151 &renames->dir_renames[2]);
3152 STABLE_QSORT(combined.queue, combined.nr, compare_pairs);
3153 trace2_region_leave("merge", "directory renames", opt->repo);
3155 trace2_region_enter("merge", "process renames", opt->repo);
3156 clean &= process_renames(opt, &combined);
3157 trace2_region_leave("merge", "process renames", opt->repo);
3159 goto simple_cleanup; /* collect_renames() handles some of cleanup */
3161 cleanup:
3163 * Free now unneeded filepairs, which would have been handled
3164 * in collect_renames() normally but we skipped that code.
3166 for (s = MERGE_SIDE1; s <= MERGE_SIDE2; s++) {
3167 struct diff_queue_struct *side_pairs;
3168 int i;
3170 side_pairs = &renames->pairs[s];
3171 for (i = 0; i < side_pairs->nr; ++i) {
3172 struct diff_filepair *p = side_pairs->queue[i];
3173 pool_diff_free_filepair(&opt->priv->pool, p);
3177 simple_cleanup:
3178 /* Free memory for renames->pairs[] and combined */
3179 for (s = MERGE_SIDE1; s <= MERGE_SIDE2; s++) {
3180 free(renames->pairs[s].queue);
3181 DIFF_QUEUE_CLEAR(&renames->pairs[s]);
3183 if (combined.nr) {
3184 int i;
3185 for (i = 0; i < combined.nr; i++)
3186 pool_diff_free_filepair(&opt->priv->pool,
3187 combined.queue[i]);
3188 free(combined.queue);
3191 return clean;
3194 /*** Function Grouping: functions related to process_entries() ***/
3196 static int sort_dirs_next_to_their_children(const char *one, const char *two)
3198 unsigned char c1, c2;
3201 * Here we only care that entries for directories appear adjacent
3202 * to and before files underneath the directory. We can achieve
3203 * that by pretending to add a trailing slash to every file and
3204 * then sorting. In other words, we do not want the natural
3205 * sorting of
3206 * foo
3207 * foo.txt
3208 * foo/bar
3209 * Instead, we want "foo" to sort as though it were "foo/", so that
3210 * we instead get
3211 * foo.txt
3212 * foo
3213 * foo/bar
3214 * To achieve this, we basically implement our own strcmp, except that
3215 * if we get to the end of either string instead of comparing NUL to
3216 * another character, we compare '/' to it.
3218 * If this unusual "sort as though '/' were appended" perplexes
3219 * you, perhaps it will help to note that this is not the final
3220 * sort. write_tree() will sort again without the trailing slash
3221 * magic, but just on paths immediately under a given tree.
3223 * The reason to not use df_name_compare directly was that it was
3224 * just too expensive (we don't have the string lengths handy), so
3225 * it was reimplemented.
3229 * NOTE: This function will never be called with two equal strings,
3230 * because it is used to sort the keys of a strmap, and strmaps have
3231 * unique keys by construction. That simplifies our c1==c2 handling
3232 * below.
3235 while (*one && (*one == *two)) {
3236 one++;
3237 two++;
3240 c1 = *one ? *one : '/';
3241 c2 = *two ? *two : '/';
3243 if (c1 == c2) {
3244 /* Getting here means one is a leading directory of the other */
3245 return (*one) ? 1 : -1;
3246 } else
3247 return c1 - c2;
3250 static int read_oid_strbuf(struct merge_options *opt,
3251 const struct object_id *oid,
3252 struct strbuf *dst)
3254 void *buf;
3255 enum object_type type;
3256 unsigned long size;
3257 buf = read_object_file(oid, &type, &size);
3258 if (!buf)
3259 return err(opt, _("cannot read object %s"), oid_to_hex(oid));
3260 if (type != OBJ_BLOB) {
3261 free(buf);
3262 return err(opt, _("object %s is not a blob"), oid_to_hex(oid));
3264 strbuf_attach(dst, buf, size, size + 1);
3265 return 0;
3268 static int blob_unchanged(struct merge_options *opt,
3269 const struct version_info *base,
3270 const struct version_info *side,
3271 const char *path)
3273 struct strbuf basebuf = STRBUF_INIT;
3274 struct strbuf sidebuf = STRBUF_INIT;
3275 int ret = 0; /* assume changed for safety */
3276 struct index_state *idx = &opt->priv->attr_index;
3278 if (!idx->initialized)
3279 initialize_attr_index(opt);
3281 if (base->mode != side->mode)
3282 return 0;
3283 if (oideq(&base->oid, &side->oid))
3284 return 1;
3286 if (read_oid_strbuf(opt, &base->oid, &basebuf) ||
3287 read_oid_strbuf(opt, &side->oid, &sidebuf))
3288 goto error_return;
3290 * Note: binary | is used so that both renormalizations are
3291 * performed. Comparison can be skipped if both files are
3292 * unchanged since their sha1s have already been compared.
3294 if (renormalize_buffer(idx, path, basebuf.buf, basebuf.len, &basebuf) |
3295 renormalize_buffer(idx, path, sidebuf.buf, sidebuf.len, &sidebuf))
3296 ret = (basebuf.len == sidebuf.len &&
3297 !memcmp(basebuf.buf, sidebuf.buf, basebuf.len));
3299 error_return:
3300 strbuf_release(&basebuf);
3301 strbuf_release(&sidebuf);
3302 return ret;
3305 struct directory_versions {
3307 * versions: list of (basename -> version_info)
3309 * The basenames are in reverse lexicographic order of full pathnames,
3310 * as processed in process_entries(). This puts all entries within
3311 * a directory together, and covers the directory itself after
3312 * everything within it, allowing us to write subtrees before needing
3313 * to record information for the tree itself.
3315 struct string_list versions;
3318 * offsets: list of (full relative path directories -> integer offsets)
3320 * Since versions contains basenames from files in multiple different
3321 * directories, we need to know which entries in versions correspond
3322 * to which directories. Values of e.g.
3323 * "" 0
3324 * src 2
3325 * src/moduleA 5
3326 * Would mean that entries 0-1 of versions are files in the toplevel
3327 * directory, entries 2-4 are files under src/, and the remaining
3328 * entries starting at index 5 are files under src/moduleA/.
3330 struct string_list offsets;
3333 * last_directory: directory that previously processed file found in
3335 * last_directory starts NULL, but records the directory in which the
3336 * previous file was found within. As soon as
3337 * directory(current_file) != last_directory
3338 * then we need to start updating accounting in versions & offsets.
3339 * Note that last_directory is always the last path in "offsets" (or
3340 * NULL if "offsets" is empty) so this exists just for quick access.
3342 const char *last_directory;
3344 /* last_directory_len: cached computation of strlen(last_directory) */
3345 unsigned last_directory_len;
3348 static int tree_entry_order(const void *a_, const void *b_)
3350 const struct string_list_item *a = a_;
3351 const struct string_list_item *b = b_;
3353 const struct merged_info *ami = a->util;
3354 const struct merged_info *bmi = b->util;
3355 return base_name_compare(a->string, strlen(a->string), ami->result.mode,
3356 b->string, strlen(b->string), bmi->result.mode);
3359 static void write_tree(struct object_id *result_oid,
3360 struct string_list *versions,
3361 unsigned int offset,
3362 size_t hash_size)
3364 size_t maxlen = 0, extra;
3365 unsigned int nr;
3366 struct strbuf buf = STRBUF_INIT;
3367 int i;
3369 assert(offset <= versions->nr);
3370 nr = versions->nr - offset;
3371 if (versions->nr)
3372 /* No need for STABLE_QSORT -- filenames must be unique */
3373 QSORT(versions->items + offset, nr, tree_entry_order);
3375 /* Pre-allocate some space in buf */
3376 extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
3377 for (i = 0; i < nr; i++) {
3378 maxlen += strlen(versions->items[offset+i].string) + extra;
3380 strbuf_grow(&buf, maxlen);
3382 /* Write each entry out to buf */
3383 for (i = 0; i < nr; i++) {
3384 struct merged_info *mi = versions->items[offset+i].util;
3385 struct version_info *ri = &mi->result;
3386 strbuf_addf(&buf, "%o %s%c",
3387 ri->mode,
3388 versions->items[offset+i].string, '\0');
3389 strbuf_add(&buf, ri->oid.hash, hash_size);
3392 /* Write this object file out, and record in result_oid */
3393 write_object_file(buf.buf, buf.len, tree_type, result_oid);
3394 strbuf_release(&buf);
3397 static void record_entry_for_tree(struct directory_versions *dir_metadata,
3398 const char *path,
3399 struct merged_info *mi)
3401 const char *basename;
3403 if (mi->is_null)
3404 /* nothing to record */
3405 return;
3407 basename = path + mi->basename_offset;
3408 assert(strchr(basename, '/') == NULL);
3409 string_list_append(&dir_metadata->versions,
3410 basename)->util = &mi->result;
3413 static void write_completed_directory(struct merge_options *opt,
3414 const char *new_directory_name,
3415 struct directory_versions *info)
3417 const char *prev_dir;
3418 struct merged_info *dir_info = NULL;
3419 unsigned int offset;
3422 * Some explanation of info->versions and info->offsets...
3424 * process_entries() iterates over all relevant files AND
3425 * directories in reverse lexicographic order, and calls this
3426 * function. Thus, an example of the paths that process_entries()
3427 * could operate on (along with the directories for those paths
3428 * being shown) is:
3430 * xtract.c ""
3431 * tokens.txt ""
3432 * src/moduleB/umm.c src/moduleB
3433 * src/moduleB/stuff.h src/moduleB
3434 * src/moduleB/baz.c src/moduleB
3435 * src/moduleB src
3436 * src/moduleA/foo.c src/moduleA
3437 * src/moduleA/bar.c src/moduleA
3438 * src/moduleA src
3439 * src ""
3440 * Makefile ""
3442 * info->versions:
3444 * always contains the unprocessed entries and their
3445 * version_info information. For example, after the first five
3446 * entries above, info->versions would be:
3448 * xtract.c <xtract.c's version_info>
3449 * token.txt <token.txt's version_info>
3450 * umm.c <src/moduleB/umm.c's version_info>
3451 * stuff.h <src/moduleB/stuff.h's version_info>
3452 * baz.c <src/moduleB/baz.c's version_info>
3454 * Once a subdirectory is completed we remove the entries in
3455 * that subdirectory from info->versions, writing it as a tree
3456 * (write_tree()). Thus, as soon as we get to src/moduleB,
3457 * info->versions would be updated to
3459 * xtract.c <xtract.c's version_info>
3460 * token.txt <token.txt's version_info>
3461 * moduleB <src/moduleB's version_info>
3463 * info->offsets:
3465 * helps us track which entries in info->versions correspond to
3466 * which directories. When we are N directories deep (e.g. 4
3467 * for src/modA/submod/subdir/), we have up to N+1 unprocessed
3468 * directories (+1 because of toplevel dir). Corresponding to
3469 * the info->versions example above, after processing five entries
3470 * info->offsets will be:
3472 * "" 0
3473 * src/moduleB 2
3475 * which is used to know that xtract.c & token.txt are from the
3476 * toplevel dirctory, while umm.c & stuff.h & baz.c are from the
3477 * src/moduleB directory. Again, following the example above,
3478 * once we need to process src/moduleB, then info->offsets is
3479 * updated to
3481 * "" 0
3482 * src 2
3484 * which says that moduleB (and only moduleB so far) is in the
3485 * src directory.
3487 * One unique thing to note about info->offsets here is that
3488 * "src" was not added to info->offsets until there was a path
3489 * (a file OR directory) immediately below src/ that got
3490 * processed.
3492 * Since process_entry() just appends new entries to info->versions,
3493 * write_completed_directory() only needs to do work if the next path
3494 * is in a directory that is different than the last directory found
3495 * in info->offsets.
3499 * If we are working with the same directory as the last entry, there
3500 * is no work to do. (See comments above the directory_name member of
3501 * struct merged_info for why we can use pointer comparison instead of
3502 * strcmp here.)
3504 if (new_directory_name == info->last_directory)
3505 return;
3508 * If we are just starting (last_directory is NULL), or last_directory
3509 * is a prefix of the current directory, then we can just update
3510 * info->offsets to record the offset where we started this directory
3511 * and update last_directory to have quick access to it.
3513 if (info->last_directory == NULL ||
3514 !strncmp(new_directory_name, info->last_directory,
3515 info->last_directory_len)) {
3516 uintptr_t offset = info->versions.nr;
3518 info->last_directory = new_directory_name;
3519 info->last_directory_len = strlen(info->last_directory);
3521 * Record the offset into info->versions where we will
3522 * start recording basenames of paths found within
3523 * new_directory_name.
3525 string_list_append(&info->offsets,
3526 info->last_directory)->util = (void*)offset;
3527 return;
3531 * The next entry that will be processed will be within
3532 * new_directory_name. Since at this point we know that
3533 * new_directory_name is within a different directory than
3534 * info->last_directory, we have all entries for info->last_directory
3535 * in info->versions and we need to create a tree object for them.
3537 dir_info = strmap_get(&opt->priv->paths, info->last_directory);
3538 assert(dir_info);
3539 offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
3540 if (offset == info->versions.nr) {
3542 * Actually, we don't need to create a tree object in this
3543 * case. Whenever all files within a directory disappear
3544 * during the merge (e.g. unmodified on one side and
3545 * deleted on the other, or files were renamed elsewhere),
3546 * then we get here and the directory itself needs to be
3547 * omitted from its parent tree as well.
3549 dir_info->is_null = 1;
3550 } else {
3552 * Write out the tree to the git object directory, and also
3553 * record the mode and oid in dir_info->result.
3555 dir_info->is_null = 0;
3556 dir_info->result.mode = S_IFDIR;
3557 write_tree(&dir_info->result.oid, &info->versions, offset,
3558 opt->repo->hash_algo->rawsz);
3562 * We've now used several entries from info->versions and one entry
3563 * from info->offsets, so we get rid of those values.
3565 info->offsets.nr--;
3566 info->versions.nr = offset;
3569 * Now we've taken care of the completed directory, but we need to
3570 * prepare things since future entries will be in
3571 * new_directory_name. (In particular, process_entry() will be
3572 * appending new entries to info->versions.) So, we need to make
3573 * sure new_directory_name is the last entry in info->offsets.
3575 prev_dir = info->offsets.nr == 0 ? NULL :
3576 info->offsets.items[info->offsets.nr-1].string;
3577 if (new_directory_name != prev_dir) {
3578 uintptr_t c = info->versions.nr;
3579 string_list_append(&info->offsets,
3580 new_directory_name)->util = (void*)c;
3583 /* And, of course, we need to update last_directory to match. */
3584 info->last_directory = new_directory_name;
3585 info->last_directory_len = strlen(info->last_directory);
3588 /* Per entry merge function */
3589 static void process_entry(struct merge_options *opt,
3590 const char *path,
3591 struct conflict_info *ci,
3592 struct directory_versions *dir_metadata)
3594 int df_file_index = 0;
3596 VERIFY_CI(ci);
3597 assert(ci->filemask >= 0 && ci->filemask <= 7);
3598 /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
3599 assert(ci->match_mask == 0 || ci->match_mask == 3 ||
3600 ci->match_mask == 5 || ci->match_mask == 6);
3602 if (ci->dirmask) {
3603 record_entry_for_tree(dir_metadata, path, &ci->merged);
3604 if (ci->filemask == 0)
3605 /* nothing else to handle */
3606 return;
3607 assert(ci->df_conflict);
3610 if (ci->df_conflict && ci->merged.result.mode == 0) {
3611 int i;
3614 * directory no longer in the way, but we do have a file we
3615 * need to place here so we need to clean away the "directory
3616 * merges to nothing" result.
3618 ci->df_conflict = 0;
3619 assert(ci->filemask != 0);
3620 ci->merged.clean = 0;
3621 ci->merged.is_null = 0;
3622 /* and we want to zero out any directory-related entries */
3623 ci->match_mask = (ci->match_mask & ~ci->dirmask);
3624 ci->dirmask = 0;
3625 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
3626 if (ci->filemask & (1 << i))
3627 continue;
3628 ci->stages[i].mode = 0;
3629 oidcpy(&ci->stages[i].oid, null_oid());
3631 } else if (ci->df_conflict && ci->merged.result.mode != 0) {
3633 * This started out as a D/F conflict, and the entries in
3634 * the competing directory were not removed by the merge as
3635 * evidenced by write_completed_directory() writing a value
3636 * to ci->merged.result.mode.
3638 struct conflict_info *new_ci;
3639 const char *branch;
3640 const char *old_path = path;
3641 int i;
3643 assert(ci->merged.result.mode == S_IFDIR);
3646 * If filemask is 1, we can just ignore the file as having
3647 * been deleted on both sides. We do not want to overwrite
3648 * ci->merged.result, since it stores the tree for all the
3649 * files under it.
3651 if (ci->filemask == 1) {
3652 ci->filemask = 0;
3653 return;
3657 * This file still exists on at least one side, and we want
3658 * the directory to remain here, so we need to move this
3659 * path to some new location.
3661 new_ci = mem_pool_calloc(&opt->priv->pool, 1, sizeof(*new_ci));
3663 /* We don't really want new_ci->merged.result copied, but it'll
3664 * be overwritten below so it doesn't matter. We also don't
3665 * want any directory mode/oid values copied, but we'll zero
3666 * those out immediately. We do want the rest of ci copied.
3668 memcpy(new_ci, ci, sizeof(*ci));
3669 new_ci->match_mask = (new_ci->match_mask & ~new_ci->dirmask);
3670 new_ci->dirmask = 0;
3671 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
3672 if (new_ci->filemask & (1 << i))
3673 continue;
3674 /* zero out any entries related to directories */
3675 new_ci->stages[i].mode = 0;
3676 oidcpy(&new_ci->stages[i].oid, null_oid());
3680 * Find out which side this file came from; note that we
3681 * cannot just use ci->filemask, because renames could cause
3682 * the filemask to go back to 7. So we use dirmask, then
3683 * pick the opposite side's index.
3685 df_file_index = (ci->dirmask & (1 << 1)) ? 2 : 1;
3686 branch = (df_file_index == 1) ? opt->branch1 : opt->branch2;
3687 path = unique_path(&opt->priv->paths, path, branch);
3688 strmap_put(&opt->priv->paths, path, new_ci);
3690 path_msg(opt, path, 0,
3691 _("CONFLICT (file/directory): directory in the way "
3692 "of %s from %s; moving it to %s instead."),
3693 old_path, branch, path);
3696 * Zero out the filemask for the old ci. At this point, ci
3697 * was just an entry for a directory, so we don't need to
3698 * do anything more with it.
3700 ci->filemask = 0;
3703 * Now note that we're working on the new entry (path was
3704 * updated above.
3706 ci = new_ci;
3710 * NOTE: Below there is a long switch-like if-elseif-elseif... block
3711 * which the code goes through even for the df_conflict cases
3712 * above.
3714 if (ci->match_mask) {
3715 ci->merged.clean = !ci->df_conflict && !ci->path_conflict;
3716 if (ci->match_mask == 6) {
3717 /* stages[1] == stages[2] */
3718 ci->merged.result.mode = ci->stages[1].mode;
3719 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
3720 } else {
3721 /* determine the mask of the side that didn't match */
3722 unsigned int othermask = 7 & ~ci->match_mask;
3723 int side = (othermask == 4) ? 2 : 1;
3725 ci->merged.result.mode = ci->stages[side].mode;
3726 ci->merged.is_null = !ci->merged.result.mode;
3727 if (ci->merged.is_null)
3728 ci->merged.clean = 1;
3729 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
3731 assert(othermask == 2 || othermask == 4);
3732 assert(ci->merged.is_null ==
3733 (ci->filemask == ci->match_mask));
3735 } else if (ci->filemask >= 6 &&
3736 (S_IFMT & ci->stages[1].mode) !=
3737 (S_IFMT & ci->stages[2].mode)) {
3738 /* Two different items from (file/submodule/symlink) */
3739 if (opt->priv->call_depth) {
3740 /* Just use the version from the merge base */
3741 ci->merged.clean = 0;
3742 oidcpy(&ci->merged.result.oid, &ci->stages[0].oid);
3743 ci->merged.result.mode = ci->stages[0].mode;
3744 ci->merged.is_null = (ci->merged.result.mode == 0);
3745 } else {
3746 /* Handle by renaming one or both to separate paths. */
3747 unsigned o_mode = ci->stages[0].mode;
3748 unsigned a_mode = ci->stages[1].mode;
3749 unsigned b_mode = ci->stages[2].mode;
3750 struct conflict_info *new_ci;
3751 const char *a_path = NULL, *b_path = NULL;
3752 int rename_a = 0, rename_b = 0;
3754 new_ci = mem_pool_alloc(&opt->priv->pool,
3755 sizeof(*new_ci));
3757 if (S_ISREG(a_mode))
3758 rename_a = 1;
3759 else if (S_ISREG(b_mode))
3760 rename_b = 1;
3761 else {
3762 rename_a = 1;
3763 rename_b = 1;
3766 if (rename_a && rename_b) {
3767 path_msg(opt, path, 0,
3768 _("CONFLICT (distinct types): %s had "
3769 "different types on each side; "
3770 "renamed both of them so each can "
3771 "be recorded somewhere."),
3772 path);
3773 } else {
3774 path_msg(opt, path, 0,
3775 _("CONFLICT (distinct types): %s had "
3776 "different types on each side; "
3777 "renamed one of them so each can be "
3778 "recorded somewhere."),
3779 path);
3782 ci->merged.clean = 0;
3783 memcpy(new_ci, ci, sizeof(*new_ci));
3785 /* Put b into new_ci, removing a from stages */
3786 new_ci->merged.result.mode = ci->stages[2].mode;
3787 oidcpy(&new_ci->merged.result.oid, &ci->stages[2].oid);
3788 new_ci->stages[1].mode = 0;
3789 oidcpy(&new_ci->stages[1].oid, null_oid());
3790 new_ci->filemask = 5;
3791 if ((S_IFMT & b_mode) != (S_IFMT & o_mode)) {
3792 new_ci->stages[0].mode = 0;
3793 oidcpy(&new_ci->stages[0].oid, null_oid());
3794 new_ci->filemask = 4;
3797 /* Leave only a in ci, fixing stages. */
3798 ci->merged.result.mode = ci->stages[1].mode;
3799 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
3800 ci->stages[2].mode = 0;
3801 oidcpy(&ci->stages[2].oid, null_oid());
3802 ci->filemask = 3;
3803 if ((S_IFMT & a_mode) != (S_IFMT & o_mode)) {
3804 ci->stages[0].mode = 0;
3805 oidcpy(&ci->stages[0].oid, null_oid());
3806 ci->filemask = 2;
3809 /* Insert entries into opt->priv_paths */
3810 assert(rename_a || rename_b);
3811 if (rename_a) {
3812 a_path = unique_path(&opt->priv->paths,
3813 path, opt->branch1);
3814 strmap_put(&opt->priv->paths, a_path, ci);
3817 if (rename_b)
3818 b_path = unique_path(&opt->priv->paths,
3819 path, opt->branch2);
3820 else
3821 b_path = path;
3822 strmap_put(&opt->priv->paths, b_path, new_ci);
3824 if (rename_a && rename_b)
3825 strmap_remove(&opt->priv->paths, path, 0);
3828 * Do special handling for b_path since process_entry()
3829 * won't be called on it specially.
3831 strmap_put(&opt->priv->conflicted, b_path, new_ci);
3832 record_entry_for_tree(dir_metadata, b_path,
3833 &new_ci->merged);
3836 * Remaining code for processing this entry should
3837 * think in terms of processing a_path.
3839 if (a_path)
3840 path = a_path;
3842 } else if (ci->filemask >= 6) {
3843 /* Need a two-way or three-way content merge */
3844 struct version_info merged_file;
3845 unsigned clean_merge;
3846 struct version_info *o = &ci->stages[0];
3847 struct version_info *a = &ci->stages[1];
3848 struct version_info *b = &ci->stages[2];
3850 clean_merge = handle_content_merge(opt, path, o, a, b,
3851 ci->pathnames,
3852 opt->priv->call_depth * 2,
3853 &merged_file);
3854 ci->merged.clean = clean_merge &&
3855 !ci->df_conflict && !ci->path_conflict;
3856 ci->merged.result.mode = merged_file.mode;
3857 ci->merged.is_null = (merged_file.mode == 0);
3858 oidcpy(&ci->merged.result.oid, &merged_file.oid);
3859 if (clean_merge && ci->df_conflict) {
3860 assert(df_file_index == 1 || df_file_index == 2);
3861 ci->filemask = 1 << df_file_index;
3862 ci->stages[df_file_index].mode = merged_file.mode;
3863 oidcpy(&ci->stages[df_file_index].oid, &merged_file.oid);
3865 if (!clean_merge) {
3866 const char *reason = _("content");
3867 if (ci->filemask == 6)
3868 reason = _("add/add");
3869 if (S_ISGITLINK(merged_file.mode))
3870 reason = _("submodule");
3871 path_msg(opt, path, 0,
3872 _("CONFLICT (%s): Merge conflict in %s"),
3873 reason, path);
3875 } else if (ci->filemask == 3 || ci->filemask == 5) {
3876 /* Modify/delete */
3877 const char *modify_branch, *delete_branch;
3878 int side = (ci->filemask == 5) ? 2 : 1;
3879 int index = opt->priv->call_depth ? 0 : side;
3881 ci->merged.result.mode = ci->stages[index].mode;
3882 oidcpy(&ci->merged.result.oid, &ci->stages[index].oid);
3883 ci->merged.clean = 0;
3885 modify_branch = (side == 1) ? opt->branch1 : opt->branch2;
3886 delete_branch = (side == 1) ? opt->branch2 : opt->branch1;
3888 if (opt->renormalize &&
3889 blob_unchanged(opt, &ci->stages[0], &ci->stages[side],
3890 path)) {
3891 if (!ci->path_conflict) {
3893 * Blob unchanged after renormalization, so
3894 * there's no modify/delete conflict after all;
3895 * we can just remove the file.
3897 ci->merged.is_null = 1;
3898 ci->merged.clean = 1;
3900 * file goes away => even if there was a
3901 * directory/file conflict there isn't one now.
3903 ci->df_conflict = 0;
3904 } else {
3905 /* rename/delete, so conflict remains */
3907 } else if (ci->path_conflict &&
3908 oideq(&ci->stages[0].oid, &ci->stages[side].oid)) {
3910 * This came from a rename/delete; no action to take,
3911 * but avoid printing "modify/delete" conflict notice
3912 * since the contents were not modified.
3914 } else {
3915 path_msg(opt, path, 0,
3916 _("CONFLICT (modify/delete): %s deleted in %s "
3917 "and modified in %s. Version %s of %s left "
3918 "in tree."),
3919 path, delete_branch, modify_branch,
3920 modify_branch, path);
3922 } else if (ci->filemask == 2 || ci->filemask == 4) {
3923 /* Added on one side */
3924 int side = (ci->filemask == 4) ? 2 : 1;
3925 ci->merged.result.mode = ci->stages[side].mode;
3926 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
3927 ci->merged.clean = !ci->df_conflict && !ci->path_conflict;
3928 } else if (ci->filemask == 1) {
3929 /* Deleted on both sides */
3930 ci->merged.is_null = 1;
3931 ci->merged.result.mode = 0;
3932 oidcpy(&ci->merged.result.oid, null_oid());
3933 assert(!ci->df_conflict);
3934 ci->merged.clean = !ci->path_conflict;
3938 * If still conflicted, record it separately. This allows us to later
3939 * iterate over just conflicted entries when updating the index instead
3940 * of iterating over all entries.
3942 if (!ci->merged.clean)
3943 strmap_put(&opt->priv->conflicted, path, ci);
3945 /* Record metadata for ci->merged in dir_metadata */
3946 record_entry_for_tree(dir_metadata, path, &ci->merged);
3949 static void prefetch_for_content_merges(struct merge_options *opt,
3950 struct string_list *plist)
3952 struct string_list_item *e;
3953 struct oid_array to_fetch = OID_ARRAY_INIT;
3955 if (opt->repo != the_repository || !has_promisor_remote())
3956 return;
3958 for (e = &plist->items[plist->nr-1]; e >= plist->items; --e) {
3959 /* char *path = e->string; */
3960 struct conflict_info *ci = e->util;
3961 int i;
3963 /* Ignore clean entries */
3964 if (ci->merged.clean)
3965 continue;
3967 /* Ignore entries that don't need a content merge */
3968 if (ci->match_mask || ci->filemask < 6 ||
3969 !S_ISREG(ci->stages[1].mode) ||
3970 !S_ISREG(ci->stages[2].mode) ||
3971 oideq(&ci->stages[1].oid, &ci->stages[2].oid))
3972 continue;
3974 /* Also don't need content merge if base matches either side */
3975 if (ci->filemask == 7 &&
3976 S_ISREG(ci->stages[0].mode) &&
3977 (oideq(&ci->stages[0].oid, &ci->stages[1].oid) ||
3978 oideq(&ci->stages[0].oid, &ci->stages[2].oid)))
3979 continue;
3981 for (i = 0; i < 3; i++) {
3982 unsigned side_mask = (1 << i);
3983 struct version_info *vi = &ci->stages[i];
3985 if ((ci->filemask & side_mask) &&
3986 S_ISREG(vi->mode) &&
3987 oid_object_info_extended(opt->repo, &vi->oid, NULL,
3988 OBJECT_INFO_FOR_PREFETCH))
3989 oid_array_append(&to_fetch, &vi->oid);
3993 promisor_remote_get_direct(opt->repo, to_fetch.oid, to_fetch.nr);
3994 oid_array_clear(&to_fetch);
3997 static void process_entries(struct merge_options *opt,
3998 struct object_id *result_oid)
4000 struct hashmap_iter iter;
4001 struct strmap_entry *e;
4002 struct string_list plist = STRING_LIST_INIT_NODUP;
4003 struct string_list_item *entry;
4004 struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
4005 STRING_LIST_INIT_NODUP,
4006 NULL, 0 };
4008 trace2_region_enter("merge", "process_entries setup", opt->repo);
4009 if (strmap_empty(&opt->priv->paths)) {
4010 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
4011 return;
4014 /* Hack to pre-allocate plist to the desired size */
4015 trace2_region_enter("merge", "plist grow", opt->repo);
4016 ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
4017 trace2_region_leave("merge", "plist grow", opt->repo);
4019 /* Put every entry from paths into plist, then sort */
4020 trace2_region_enter("merge", "plist copy", opt->repo);
4021 strmap_for_each_entry(&opt->priv->paths, &iter, e) {
4022 string_list_append(&plist, e->key)->util = e->value;
4024 trace2_region_leave("merge", "plist copy", opt->repo);
4026 trace2_region_enter("merge", "plist special sort", opt->repo);
4027 plist.cmp = sort_dirs_next_to_their_children;
4028 string_list_sort(&plist);
4029 trace2_region_leave("merge", "plist special sort", opt->repo);
4031 trace2_region_leave("merge", "process_entries setup", opt->repo);
4034 * Iterate over the items in reverse order, so we can handle paths
4035 * below a directory before needing to handle the directory itself.
4037 * This allows us to write subtrees before we need to write trees,
4038 * and it also enables sane handling of directory/file conflicts
4039 * (because it allows us to know whether the directory is still in
4040 * the way when it is time to process the file at the same path).
4042 trace2_region_enter("merge", "processing", opt->repo);
4043 prefetch_for_content_merges(opt, &plist);
4044 for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
4045 char *path = entry->string;
4047 * NOTE: mi may actually be a pointer to a conflict_info, but
4048 * we have to check mi->clean first to see if it's safe to
4049 * reassign to such a pointer type.
4051 struct merged_info *mi = entry->util;
4053 write_completed_directory(opt, mi->directory_name,
4054 &dir_metadata);
4055 if (mi->clean)
4056 record_entry_for_tree(&dir_metadata, path, mi);
4057 else {
4058 struct conflict_info *ci = (struct conflict_info *)mi;
4059 process_entry(opt, path, ci, &dir_metadata);
4062 trace2_region_leave("merge", "processing", opt->repo);
4064 trace2_region_enter("merge", "process_entries cleanup", opt->repo);
4065 if (dir_metadata.offsets.nr != 1 ||
4066 (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
4067 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
4068 dir_metadata.offsets.nr);
4069 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
4070 (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
4071 fflush(stdout);
4072 BUG("dir_metadata accounting completely off; shouldn't happen");
4074 write_tree(result_oid, &dir_metadata.versions, 0,
4075 opt->repo->hash_algo->rawsz);
4076 string_list_clear(&plist, 0);
4077 string_list_clear(&dir_metadata.versions, 0);
4078 string_list_clear(&dir_metadata.offsets, 0);
4079 trace2_region_leave("merge", "process_entries cleanup", opt->repo);
4082 /*** Function Grouping: functions related to merge_switch_to_result() ***/
4084 static int checkout(struct merge_options *opt,
4085 struct tree *prev,
4086 struct tree *next)
4088 /* Switch the index/working copy from old to new */
4089 int ret;
4090 struct tree_desc trees[2];
4091 struct unpack_trees_options unpack_opts;
4093 memset(&unpack_opts, 0, sizeof(unpack_opts));
4094 unpack_opts.head_idx = -1;
4095 unpack_opts.src_index = opt->repo->index;
4096 unpack_opts.dst_index = opt->repo->index;
4098 setup_unpack_trees_porcelain(&unpack_opts, "merge");
4101 * NOTE: if this were just "git checkout" code, we would probably
4102 * read or refresh the cache and check for a conflicted index, but
4103 * builtin/merge.c or sequencer.c really needs to read the index
4104 * and check for conflicted entries before starting merging for a
4105 * good user experience (no sense waiting for merges/rebases before
4106 * erroring out), so there's no reason to duplicate that work here.
4109 /* 2-way merge to the new branch */
4110 unpack_opts.update = 1;
4111 unpack_opts.merge = 1;
4112 unpack_opts.quiet = 0; /* FIXME: sequencer might want quiet? */
4113 unpack_opts.verbose_update = (opt->verbosity > 2);
4114 unpack_opts.fn = twoway_merge;
4115 unpack_opts.preserve_ignored = 0; /* FIXME: !opts->overwrite_ignore */
4116 parse_tree(prev);
4117 init_tree_desc(&trees[0], prev->buffer, prev->size);
4118 parse_tree(next);
4119 init_tree_desc(&trees[1], next->buffer, next->size);
4121 ret = unpack_trees(2, trees, &unpack_opts);
4122 clear_unpack_trees_porcelain(&unpack_opts);
4123 return ret;
4126 static int record_conflicted_index_entries(struct merge_options *opt)
4128 struct hashmap_iter iter;
4129 struct strmap_entry *e;
4130 struct index_state *index = opt->repo->index;
4131 struct checkout state = CHECKOUT_INIT;
4132 int errs = 0;
4133 int original_cache_nr;
4135 if (strmap_empty(&opt->priv->conflicted))
4136 return 0;
4139 * We are in a conflicted state. These conflicts might be inside
4140 * sparse-directory entries, so check if any entries are outside
4141 * of the sparse-checkout cone preemptively.
4143 * We set original_cache_nr below, but that might change if
4144 * index_name_pos() calls ask for paths within sparse directories.
4146 strmap_for_each_entry(&opt->priv->conflicted, &iter, e) {
4147 if (!path_in_sparse_checkout(e->key, index)) {
4148 ensure_full_index(index);
4149 break;
4153 /* If any entries have skip_worktree set, we'll have to check 'em out */
4154 state.force = 1;
4155 state.quiet = 1;
4156 state.refresh_cache = 1;
4157 state.istate = index;
4158 original_cache_nr = index->cache_nr;
4160 /* Append every entry from conflicted into index, then sort */
4161 strmap_for_each_entry(&opt->priv->conflicted, &iter, e) {
4162 const char *path = e->key;
4163 struct conflict_info *ci = e->value;
4164 int pos;
4165 struct cache_entry *ce;
4166 int i;
4168 VERIFY_CI(ci);
4171 * The index will already have a stage=0 entry for this path,
4172 * because we created an as-merged-as-possible version of the
4173 * file and checkout() moved the working copy and index over
4174 * to that version.
4176 * However, previous iterations through this loop will have
4177 * added unstaged entries to the end of the cache which
4178 * ignore the standard alphabetical ordering of cache
4179 * entries and break invariants needed for index_name_pos()
4180 * to work. However, we know the entry we want is before
4181 * those appended cache entries, so do a temporary swap on
4182 * cache_nr to only look through entries of interest.
4184 SWAP(index->cache_nr, original_cache_nr);
4185 pos = index_name_pos(index, path, strlen(path));
4186 SWAP(index->cache_nr, original_cache_nr);
4187 if (pos < 0) {
4188 if (ci->filemask != 1)
4189 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path);
4190 cache_tree_invalidate_path(index, path);
4191 } else {
4192 ce = index->cache[pos];
4195 * Clean paths with CE_SKIP_WORKTREE set will not be
4196 * written to the working tree by the unpack_trees()
4197 * call in checkout(). Our conflicted entries would
4198 * have appeared clean to that code since we ignored
4199 * the higher order stages. Thus, we need override
4200 * the CE_SKIP_WORKTREE bit and manually write those
4201 * files to the working disk here.
4203 if (ce_skip_worktree(ce)) {
4204 struct stat st;
4206 if (!lstat(path, &st)) {
4207 char *new_name = unique_path(&opt->priv->paths,
4208 path,
4209 "cruft");
4211 path_msg(opt, path, 1,
4212 _("Note: %s not up to date and in way of checking out conflicted version; old copy renamed to %s"),
4213 path, new_name);
4214 errs |= rename(path, new_name);
4215 free(new_name);
4217 errs |= checkout_entry(ce, &state, NULL, NULL);
4221 * Mark this cache entry for removal and instead add
4222 * new stage>0 entries corresponding to the
4223 * conflicts. If there are many conflicted entries, we
4224 * want to avoid memmove'ing O(NM) entries by
4225 * inserting the new entries one at a time. So,
4226 * instead, we just add the new cache entries to the
4227 * end (ignoring normal index requirements on sort
4228 * order) and sort the index once we're all done.
4230 ce->ce_flags |= CE_REMOVE;
4233 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
4234 struct version_info *vi;
4235 if (!(ci->filemask & (1ul << i)))
4236 continue;
4237 vi = &ci->stages[i];
4238 ce = make_cache_entry(index, vi->mode, &vi->oid,
4239 path, i+1, 0);
4240 add_index_entry(index, ce, ADD_CACHE_JUST_APPEND);
4245 * Remove the unused cache entries (and invalidate the relevant
4246 * cache-trees), then sort the index entries to get the conflicted
4247 * entries we added to the end into their right locations.
4249 remove_marked_cache_entries(index, 1);
4251 * No need for STABLE_QSORT -- cmp_cache_name_compare sorts primarily
4252 * on filename and secondarily on stage, and (name, stage #) are a
4253 * unique tuple.
4255 QSORT(index->cache, index->cache_nr, cmp_cache_name_compare);
4257 return errs;
4260 void merge_switch_to_result(struct merge_options *opt,
4261 struct tree *head,
4262 struct merge_result *result,
4263 int update_worktree_and_index,
4264 int display_update_msgs)
4266 assert(opt->priv == NULL);
4267 if (result->clean >= 0 && update_worktree_and_index) {
4268 const char *filename;
4269 FILE *fp;
4271 trace2_region_enter("merge", "checkout", opt->repo);
4272 if (checkout(opt, head, result->tree)) {
4273 /* failure to function */
4274 result->clean = -1;
4275 return;
4277 trace2_region_leave("merge", "checkout", opt->repo);
4279 trace2_region_enter("merge", "record_conflicted", opt->repo);
4280 opt->priv = result->priv;
4281 if (record_conflicted_index_entries(opt)) {
4282 /* failure to function */
4283 opt->priv = NULL;
4284 result->clean = -1;
4285 return;
4287 opt->priv = NULL;
4288 trace2_region_leave("merge", "record_conflicted", opt->repo);
4290 trace2_region_enter("merge", "write_auto_merge", opt->repo);
4291 filename = git_path_auto_merge(opt->repo);
4292 fp = xfopen(filename, "w");
4293 fprintf(fp, "%s\n", oid_to_hex(&result->tree->object.oid));
4294 fclose(fp);
4295 trace2_region_leave("merge", "write_auto_merge", opt->repo);
4298 if (display_update_msgs) {
4299 struct merge_options_internal *opti = result->priv;
4300 struct hashmap_iter iter;
4301 struct strmap_entry *e;
4302 struct string_list olist = STRING_LIST_INIT_NODUP;
4303 int i;
4305 if (opt->record_conflict_msgs_as_headers)
4306 BUG("Either display conflict messages or record them as headers, not both");
4308 trace2_region_enter("merge", "display messages", opt->repo);
4310 /* Hack to pre-allocate olist to the desired size */
4311 ALLOC_GROW(olist.items, strmap_get_size(&opti->output),
4312 olist.alloc);
4314 /* Put every entry from output into olist, then sort */
4315 strmap_for_each_entry(&opti->output, &iter, e) {
4316 string_list_append(&olist, e->key)->util = e->value;
4318 string_list_sort(&olist);
4320 /* Iterate over the items, printing them */
4321 for (i = 0; i < olist.nr; ++i) {
4322 struct strbuf *sb = olist.items[i].util;
4324 printf("%s", sb->buf);
4326 string_list_clear(&olist, 0);
4328 /* Also include needed rename limit adjustment now */
4329 diff_warn_rename_limit("merge.renamelimit",
4330 opti->renames.needed_limit, 0);
4332 trace2_region_leave("merge", "display messages", opt->repo);
4335 merge_finalize(opt, result);
4338 void merge_finalize(struct merge_options *opt,
4339 struct merge_result *result)
4341 struct merge_options_internal *opti = result->priv;
4343 if (opt->renormalize)
4344 git_attr_set_direction(GIT_ATTR_CHECKIN);
4345 assert(opt->priv == NULL);
4347 clear_or_reinit_internal_opts(opti, 0);
4348 FREE_AND_NULL(opti);
4351 /*** Function Grouping: helper functions for merge_incore_*() ***/
4353 static struct tree *shift_tree_object(struct repository *repo,
4354 struct tree *one, struct tree *two,
4355 const char *subtree_shift)
4357 struct object_id shifted;
4359 if (!*subtree_shift) {
4360 shift_tree(repo, &one->object.oid, &two->object.oid, &shifted, 0);
4361 } else {
4362 shift_tree_by(repo, &one->object.oid, &two->object.oid, &shifted,
4363 subtree_shift);
4365 if (oideq(&two->object.oid, &shifted))
4366 return two;
4367 return lookup_tree(repo, &shifted);
4370 static inline void set_commit_tree(struct commit *c, struct tree *t)
4372 c->maybe_tree = t;
4375 static struct commit *make_virtual_commit(struct repository *repo,
4376 struct tree *tree,
4377 const char *comment)
4379 struct commit *commit = alloc_commit_node(repo);
4381 set_merge_remote_desc(commit, comment, (struct object *)commit);
4382 set_commit_tree(commit, tree);
4383 commit->object.parsed = 1;
4384 return commit;
4387 static void merge_start(struct merge_options *opt, struct merge_result *result)
4389 struct rename_info *renames;
4390 int i;
4391 struct mem_pool *pool = NULL;
4393 /* Sanity checks on opt */
4394 trace2_region_enter("merge", "sanity checks", opt->repo);
4395 assert(opt->repo);
4397 assert(opt->branch1 && opt->branch2);
4399 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
4400 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
4401 assert(opt->rename_limit >= -1);
4402 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
4403 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
4405 assert(opt->xdl_opts >= 0);
4406 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
4407 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
4409 if (opt->msg_header_prefix)
4410 assert(opt->record_conflict_msgs_as_headers);
4413 * detect_renames, verbosity, buffer_output, and obuf are ignored
4414 * fields that were used by "recursive" rather than "ort" -- but
4415 * sanity check them anyway.
4417 assert(opt->detect_renames >= -1 &&
4418 opt->detect_renames <= DIFF_DETECT_COPY);
4419 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
4420 assert(opt->buffer_output <= 2);
4421 assert(opt->obuf.len == 0);
4423 assert(opt->priv == NULL);
4424 if (result->_properly_initialized != 0 &&
4425 result->_properly_initialized != RESULT_INITIALIZED)
4426 BUG("struct merge_result passed to merge_incore_*recursive() must be zeroed or filled with values from a previous run");
4427 assert(!!result->priv == !!result->_properly_initialized);
4428 if (result->priv) {
4429 opt->priv = result->priv;
4430 result->priv = NULL;
4432 * opt->priv non-NULL means we had results from a previous
4433 * run; do a few sanity checks that user didn't mess with
4434 * it in an obvious fashion.
4436 assert(opt->priv->call_depth == 0);
4437 assert(!opt->priv->toplevel_dir ||
4438 0 == strlen(opt->priv->toplevel_dir));
4440 trace2_region_leave("merge", "sanity checks", opt->repo);
4442 /* Default to histogram diff. Actually, just hardcode it...for now. */
4443 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
4445 /* Handle attr direction stuff for renormalization */
4446 if (opt->renormalize)
4447 git_attr_set_direction(GIT_ATTR_CHECKOUT);
4449 /* Initialization of opt->priv, our internal merge data */
4450 trace2_region_enter("merge", "allocate/init", opt->repo);
4451 if (opt->priv) {
4452 clear_or_reinit_internal_opts(opt->priv, 1);
4453 trace2_region_leave("merge", "allocate/init", opt->repo);
4454 return;
4456 opt->priv = xcalloc(1, sizeof(*opt->priv));
4458 /* Initialization of various renames fields */
4459 renames = &opt->priv->renames;
4460 mem_pool_init(&opt->priv->pool, 0);
4461 pool = &opt->priv->pool;
4462 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; i++) {
4463 strintmap_init_with_options(&renames->dirs_removed[i],
4464 NOT_RELEVANT, pool, 0);
4465 strmap_init_with_options(&renames->dir_rename_count[i],
4466 NULL, 1);
4467 strmap_init_with_options(&renames->dir_renames[i],
4468 NULL, 0);
4470 * relevant_sources uses -1 for the default, because we need
4471 * to be able to distinguish not-in-strintmap from valid
4472 * relevant_source values from enum file_rename_relevance.
4473 * In particular, possibly_cache_new_pair() expects a negative
4474 * value for not-found entries.
4476 strintmap_init_with_options(&renames->relevant_sources[i],
4477 -1 /* explicitly invalid */,
4478 pool, 0);
4479 strmap_init_with_options(&renames->cached_pairs[i],
4480 NULL, 1);
4481 strset_init_with_options(&renames->cached_irrelevant[i],
4482 NULL, 1);
4483 strset_init_with_options(&renames->cached_target_names[i],
4484 NULL, 0);
4486 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; i++) {
4487 strintmap_init_with_options(&renames->deferred[i].possible_trivial_merges,
4488 0, pool, 0);
4489 strset_init_with_options(&renames->deferred[i].target_dirs,
4490 pool, 1);
4491 renames->deferred[i].trivial_merges_okay = 1; /* 1 == maybe */
4495 * Although we initialize opt->priv->paths with strdup_strings=0,
4496 * that's just to avoid making yet another copy of an allocated
4497 * string. Putting the entry into paths means we are taking
4498 * ownership, so we will later free it.
4500 * In contrast, conflicted just has a subset of keys from paths, so
4501 * we don't want to free those (it'd be a duplicate free).
4503 strmap_init_with_options(&opt->priv->paths, pool, 0);
4504 strmap_init_with_options(&opt->priv->conflicted, pool, 0);
4507 * keys & strbufs in output will sometimes need to outlive "paths",
4508 * so it will have a copy of relevant keys. It's probably a small
4509 * subset of the overall paths that have special output.
4511 strmap_init(&opt->priv->output);
4513 trace2_region_leave("merge", "allocate/init", opt->repo);
4516 static void merge_check_renames_reusable(struct merge_options *opt,
4517 struct merge_result *result,
4518 struct tree *merge_base,
4519 struct tree *side1,
4520 struct tree *side2)
4522 struct rename_info *renames;
4523 struct tree **merge_trees;
4524 struct merge_options_internal *opti = result->priv;
4526 if (!opti)
4527 return;
4529 renames = &opti->renames;
4530 merge_trees = renames->merge_trees;
4533 * Handle case where previous merge operation did not want cache to
4534 * take effect, e.g. because rename/rename(1to1) makes it invalid.
4536 if (!merge_trees[0]) {
4537 assert(!merge_trees[0] && !merge_trees[1] && !merge_trees[2]);
4538 renames->cached_pairs_valid_side = 0; /* neither side valid */
4539 return;
4543 * Handle other cases; note that merge_trees[0..2] will only
4544 * be NULL if opti is, or if all three were manually set to
4545 * NULL by e.g. rename/rename(1to1) handling.
4547 assert(merge_trees[0] && merge_trees[1] && merge_trees[2]);
4549 /* Check if we meet a condition for re-using cached_pairs */
4550 if (oideq(&merge_base->object.oid, &merge_trees[2]->object.oid) &&
4551 oideq(&side1->object.oid, &result->tree->object.oid))
4552 renames->cached_pairs_valid_side = MERGE_SIDE1;
4553 else if (oideq(&merge_base->object.oid, &merge_trees[1]->object.oid) &&
4554 oideq(&side2->object.oid, &result->tree->object.oid))
4555 renames->cached_pairs_valid_side = MERGE_SIDE2;
4556 else
4557 renames->cached_pairs_valid_side = 0; /* neither side valid */
4560 /*** Function Grouping: merge_incore_*() and their internal variants ***/
4563 * Originally from merge_trees_internal(); heavily adapted, though.
4565 static void merge_ort_nonrecursive_internal(struct merge_options *opt,
4566 struct tree *merge_base,
4567 struct tree *side1,
4568 struct tree *side2,
4569 struct merge_result *result)
4571 struct object_id working_tree_oid;
4573 if (opt->subtree_shift) {
4574 side2 = shift_tree_object(opt->repo, side1, side2,
4575 opt->subtree_shift);
4576 merge_base = shift_tree_object(opt->repo, side1, merge_base,
4577 opt->subtree_shift);
4580 redo:
4581 trace2_region_enter("merge", "collect_merge_info", opt->repo);
4582 if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
4584 * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
4585 * base, and 2-3) the trees for the two trees we're merging.
4587 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
4588 oid_to_hex(&merge_base->object.oid),
4589 oid_to_hex(&side1->object.oid),
4590 oid_to_hex(&side2->object.oid));
4591 result->clean = -1;
4592 return;
4594 trace2_region_leave("merge", "collect_merge_info", opt->repo);
4596 trace2_region_enter("merge", "renames", opt->repo);
4597 result->clean = detect_and_process_renames(opt, merge_base,
4598 side1, side2);
4599 trace2_region_leave("merge", "renames", opt->repo);
4600 if (opt->priv->renames.redo_after_renames == 2) {
4601 trace2_region_enter("merge", "reset_maps", opt->repo);
4602 clear_or_reinit_internal_opts(opt->priv, 1);
4603 trace2_region_leave("merge", "reset_maps", opt->repo);
4604 goto redo;
4607 trace2_region_enter("merge", "process_entries", opt->repo);
4608 process_entries(opt, &working_tree_oid);
4609 trace2_region_leave("merge", "process_entries", opt->repo);
4611 /* Set return values */
4612 result->path_messages = &opt->priv->output;
4613 result->tree = parse_tree_indirect(&working_tree_oid);
4614 /* existence of conflicted entries implies unclean */
4615 result->clean &= strmap_empty(&opt->priv->conflicted);
4616 if (!opt->priv->call_depth) {
4617 result->priv = opt->priv;
4618 result->_properly_initialized = RESULT_INITIALIZED;
4619 opt->priv = NULL;
4624 * Originally from merge_recursive_internal(); somewhat adapted, though.
4626 static void merge_ort_internal(struct merge_options *opt,
4627 struct commit_list *merge_bases,
4628 struct commit *h1,
4629 struct commit *h2,
4630 struct merge_result *result)
4632 struct commit *next;
4633 struct commit *merged_merge_bases;
4634 const char *ancestor_name;
4635 struct strbuf merge_base_abbrev = STRBUF_INIT;
4637 if (!merge_bases) {
4638 merge_bases = get_merge_bases(h1, h2);
4639 /* See merge-ort.h:merge_incore_recursive() declaration NOTE */
4640 merge_bases = reverse_commit_list(merge_bases);
4643 merged_merge_bases = pop_commit(&merge_bases);
4644 if (merged_merge_bases == NULL) {
4645 /* if there is no common ancestor, use an empty tree */
4646 struct tree *tree;
4648 tree = lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);
4649 merged_merge_bases = make_virtual_commit(opt->repo, tree,
4650 "ancestor");
4651 ancestor_name = "empty tree";
4652 } else if (merge_bases) {
4653 ancestor_name = "merged common ancestors";
4654 } else {
4655 strbuf_add_unique_abbrev(&merge_base_abbrev,
4656 &merged_merge_bases->object.oid,
4657 DEFAULT_ABBREV);
4658 ancestor_name = merge_base_abbrev.buf;
4661 for (next = pop_commit(&merge_bases); next;
4662 next = pop_commit(&merge_bases)) {
4663 const char *saved_b1, *saved_b2;
4664 struct commit *prev = merged_merge_bases;
4666 opt->priv->call_depth++;
4668 * When the merge fails, the result contains files
4669 * with conflict markers. The cleanness flag is
4670 * ignored (unless indicating an error), it was never
4671 * actually used, as result of merge_trees has always
4672 * overwritten it: the committed "conflicts" were
4673 * already resolved.
4675 saved_b1 = opt->branch1;
4676 saved_b2 = opt->branch2;
4677 opt->branch1 = "Temporary merge branch 1";
4678 opt->branch2 = "Temporary merge branch 2";
4679 merge_ort_internal(opt, NULL, prev, next, result);
4680 if (result->clean < 0)
4681 return;
4682 opt->branch1 = saved_b1;
4683 opt->branch2 = saved_b2;
4684 opt->priv->call_depth--;
4686 merged_merge_bases = make_virtual_commit(opt->repo,
4687 result->tree,
4688 "merged tree");
4689 commit_list_insert(prev, &merged_merge_bases->parents);
4690 commit_list_insert(next, &merged_merge_bases->parents->next);
4692 clear_or_reinit_internal_opts(opt->priv, 1);
4695 opt->ancestor = ancestor_name;
4696 merge_ort_nonrecursive_internal(opt,
4697 repo_get_commit_tree(opt->repo,
4698 merged_merge_bases),
4699 repo_get_commit_tree(opt->repo, h1),
4700 repo_get_commit_tree(opt->repo, h2),
4701 result);
4702 strbuf_release(&merge_base_abbrev);
4703 opt->ancestor = NULL; /* avoid accidental re-use of opt->ancestor */
4706 void merge_incore_nonrecursive(struct merge_options *opt,
4707 struct tree *merge_base,
4708 struct tree *side1,
4709 struct tree *side2,
4710 struct merge_result *result)
4712 trace2_region_enter("merge", "incore_nonrecursive", opt->repo);
4714 trace2_region_enter("merge", "merge_start", opt->repo);
4715 assert(opt->ancestor != NULL);
4716 merge_check_renames_reusable(opt, result, merge_base, side1, side2);
4717 merge_start(opt, result);
4719 * Record the trees used in this merge, so if there's a next merge in
4720 * a cherry-pick or rebase sequence it might be able to take advantage
4721 * of the cached_pairs in that next merge.
4723 opt->priv->renames.merge_trees[0] = merge_base;
4724 opt->priv->renames.merge_trees[1] = side1;
4725 opt->priv->renames.merge_trees[2] = side2;
4726 trace2_region_leave("merge", "merge_start", opt->repo);
4728 merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
4729 trace2_region_leave("merge", "incore_nonrecursive", opt->repo);
4732 void merge_incore_recursive(struct merge_options *opt,
4733 struct commit_list *merge_bases,
4734 struct commit *side1,
4735 struct commit *side2,
4736 struct merge_result *result)
4738 trace2_region_enter("merge", "incore_recursive", opt->repo);
4740 /* We set the ancestor label based on the merge_bases */
4741 assert(opt->ancestor == NULL);
4743 trace2_region_enter("merge", "merge_start", opt->repo);
4744 merge_start(opt, result);
4745 trace2_region_leave("merge", "merge_start", opt->repo);
4747 merge_ort_internal(opt, merge_bases, side1, side2, result);
4748 trace2_region_leave("merge", "incore_recursive", opt->repo);