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
6 * git merge [-s recursive]
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"?)
18 #include "merge-ort.h"
21 #include "cache-tree.h"
22 #include "commit-reach.h"
27 #include "object-store.h"
29 #include "submodule.h"
31 #include "unpack-trees.h"
32 #include "xdiff-interface.h"
35 * We have many arrays of size 3. Whenever we have such an array, the
36 * indices refer to one of the sides of the three-way merge. This is so
37 * pervasive that the constants 0, 1, and 2 are used in many places in the
38 * code (especially in arithmetic operations to find the other side's index
39 * or to compute a relevant mask), but sometimes these enum names are used
40 * to aid code clarity.
42 * See also 'filemask' and 'dirmask' in struct conflict_info; the "ith side"
43 * referred to there is one of these three sides.
51 struct merge_options_internal {
53 * paths: primary data structure in all of merge ort.
56 * * are full relative paths from the toplevel of the repository
57 * (e.g. "drivers/firmware/raspberrypi.c").
58 * * store all relevant paths in the repo, both directories and
59 * files (e.g. drivers, drivers/firmware would also be included)
60 * * these keys serve to intern all the path strings, which allows
61 * us to do pointer comparison on directory names instead of
62 * strcmp; we just have to be careful to use the interned strings.
63 * (Technically paths_to_free may track some strings that were
64 * removed from froms paths.)
66 * The values of paths:
67 * * either a pointer to a merged_info, or a conflict_info struct
68 * * merged_info contains all relevant information for a
69 * non-conflicted entry.
70 * * conflict_info contains a merged_info, plus any additional
71 * information about a conflict such as the higher orders stages
72 * involved and the names of the paths those came from (handy
73 * once renames get involved).
74 * * a path may start "conflicted" (i.e. point to a conflict_info)
75 * and then a later step (e.g. three-way content merge) determines
76 * it can be cleanly merged, at which point it'll be marked clean
77 * and the algorithm will ignore any data outside the contained
78 * merged_info for that entry
79 * * If an entry remains conflicted, the merged_info portion of a
80 * conflict_info will later be filled with whatever version of
81 * the file should be placed in the working directory (e.g. an
82 * as-merged-as-possible variation that contains conflict markers).
87 * conflicted: a subset of keys->values from "paths"
89 * conflicted is basically an optimization between process_entries()
90 * and record_conflicted_index_entries(); the latter could loop over
91 * ALL the entries in paths AGAIN and look for the ones that are
92 * still conflicted, but since process_entries() has to loop over
93 * all of them, it saves the ones it couldn't resolve in this strmap
94 * so that record_conflicted_index_entries() can iterate just the
97 struct strmap conflicted;
100 * paths_to_free: additional list of strings to free
102 * If keys are removed from "paths", they are added to paths_to_free
103 * to ensure they are later freed. We avoid free'ing immediately since
104 * other places (e.g. conflict_info.pathnames[]) may still be
105 * referencing these paths.
107 struct string_list paths_to_free;
110 * output: special messages and conflict notices for various paths
112 * This is a map of pathnames (a subset of the keys in "paths" above)
113 * to strbufs. It gathers various warning/conflict/notice messages
114 * for later processing.
116 struct strmap output;
119 * current_dir_name: temporary var used in collect_merge_info_callback()
121 * Used to set merged_info.directory_name; see documentation for that
122 * variable and the requirements placed on that field.
124 const char *current_dir_name;
126 /* call_depth: recursion level counter for merging merge bases */
130 struct version_info {
131 struct object_id oid;
136 /* if is_null, ignore result. otherwise result has oid & mode */
137 struct version_info result;
141 * clean: whether the path in question is cleanly merged.
143 * see conflict_info.merged for more details.
148 * basename_offset: offset of basename of path.
150 * perf optimization to avoid recomputing offset of final '/'
151 * character in pathname (0 if no '/' in pathname).
153 size_t basename_offset;
156 * directory_name: containing directory name.
158 * Note that we assume directory_name is constructed such that
159 * strcmp(dir1_name, dir2_name) == 0 iff dir1_name == dir2_name,
160 * i.e. string equality is equivalent to pointer equality. For this
161 * to hold, we have to be careful setting directory_name.
163 const char *directory_name;
166 struct conflict_info {
168 * merged: the version of the path that will be written to working tree
170 * WARNING: It is critical to check merged.clean and ensure it is 0
171 * before reading any conflict_info fields outside of merged.
172 * Allocated merge_info structs will always have clean set to 1.
173 * Allocated conflict_info structs will have merged.clean set to 0
174 * initially. The merged.clean field is how we know if it is safe
175 * to access other parts of conflict_info besides merged; if a
176 * conflict_info's merged.clean is changed to 1, the rest of the
177 * algorithm is not allowed to look at anything outside of the
178 * merged member anymore.
180 struct merged_info merged;
182 /* oids & modes from each of the three trees for this path */
183 struct version_info stages[3];
185 /* pathnames for each stage; may differ due to rename detection */
186 const char *pathnames[3];
188 /* Whether this path is/was involved in a directory/file conflict */
189 unsigned df_conflict:1;
192 * Whether this path is/was involved in a non-content conflict other
193 * than a directory/file conflict (e.g. rename/rename, rename/delete,
194 * file location based on possible directory rename).
196 unsigned path_conflict:1;
199 * For filemask and dirmask, the ith bit corresponds to whether the
200 * ith entry is a file (filemask) or a directory (dirmask). Thus,
201 * filemask & dirmask is always zero, and filemask | dirmask is at
202 * most 7 but can be less when a path does not appear as either a
203 * file or a directory on at least one side of history.
205 * Note that these masks are related to enum merge_side, as the ith
206 * entry corresponds to side i.
208 * These values come from a traverse_trees() call; more info may be
209 * found looking at tree-walk.h's struct traverse_info,
210 * particularly the documentation above the "fn" member (note that
211 * filemask = mask & ~dirmask from that documentation).
217 * Optimization to track which stages match, to avoid the need to
218 * recompute it in multiple steps. Either 0 or at least 2 bits are
219 * set; if at least 2 bits are set, their corresponding stages match.
221 unsigned match_mask:3;
224 /*** Function Grouping: various utility functions ***/
227 * For the next three macros, see warning for conflict_info.merged.
229 * In each of the below, mi is a struct merged_info*, and ci was defined
230 * as a struct conflict_info* (but we need to verify ci isn't actually
231 * pointed at a struct merged_info*).
233 * INITIALIZE_CI: Assign ci to mi but only if it's safe; set to NULL otherwise.
234 * VERIFY_CI: Ensure that something we assigned to a conflict_info* is one.
235 * ASSIGN_AND_VERIFY_CI: Similar to VERIFY_CI but do assignment first.
237 #define INITIALIZE_CI(ci, mi) do { \
238 (ci) = (!(mi) || (mi)->clean) ? NULL : (struct conflict_info *)(mi); \
240 #define VERIFY_CI(ci) assert(ci && !ci->merged.clean);
241 #define ASSIGN_AND_VERIFY_CI(ci, mi) do { \
242 (ci) = (struct conflict_info *)(mi); \
243 assert((ci) && !(mi)->clean); \
246 static void free_strmap_strings(struct strmap *map)
248 struct hashmap_iter iter;
249 struct strmap_entry *entry;
251 strmap_for_each_entry(map, &iter, entry) {
252 free((char*)entry->key);
256 static void clear_internal_opts(struct merge_options_internal *opti,
259 assert(!reinitialize);
262 * We marked opti->paths with strdup_strings = 0, so that we
263 * wouldn't have to make another copy of the fullpath created by
264 * make_traverse_path from setup_path_info(). But, now that we've
265 * used it and have no other references to these strings, it is time
266 * to deallocate them.
268 free_strmap_strings(&opti->paths);
269 strmap_clear(&opti->paths, 1);
272 * All keys and values in opti->conflicted are a subset of those in
273 * opti->paths. We don't want to deallocate anything twice, so we
274 * don't free the keys and we pass 0 for free_values.
276 strmap_clear(&opti->conflicted, 0);
279 * opti->paths_to_free is similar to opti->paths; we created it with
280 * strdup_strings = 0 to avoid making _another_ copy of the fullpath
281 * but now that we've used it and have no other references to these
282 * strings, it is time to deallocate them. We do so by temporarily
283 * setting strdup_strings to 1.
285 opti->paths_to_free.strdup_strings = 1;
286 string_list_clear(&opti->paths_to_free, 0);
287 opti->paths_to_free.strdup_strings = 0;
290 struct hashmap_iter iter;
291 struct strmap_entry *e;
293 /* Release and free each strbuf found in output */
294 strmap_for_each_entry(&opti->output, &iter, e) {
295 struct strbuf *sb = e->value;
298 * While strictly speaking we don't need to free(sb)
299 * here because we could pass free_values=1 when
300 * calling strmap_clear() on opti->output, that would
301 * require strmap_clear to do another
302 * strmap_for_each_entry() loop, so we just free it
303 * while we're iterating anyway.
307 strmap_clear(&opti->output, 0);
311 static int err(struct merge_options *opt, const char *err, ...)
314 struct strbuf sb = STRBUF_INIT;
316 strbuf_addstr(&sb, "error: ");
317 va_start(params, err);
318 strbuf_vaddf(&sb, err, params);
327 static void format_commit(struct strbuf *sb,
329 struct commit *commit)
331 struct merge_remote_desc *desc;
332 struct pretty_print_context ctx = {0};
333 ctx.abbrev = DEFAULT_ABBREV;
335 strbuf_addchars(sb, ' ', indent);
336 desc = merge_remote_util(commit);
338 strbuf_addf(sb, "virtual %s\n", desc->name);
342 format_commit_message(commit, "%h %s", sb, &ctx);
343 strbuf_addch(sb, '\n');
346 __attribute__((format (printf, 4, 5)))
347 static void path_msg(struct merge_options *opt,
349 int omittable_hint, /* skippable under --remerge-diff */
350 const char *fmt, ...)
353 struct strbuf *sb = strmap_get(&opt->priv->output, path);
355 sb = xmalloc(sizeof(*sb));
357 strmap_put(&opt->priv->output, path, sb);
361 strbuf_vaddf(sb, fmt, ap);
364 strbuf_addch(sb, '\n');
367 /* add a string to a strbuf, but converting "/" to "_" */
368 static void add_flattened_path(struct strbuf *out, const char *s)
371 strbuf_addstr(out, s);
372 for (; i < out->len; i++)
373 if (out->buf[i] == '/')
377 static char *unique_path(struct strmap *existing_paths,
381 struct strbuf newpath = STRBUF_INIT;
385 strbuf_addf(&newpath, "%s~", path);
386 add_flattened_path(&newpath, branch);
388 base_len = newpath.len;
389 while (strmap_contains(existing_paths, newpath.buf)) {
390 strbuf_setlen(&newpath, base_len);
391 strbuf_addf(&newpath, "_%d", suffix++);
394 return strbuf_detach(&newpath, NULL);
397 /*** Function Grouping: functions related to collect_merge_info() ***/
399 static void setup_path_info(struct merge_options *opt,
400 struct string_list_item *result,
401 const char *current_dir_name,
402 int current_dir_name_len,
403 char *fullpath, /* we'll take over ownership */
404 struct name_entry *names,
405 struct name_entry *merged_version,
406 unsigned is_null, /* boolean */
407 unsigned df_conflict, /* boolean */
410 int resolved /* boolean */)
412 /* result->util is void*, so mi is a convenience typed variable */
413 struct merged_info *mi;
415 assert(!is_null || resolved);
416 assert(!df_conflict || !resolved); /* df_conflict implies !resolved */
417 assert(resolved == (merged_version != NULL));
419 mi = xcalloc(1, resolved ? sizeof(struct merged_info) :
420 sizeof(struct conflict_info));
421 mi->directory_name = current_dir_name;
422 mi->basename_offset = current_dir_name_len;
423 mi->clean = !!resolved;
425 mi->result.mode = merged_version->mode;
426 oidcpy(&mi->result.oid, &merged_version->oid);
427 mi->is_null = !!is_null;
430 struct conflict_info *ci;
432 ASSIGN_AND_VERIFY_CI(ci, mi);
433 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
434 ci->pathnames[i] = fullpath;
435 ci->stages[i].mode = names[i].mode;
436 oidcpy(&ci->stages[i].oid, &names[i].oid);
438 ci->filemask = filemask;
439 ci->dirmask = dirmask;
440 ci->df_conflict = !!df_conflict;
443 * Assume is_null for now, but if we have entries
444 * under the directory then when it is complete in
445 * write_completed_directory() it'll update this.
446 * Also, for D/F conflicts, we have to handle the
447 * directory first, then clear this bit and process
448 * the file to see how it is handled -- that occurs
449 * near the top of process_entry().
453 strmap_put(&opt->priv->paths, fullpath, mi);
454 result->string = fullpath;
458 static int collect_merge_info_callback(int n,
460 unsigned long dirmask,
461 struct name_entry *names,
462 struct traverse_info *info)
466 * common ancestor (mbase) has mask 1, and stored in index 0 of names
467 * head of side 1 (side1) has mask 2, and stored in index 1 of names
468 * head of side 2 (side2) has mask 4, and stored in index 2 of names
470 struct merge_options *opt = info->data;
471 struct merge_options_internal *opti = opt->priv;
472 struct string_list_item pi; /* Path Info */
473 struct conflict_info *ci; /* typed alias to pi.util (which is void*) */
474 struct name_entry *p;
477 const char *dirname = opti->current_dir_name;
478 unsigned filemask = mask & ~dirmask;
479 unsigned match_mask = 0; /* will be updated below */
480 unsigned mbase_null = !(mask & 1);
481 unsigned side1_null = !(mask & 2);
482 unsigned side2_null = !(mask & 4);
483 unsigned side1_matches_mbase = (!side1_null && !mbase_null &&
484 names[0].mode == names[1].mode &&
485 oideq(&names[0].oid, &names[1].oid));
486 unsigned side2_matches_mbase = (!side2_null && !mbase_null &&
487 names[0].mode == names[2].mode &&
488 oideq(&names[0].oid, &names[2].oid));
489 unsigned sides_match = (!side1_null && !side2_null &&
490 names[1].mode == names[2].mode &&
491 oideq(&names[1].oid, &names[2].oid));
494 * Note: When a path is a file on one side of history and a directory
495 * in another, we have a directory/file conflict. In such cases, if
496 * the conflict doesn't resolve from renames and deletions, then we
497 * always leave directories where they are and move files out of the
498 * way. Thus, while struct conflict_info has a df_conflict field to
499 * track such conflicts, we ignore that field for any directories at
500 * a path and only pay attention to it for files at the given path.
501 * The fact that we leave directories were they are also means that
502 * we do not need to worry about getting additional df_conflict
503 * information propagated from parent directories down to children
504 * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
505 * sets a newinfo.df_conflicts field specifically to propagate it).
507 unsigned df_conflict = (filemask != 0) && (dirmask != 0);
509 /* n = 3 is a fundamental assumption. */
511 BUG("Called collect_merge_info_callback wrong");
514 * A bunch of sanity checks verifying that traverse_trees() calls
515 * us the way I expect. Could just remove these at some point,
516 * though maybe they are helpful to future code readers.
518 assert(mbase_null == is_null_oid(&names[0].oid));
519 assert(side1_null == is_null_oid(&names[1].oid));
520 assert(side2_null == is_null_oid(&names[2].oid));
521 assert(!mbase_null || !side1_null || !side2_null);
522 assert(mask > 0 && mask < 8);
524 /* Determine match_mask */
525 if (side1_matches_mbase)
526 match_mask = (side2_matches_mbase ? 7 : 3);
527 else if (side2_matches_mbase)
529 else if (sides_match)
533 * Get the name of the relevant filepath, which we'll pass to
534 * setup_path_info() for tracking.
539 len = traverse_path_len(info, p->pathlen);
541 /* +1 in both of the following lines to include the NUL byte */
542 fullpath = xmalloc(len + 1);
543 make_traverse_path(fullpath, len + 1, info, p->path, p->pathlen);
546 * If mbase, side1, and side2 all match, we can resolve early. Even
547 * if these are trees, there will be no renames or anything
550 if (side1_matches_mbase && side2_matches_mbase) {
551 /* mbase, side1, & side2 all match; use mbase as resolution */
552 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
553 names, names+0, mbase_null, 0,
554 filemask, dirmask, 1);
559 * Record information about the path so we can resolve later in
562 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
563 names, NULL, 0, df_conflict, filemask, dirmask, 0);
567 ci->match_mask = match_mask;
569 /* If dirmask, recurse into subdirectories */
571 struct traverse_info newinfo;
572 struct tree_desc t[3];
573 void *buf[3] = {NULL, NULL, NULL};
574 const char *original_dir_name;
577 ci->match_mask &= filemask;
580 newinfo.name = p->path;
581 newinfo.namelen = p->pathlen;
582 newinfo.pathlen = st_add3(newinfo.pathlen, p->pathlen, 1);
584 * If this directory we are about to recurse into cared about
585 * its parent directory (the current directory) having a D/F
586 * conflict, then we'd propagate the masks in this way:
587 * newinfo.df_conflicts |= (mask & ~dirmask);
588 * But we don't worry about propagating D/F conflicts. (See
589 * comment near setting of local df_conflict variable near
590 * the beginning of this function).
593 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
594 if (i == 1 && side1_matches_mbase)
596 else if (i == 2 && side2_matches_mbase)
598 else if (i == 2 && sides_match)
601 const struct object_id *oid = NULL;
604 buf[i] = fill_tree_descriptor(opt->repo,
610 original_dir_name = opti->current_dir_name;
611 opti->current_dir_name = pi.string;
612 ret = traverse_trees(NULL, 3, t, &newinfo);
613 opti->current_dir_name = original_dir_name;
615 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
625 static int collect_merge_info(struct merge_options *opt,
626 struct tree *merge_base,
631 struct tree_desc t[3];
632 struct traverse_info info;
633 const char *toplevel_dir_placeholder = "";
635 opt->priv->current_dir_name = toplevel_dir_placeholder;
636 setup_traverse_info(&info, toplevel_dir_placeholder);
637 info.fn = collect_merge_info_callback;
639 info.show_all_errors = 1;
641 parse_tree(merge_base);
644 init_tree_desc(t + 0, merge_base->buffer, merge_base->size);
645 init_tree_desc(t + 1, side1->buffer, side1->size);
646 init_tree_desc(t + 2, side2->buffer, side2->size);
648 ret = traverse_trees(NULL, 3, t, &info);
653 /*** Function Grouping: functions related to threeway content merges ***/
655 static int find_first_merges(struct repository *repo,
659 struct object_array *result)
661 die("Not yet implemented.");
664 static int merge_submodule(struct merge_options *opt,
666 const struct object_id *o,
667 const struct object_id *a,
668 const struct object_id *b,
669 struct object_id *result)
671 struct commit *commit_o, *commit_a, *commit_b;
673 struct object_array merges;
674 struct strbuf sb = STRBUF_INIT;
677 int search = !opt->priv->call_depth;
679 /* store fallback answer in result in case we fail */
680 oidcpy(result, opt->priv->call_depth ? o : a);
682 /* we can not handle deletion conflicts */
690 if (add_submodule_odb(path)) {
691 path_msg(opt, path, 0,
692 _("Failed to merge submodule %s (not checked out)"),
697 if (!(commit_o = lookup_commit_reference(opt->repo, o)) ||
698 !(commit_a = lookup_commit_reference(opt->repo, a)) ||
699 !(commit_b = lookup_commit_reference(opt->repo, b))) {
700 path_msg(opt, path, 0,
701 _("Failed to merge submodule %s (commits not present)"),
706 /* check whether both changes are forward */
707 if (!in_merge_bases(commit_o, commit_a) ||
708 !in_merge_bases(commit_o, commit_b)) {
709 path_msg(opt, path, 0,
710 _("Failed to merge submodule %s "
711 "(commits don't follow merge-base)"),
716 /* Case #1: a is contained in b or vice versa */
717 if (in_merge_bases(commit_a, commit_b)) {
719 path_msg(opt, path, 1,
720 _("Note: Fast-forwarding submodule %s to %s"),
721 path, oid_to_hex(b));
724 if (in_merge_bases(commit_b, commit_a)) {
726 path_msg(opt, path, 1,
727 _("Note: Fast-forwarding submodule %s to %s"),
728 path, oid_to_hex(a));
733 * Case #2: There are one or more merges that contain a and b in
734 * the submodule. If there is only one, then present it as a
735 * suggestion to the user, but leave it marked unmerged so the
736 * user needs to confirm the resolution.
739 /* Skip the search if makes no sense to the calling context. */
743 /* find commit which merges them */
744 parent_count = find_first_merges(opt->repo, path, commit_a, commit_b,
746 switch (parent_count) {
748 path_msg(opt, path, 0, _("Failed to merge submodule %s"), path);
752 format_commit(&sb, 4,
753 (struct commit *)merges.objects[0].item);
754 path_msg(opt, path, 0,
755 _("Failed to merge submodule %s, but a possible merge "
756 "resolution exists:\n%s\n"),
758 path_msg(opt, path, 1,
759 _("If this is correct simply add it to the index "
762 " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
763 "which will accept this suggestion.\n"),
764 oid_to_hex(&merges.objects[0].item->oid), path);
768 for (i = 0; i < merges.nr; i++)
769 format_commit(&sb, 4,
770 (struct commit *)merges.objects[i].item);
771 path_msg(opt, path, 0,
772 _("Failed to merge submodule %s, but multiple "
773 "possible merges exist:\n%s"), path, sb.buf);
777 object_array_clear(&merges);
781 static int merge_3way(struct merge_options *opt,
783 const struct object_id *o,
784 const struct object_id *a,
785 const struct object_id *b,
786 const char *pathnames[3],
787 const int extra_marker_size,
788 mmbuffer_t *result_buf)
790 mmfile_t orig, src1, src2;
791 struct ll_merge_options ll_opts = {0};
792 char *base, *name1, *name2;
795 ll_opts.renormalize = opt->renormalize;
796 ll_opts.extra_marker_size = extra_marker_size;
797 ll_opts.xdl_opts = opt->xdl_opts;
799 if (opt->priv->call_depth) {
800 ll_opts.virtual_ancestor = 1;
803 switch (opt->recursive_variant) {
804 case MERGE_VARIANT_OURS:
805 ll_opts.variant = XDL_MERGE_FAVOR_OURS;
807 case MERGE_VARIANT_THEIRS:
808 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
816 assert(pathnames[0] && pathnames[1] && pathnames[2] && opt->ancestor);
817 if (pathnames[0] == pathnames[1] && pathnames[1] == pathnames[2]) {
818 base = mkpathdup("%s", opt->ancestor);
819 name1 = mkpathdup("%s", opt->branch1);
820 name2 = mkpathdup("%s", opt->branch2);
822 base = mkpathdup("%s:%s", opt->ancestor, pathnames[0]);
823 name1 = mkpathdup("%s:%s", opt->branch1, pathnames[1]);
824 name2 = mkpathdup("%s:%s", opt->branch2, pathnames[2]);
827 read_mmblob(&orig, o);
828 read_mmblob(&src1, a);
829 read_mmblob(&src2, b);
831 merge_status = ll_merge(result_buf, path, &orig, base,
832 &src1, name1, &src2, name2,
833 opt->repo->index, &ll_opts);
844 static int handle_content_merge(struct merge_options *opt,
846 const struct version_info *o,
847 const struct version_info *a,
848 const struct version_info *b,
849 const char *pathnames[3],
850 const int extra_marker_size,
851 struct version_info *result)
854 * path is the target location where we want to put the file, and
855 * is used to determine any normalization rules in ll_merge.
857 * The normal case is that path and all entries in pathnames are
858 * identical, though renames can affect which path we got one of
859 * the three blobs to merge on various sides of history.
861 * extra_marker_size is the amount to extend conflict markers in
862 * ll_merge; this is neeed if we have content merges of content
863 * merges, which happens for example with rename/rename(2to1) and
864 * rename/add conflicts.
869 * handle_content_merge() needs both files to be of the same type, i.e.
870 * both files OR both submodules OR both symlinks. Conflicting types
871 * needs to be handled elsewhere.
873 assert((S_IFMT & a->mode) == (S_IFMT & b->mode));
876 if (a->mode == b->mode || a->mode == o->mode)
877 result->mode = b->mode;
879 /* must be the 100644/100755 case */
880 assert(S_ISREG(a->mode));
881 result->mode = a->mode;
882 clean = (b->mode == o->mode);
884 * FIXME: If opt->priv->call_depth && !clean, then we really
885 * should not make result->mode match either a->mode or
886 * b->mode; that causes t6036 "check conflicting mode for
887 * regular file" to fail. It would be best to use some other
888 * mode, but we'll confuse all kinds of stuff if we use one
889 * where S_ISREG(result->mode) isn't true, and if we use
890 * something like 0100666, then tree-walk.c's calls to
891 * canon_mode() will just normalize that to 100644 for us and
892 * thus not solve anything.
894 * Figure out if there's some kind of way we can work around
902 * Note: While one might assume that the next four lines would
903 * be unnecessary due to the fact that match_mask is often
904 * setup and already handled, renames don't always take care
907 if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
908 oidcpy(&result->oid, &b->oid);
909 else if (oideq(&b->oid, &o->oid))
910 oidcpy(&result->oid, &a->oid);
912 /* Remaining rules depend on file vs. submodule vs. symlink. */
913 else if (S_ISREG(a->mode)) {
914 mmbuffer_t result_buf;
915 int ret = 0, merge_status;
919 * If 'o' is different type, treat it as null so we do a
922 two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
924 merge_status = merge_3way(opt, path,
925 two_way ? &null_oid : &o->oid,
927 pathnames, extra_marker_size,
930 if ((merge_status < 0) || !result_buf.ptr)
931 ret = err(opt, _("Failed to execute internal merge"));
934 write_object_file(result_buf.ptr, result_buf.size,
935 blob_type, &result->oid))
936 ret = err(opt, _("Unable to add %s to database"),
939 free(result_buf.ptr);
942 clean &= (merge_status == 0);
943 path_msg(opt, path, 1, _("Auto-merging %s"), path);
944 } else if (S_ISGITLINK(a->mode)) {
945 int two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
946 clean = merge_submodule(opt, pathnames[0],
947 two_way ? &null_oid : &o->oid,
948 &a->oid, &b->oid, &result->oid);
949 if (opt->priv->call_depth && two_way && !clean) {
950 result->mode = o->mode;
951 oidcpy(&result->oid, &o->oid);
953 } else if (S_ISLNK(a->mode)) {
954 if (opt->priv->call_depth) {
956 result->mode = o->mode;
957 oidcpy(&result->oid, &o->oid);
959 switch (opt->recursive_variant) {
960 case MERGE_VARIANT_NORMAL:
962 oidcpy(&result->oid, &a->oid);
964 case MERGE_VARIANT_OURS:
965 oidcpy(&result->oid, &a->oid);
967 case MERGE_VARIANT_THEIRS:
968 oidcpy(&result->oid, &b->oid);
973 BUG("unsupported object type in the tree: %06o for %s",
979 /*** Function Grouping: functions related to detect_and_process_renames(), ***
980 *** which are split into directory and regular rename detection sections. ***/
982 /*** Function Grouping: functions related to directory rename detection ***/
984 /*** Function Grouping: functions related to regular rename detection ***/
986 static int detect_and_process_renames(struct merge_options *opt,
987 struct tree *merge_base,
994 * Rename detection works by detecting file similarity. Here we use
995 * a really easy-to-implement scheme: files are similar IFF they have
996 * the same filename. Therefore, by this scheme, there are no renames.
998 * TODO: Actually implement a real rename detection scheme.
1003 /*** Function Grouping: functions related to process_entries() ***/
1005 static int string_list_df_name_compare(const char *one, const char *two)
1007 int onelen = strlen(one);
1008 int twolen = strlen(two);
1010 * Here we only care that entries for D/F conflicts are
1011 * adjacent, in particular with the file of the D/F conflict
1012 * appearing before files below the corresponding directory.
1013 * The order of the rest of the list is irrelevant for us.
1015 * To achieve this, we sort with df_name_compare and provide
1016 * the mode S_IFDIR so that D/F conflicts will sort correctly.
1017 * We use the mode S_IFDIR for everything else for simplicity,
1018 * since in other cases any changes in their order due to
1019 * sorting cause no problems for us.
1021 int cmp = df_name_compare(one, onelen, S_IFDIR,
1022 two, twolen, S_IFDIR);
1024 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
1025 * that 'foo' comes before 'foo/bar'.
1029 return onelen - twolen;
1032 struct directory_versions {
1034 * versions: list of (basename -> version_info)
1036 * The basenames are in reverse lexicographic order of full pathnames,
1037 * as processed in process_entries(). This puts all entries within
1038 * a directory together, and covers the directory itself after
1039 * everything within it, allowing us to write subtrees before needing
1040 * to record information for the tree itself.
1042 struct string_list versions;
1045 * offsets: list of (full relative path directories -> integer offsets)
1047 * Since versions contains basenames from files in multiple different
1048 * directories, we need to know which entries in versions correspond
1049 * to which directories. Values of e.g.
1053 * Would mean that entries 0-1 of versions are files in the toplevel
1054 * directory, entries 2-4 are files under src/, and the remaining
1055 * entries starting at index 5 are files under src/moduleA/.
1057 struct string_list offsets;
1060 * last_directory: directory that previously processed file found in
1062 * last_directory starts NULL, but records the directory in which the
1063 * previous file was found within. As soon as
1064 * directory(current_file) != last_directory
1065 * then we need to start updating accounting in versions & offsets.
1066 * Note that last_directory is always the last path in "offsets" (or
1067 * NULL if "offsets" is empty) so this exists just for quick access.
1069 const char *last_directory;
1071 /* last_directory_len: cached computation of strlen(last_directory) */
1072 unsigned last_directory_len;
1075 static int tree_entry_order(const void *a_, const void *b_)
1077 const struct string_list_item *a = a_;
1078 const struct string_list_item *b = b_;
1080 const struct merged_info *ami = a->util;
1081 const struct merged_info *bmi = b->util;
1082 return base_name_compare(a->string, strlen(a->string), ami->result.mode,
1083 b->string, strlen(b->string), bmi->result.mode);
1086 static void write_tree(struct object_id *result_oid,
1087 struct string_list *versions,
1088 unsigned int offset,
1091 size_t maxlen = 0, extra;
1092 unsigned int nr = versions->nr - offset;
1093 struct strbuf buf = STRBUF_INIT;
1094 struct string_list relevant_entries = STRING_LIST_INIT_NODUP;
1098 * We want to sort the last (versions->nr-offset) entries in versions.
1099 * Do so by abusing the string_list API a bit: make another string_list
1100 * that contains just those entries and then sort them.
1102 * We won't use relevant_entries again and will let it just pop off the
1103 * stack, so there won't be allocation worries or anything.
1105 relevant_entries.items = versions->items + offset;
1106 relevant_entries.nr = versions->nr - offset;
1107 QSORT(relevant_entries.items, relevant_entries.nr, tree_entry_order);
1109 /* Pre-allocate some space in buf */
1110 extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
1111 for (i = 0; i < nr; i++) {
1112 maxlen += strlen(versions->items[offset+i].string) + extra;
1114 strbuf_grow(&buf, maxlen);
1116 /* Write each entry out to buf */
1117 for (i = 0; i < nr; i++) {
1118 struct merged_info *mi = versions->items[offset+i].util;
1119 struct version_info *ri = &mi->result;
1120 strbuf_addf(&buf, "%o %s%c",
1122 versions->items[offset+i].string, '\0');
1123 strbuf_add(&buf, ri->oid.hash, hash_size);
1126 /* Write this object file out, and record in result_oid */
1127 write_object_file(buf.buf, buf.len, tree_type, result_oid);
1128 strbuf_release(&buf);
1131 static void record_entry_for_tree(struct directory_versions *dir_metadata,
1133 struct merged_info *mi)
1135 const char *basename;
1138 /* nothing to record */
1141 basename = path + mi->basename_offset;
1142 assert(strchr(basename, '/') == NULL);
1143 string_list_append(&dir_metadata->versions,
1144 basename)->util = &mi->result;
1147 static void write_completed_directory(struct merge_options *opt,
1148 const char *new_directory_name,
1149 struct directory_versions *info)
1151 const char *prev_dir;
1152 struct merged_info *dir_info = NULL;
1153 unsigned int offset;
1156 * Some explanation of info->versions and info->offsets...
1158 * process_entries() iterates over all relevant files AND
1159 * directories in reverse lexicographic order, and calls this
1160 * function. Thus, an example of the paths that process_entries()
1161 * could operate on (along with the directories for those paths
1166 * src/moduleB/umm.c src/moduleB
1167 * src/moduleB/stuff.h src/moduleB
1168 * src/moduleB/baz.c src/moduleB
1170 * src/moduleA/foo.c src/moduleA
1171 * src/moduleA/bar.c src/moduleA
1178 * always contains the unprocessed entries and their
1179 * version_info information. For example, after the first five
1180 * entries above, info->versions would be:
1182 * xtract.c <xtract.c's version_info>
1183 * token.txt <token.txt's version_info>
1184 * umm.c <src/moduleB/umm.c's version_info>
1185 * stuff.h <src/moduleB/stuff.h's version_info>
1186 * baz.c <src/moduleB/baz.c's version_info>
1188 * Once a subdirectory is completed we remove the entries in
1189 * that subdirectory from info->versions, writing it as a tree
1190 * (write_tree()). Thus, as soon as we get to src/moduleB,
1191 * info->versions would be updated to
1193 * xtract.c <xtract.c's version_info>
1194 * token.txt <token.txt's version_info>
1195 * moduleB <src/moduleB's version_info>
1199 * helps us track which entries in info->versions correspond to
1200 * which directories. When we are N directories deep (e.g. 4
1201 * for src/modA/submod/subdir/), we have up to N+1 unprocessed
1202 * directories (+1 because of toplevel dir). Corresponding to
1203 * the info->versions example above, after processing five entries
1204 * info->offsets will be:
1209 * which is used to know that xtract.c & token.txt are from the
1210 * toplevel dirctory, while umm.c & stuff.h & baz.c are from the
1211 * src/moduleB directory. Again, following the example above,
1212 * once we need to process src/moduleB, then info->offsets is
1218 * which says that moduleB (and only moduleB so far) is in the
1221 * One unique thing to note about info->offsets here is that
1222 * "src" was not added to info->offsets until there was a path
1223 * (a file OR directory) immediately below src/ that got
1226 * Since process_entry() just appends new entries to info->versions,
1227 * write_completed_directory() only needs to do work if the next path
1228 * is in a directory that is different than the last directory found
1233 * If we are working with the same directory as the last entry, there
1234 * is no work to do. (See comments above the directory_name member of
1235 * struct merged_info for why we can use pointer comparison instead of
1238 if (new_directory_name == info->last_directory)
1242 * If we are just starting (last_directory is NULL), or last_directory
1243 * is a prefix of the current directory, then we can just update
1244 * info->offsets to record the offset where we started this directory
1245 * and update last_directory to have quick access to it.
1247 if (info->last_directory == NULL ||
1248 !strncmp(new_directory_name, info->last_directory,
1249 info->last_directory_len)) {
1250 uintptr_t offset = info->versions.nr;
1252 info->last_directory = new_directory_name;
1253 info->last_directory_len = strlen(info->last_directory);
1255 * Record the offset into info->versions where we will
1256 * start recording basenames of paths found within
1257 * new_directory_name.
1259 string_list_append(&info->offsets,
1260 info->last_directory)->util = (void*)offset;
1265 * The next entry that will be processed will be within
1266 * new_directory_name. Since at this point we know that
1267 * new_directory_name is within a different directory than
1268 * info->last_directory, we have all entries for info->last_directory
1269 * in info->versions and we need to create a tree object for them.
1271 dir_info = strmap_get(&opt->priv->paths, info->last_directory);
1273 offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
1274 if (offset == info->versions.nr) {
1276 * Actually, we don't need to create a tree object in this
1277 * case. Whenever all files within a directory disappear
1278 * during the merge (e.g. unmodified on one side and
1279 * deleted on the other, or files were renamed elsewhere),
1280 * then we get here and the directory itself needs to be
1281 * omitted from its parent tree as well.
1283 dir_info->is_null = 1;
1286 * Write out the tree to the git object directory, and also
1287 * record the mode and oid in dir_info->result.
1289 dir_info->is_null = 0;
1290 dir_info->result.mode = S_IFDIR;
1291 write_tree(&dir_info->result.oid, &info->versions, offset,
1292 opt->repo->hash_algo->rawsz);
1296 * We've now used several entries from info->versions and one entry
1297 * from info->offsets, so we get rid of those values.
1300 info->versions.nr = offset;
1303 * Now we've taken care of the completed directory, but we need to
1304 * prepare things since future entries will be in
1305 * new_directory_name. (In particular, process_entry() will be
1306 * appending new entries to info->versions.) So, we need to make
1307 * sure new_directory_name is the last entry in info->offsets.
1309 prev_dir = info->offsets.nr == 0 ? NULL :
1310 info->offsets.items[info->offsets.nr-1].string;
1311 if (new_directory_name != prev_dir) {
1312 uintptr_t c = info->versions.nr;
1313 string_list_append(&info->offsets,
1314 new_directory_name)->util = (void*)c;
1317 /* And, of course, we need to update last_directory to match. */
1318 info->last_directory = new_directory_name;
1319 info->last_directory_len = strlen(info->last_directory);
1322 /* Per entry merge function */
1323 static void process_entry(struct merge_options *opt,
1325 struct conflict_info *ci,
1326 struct directory_versions *dir_metadata)
1328 int df_file_index = 0;
1331 assert(ci->filemask >= 0 && ci->filemask <= 7);
1332 /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
1333 assert(ci->match_mask == 0 || ci->match_mask == 3 ||
1334 ci->match_mask == 5 || ci->match_mask == 6);
1337 record_entry_for_tree(dir_metadata, path, &ci->merged);
1338 if (ci->filemask == 0)
1339 /* nothing else to handle */
1341 assert(ci->df_conflict);
1344 if (ci->df_conflict && ci->merged.result.mode == 0) {
1348 * directory no longer in the way, but we do have a file we
1349 * need to place here so we need to clean away the "directory
1350 * merges to nothing" result.
1352 ci->df_conflict = 0;
1353 assert(ci->filemask != 0);
1354 ci->merged.clean = 0;
1355 ci->merged.is_null = 0;
1356 /* and we want to zero out any directory-related entries */
1357 ci->match_mask = (ci->match_mask & ~ci->dirmask);
1359 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1360 if (ci->filemask & (1 << i))
1362 ci->stages[i].mode = 0;
1363 oidcpy(&ci->stages[i].oid, &null_oid);
1365 } else if (ci->df_conflict && ci->merged.result.mode != 0) {
1367 * This started out as a D/F conflict, and the entries in
1368 * the competing directory were not removed by the merge as
1369 * evidenced by write_completed_directory() writing a value
1370 * to ci->merged.result.mode.
1372 struct conflict_info *new_ci;
1374 const char *old_path = path;
1377 assert(ci->merged.result.mode == S_IFDIR);
1380 * If filemask is 1, we can just ignore the file as having
1381 * been deleted on both sides. We do not want to overwrite
1382 * ci->merged.result, since it stores the tree for all the
1385 if (ci->filemask == 1) {
1391 * This file still exists on at least one side, and we want
1392 * the directory to remain here, so we need to move this
1393 * path to some new location.
1395 new_ci = xcalloc(1, sizeof(*new_ci));
1396 /* We don't really want new_ci->merged.result copied, but it'll
1397 * be overwritten below so it doesn't matter. We also don't
1398 * want any directory mode/oid values copied, but we'll zero
1399 * those out immediately. We do want the rest of ci copied.
1401 memcpy(new_ci, ci, sizeof(*ci));
1402 new_ci->match_mask = (new_ci->match_mask & ~new_ci->dirmask);
1403 new_ci->dirmask = 0;
1404 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1405 if (new_ci->filemask & (1 << i))
1407 /* zero out any entries related to directories */
1408 new_ci->stages[i].mode = 0;
1409 oidcpy(&new_ci->stages[i].oid, &null_oid);
1413 * Find out which side this file came from; note that we
1414 * cannot just use ci->filemask, because renames could cause
1415 * the filemask to go back to 7. So we use dirmask, then
1416 * pick the opposite side's index.
1418 df_file_index = (ci->dirmask & (1 << 1)) ? 2 : 1;
1419 branch = (df_file_index == 1) ? opt->branch1 : opt->branch2;
1420 path = unique_path(&opt->priv->paths, path, branch);
1421 strmap_put(&opt->priv->paths, path, new_ci);
1423 path_msg(opt, path, 0,
1424 _("CONFLICT (file/directory): directory in the way "
1425 "of %s from %s; moving it to %s instead."),
1426 old_path, branch, path);
1429 * Zero out the filemask for the old ci. At this point, ci
1430 * was just an entry for a directory, so we don't need to
1431 * do anything more with it.
1436 * Now note that we're working on the new entry (path was
1443 * NOTE: Below there is a long switch-like if-elseif-elseif... block
1444 * which the code goes through even for the df_conflict cases
1447 if (ci->match_mask) {
1448 ci->merged.clean = 1;
1449 if (ci->match_mask == 6) {
1450 /* stages[1] == stages[2] */
1451 ci->merged.result.mode = ci->stages[1].mode;
1452 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
1454 /* determine the mask of the side that didn't match */
1455 unsigned int othermask = 7 & ~ci->match_mask;
1456 int side = (othermask == 4) ? 2 : 1;
1458 ci->merged.result.mode = ci->stages[side].mode;
1459 ci->merged.is_null = !ci->merged.result.mode;
1460 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1462 assert(othermask == 2 || othermask == 4);
1463 assert(ci->merged.is_null ==
1464 (ci->filemask == ci->match_mask));
1466 } else if (ci->filemask >= 6 &&
1467 (S_IFMT & ci->stages[1].mode) !=
1468 (S_IFMT & ci->stages[2].mode)) {
1470 * Two different items from (file/submodule/symlink)
1472 die("Not yet implemented.");
1473 } else if (ci->filemask >= 6) {
1474 /* Need a two-way or three-way content merge */
1475 struct version_info merged_file;
1476 unsigned clean_merge;
1477 struct version_info *o = &ci->stages[0];
1478 struct version_info *a = &ci->stages[1];
1479 struct version_info *b = &ci->stages[2];
1481 clean_merge = handle_content_merge(opt, path, o, a, b,
1483 opt->priv->call_depth * 2,
1485 ci->merged.clean = clean_merge &&
1486 !ci->df_conflict && !ci->path_conflict;
1487 ci->merged.result.mode = merged_file.mode;
1488 ci->merged.is_null = (merged_file.mode == 0);
1489 oidcpy(&ci->merged.result.oid, &merged_file.oid);
1490 if (clean_merge && ci->df_conflict) {
1491 assert(df_file_index == 1 || df_file_index == 2);
1492 ci->filemask = 1 << df_file_index;
1493 ci->stages[df_file_index].mode = merged_file.mode;
1494 oidcpy(&ci->stages[df_file_index].oid, &merged_file.oid);
1497 const char *reason = _("content");
1498 if (ci->filemask == 6)
1499 reason = _("add/add");
1500 if (S_ISGITLINK(merged_file.mode))
1501 reason = _("submodule");
1502 path_msg(opt, path, 0,
1503 _("CONFLICT (%s): Merge conflict in %s"),
1506 } else if (ci->filemask == 3 || ci->filemask == 5) {
1508 const char *modify_branch, *delete_branch;
1509 int side = (ci->filemask == 5) ? 2 : 1;
1510 int index = opt->priv->call_depth ? 0 : side;
1512 ci->merged.result.mode = ci->stages[index].mode;
1513 oidcpy(&ci->merged.result.oid, &ci->stages[index].oid);
1514 ci->merged.clean = 0;
1516 modify_branch = (side == 1) ? opt->branch1 : opt->branch2;
1517 delete_branch = (side == 1) ? opt->branch2 : opt->branch1;
1519 path_msg(opt, path, 0,
1520 _("CONFLICT (modify/delete): %s deleted in %s "
1521 "and modified in %s. Version %s of %s left "
1523 path, delete_branch, modify_branch,
1524 modify_branch, path);
1525 } else if (ci->filemask == 2 || ci->filemask == 4) {
1526 /* Added on one side */
1527 int side = (ci->filemask == 4) ? 2 : 1;
1528 ci->merged.result.mode = ci->stages[side].mode;
1529 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1530 ci->merged.clean = !ci->df_conflict;
1531 } else if (ci->filemask == 1) {
1532 /* Deleted on both sides */
1533 ci->merged.is_null = 1;
1534 ci->merged.result.mode = 0;
1535 oidcpy(&ci->merged.result.oid, &null_oid);
1536 ci->merged.clean = 1;
1540 * If still conflicted, record it separately. This allows us to later
1541 * iterate over just conflicted entries when updating the index instead
1542 * of iterating over all entries.
1544 if (!ci->merged.clean)
1545 strmap_put(&opt->priv->conflicted, path, ci);
1546 record_entry_for_tree(dir_metadata, path, &ci->merged);
1549 static void process_entries(struct merge_options *opt,
1550 struct object_id *result_oid)
1552 struct hashmap_iter iter;
1553 struct strmap_entry *e;
1554 struct string_list plist = STRING_LIST_INIT_NODUP;
1555 struct string_list_item *entry;
1556 struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
1557 STRING_LIST_INIT_NODUP,
1560 if (strmap_empty(&opt->priv->paths)) {
1561 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
1565 /* Hack to pre-allocate plist to the desired size */
1566 ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
1568 /* Put every entry from paths into plist, then sort */
1569 strmap_for_each_entry(&opt->priv->paths, &iter, e) {
1570 string_list_append(&plist, e->key)->util = e->value;
1572 plist.cmp = string_list_df_name_compare;
1573 string_list_sort(&plist);
1576 * Iterate over the items in reverse order, so we can handle paths
1577 * below a directory before needing to handle the directory itself.
1579 * This allows us to write subtrees before we need to write trees,
1580 * and it also enables sane handling of directory/file conflicts
1581 * (because it allows us to know whether the directory is still in
1582 * the way when it is time to process the file at the same path).
1584 for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
1585 char *path = entry->string;
1587 * NOTE: mi may actually be a pointer to a conflict_info, but
1588 * we have to check mi->clean first to see if it's safe to
1589 * reassign to such a pointer type.
1591 struct merged_info *mi = entry->util;
1593 write_completed_directory(opt, mi->directory_name,
1596 record_entry_for_tree(&dir_metadata, path, mi);
1598 struct conflict_info *ci = (struct conflict_info *)mi;
1599 process_entry(opt, path, ci, &dir_metadata);
1603 if (dir_metadata.offsets.nr != 1 ||
1604 (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
1605 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
1606 dir_metadata.offsets.nr);
1607 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
1608 (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
1610 BUG("dir_metadata accounting completely off; shouldn't happen");
1612 write_tree(result_oid, &dir_metadata.versions, 0,
1613 opt->repo->hash_algo->rawsz);
1614 string_list_clear(&plist, 0);
1615 string_list_clear(&dir_metadata.versions, 0);
1616 string_list_clear(&dir_metadata.offsets, 0);
1619 /*** Function Grouping: functions related to merge_switch_to_result() ***/
1621 static int checkout(struct merge_options *opt,
1625 /* Switch the index/working copy from old to new */
1627 struct tree_desc trees[2];
1628 struct unpack_trees_options unpack_opts;
1630 memset(&unpack_opts, 0, sizeof(unpack_opts));
1631 unpack_opts.head_idx = -1;
1632 unpack_opts.src_index = opt->repo->index;
1633 unpack_opts.dst_index = opt->repo->index;
1635 setup_unpack_trees_porcelain(&unpack_opts, "merge");
1638 * NOTE: if this were just "git checkout" code, we would probably
1639 * read or refresh the cache and check for a conflicted index, but
1640 * builtin/merge.c or sequencer.c really needs to read the index
1641 * and check for conflicted entries before starting merging for a
1642 * good user experience (no sense waiting for merges/rebases before
1643 * erroring out), so there's no reason to duplicate that work here.
1646 /* 2-way merge to the new branch */
1647 unpack_opts.update = 1;
1648 unpack_opts.merge = 1;
1649 unpack_opts.quiet = 0; /* FIXME: sequencer might want quiet? */
1650 unpack_opts.verbose_update = (opt->verbosity > 2);
1651 unpack_opts.fn = twoway_merge;
1652 if (1/* FIXME: opts->overwrite_ignore*/) {
1653 unpack_opts.dir = xcalloc(1, sizeof(*unpack_opts.dir));
1654 unpack_opts.dir->flags |= DIR_SHOW_IGNORED;
1655 setup_standard_excludes(unpack_opts.dir);
1658 init_tree_desc(&trees[0], prev->buffer, prev->size);
1660 init_tree_desc(&trees[1], next->buffer, next->size);
1662 ret = unpack_trees(2, trees, &unpack_opts);
1663 clear_unpack_trees_porcelain(&unpack_opts);
1664 dir_clear(unpack_opts.dir);
1665 FREE_AND_NULL(unpack_opts.dir);
1669 static int record_conflicted_index_entries(struct merge_options *opt,
1670 struct index_state *index,
1671 struct strmap *paths,
1672 struct strmap *conflicted)
1674 struct hashmap_iter iter;
1675 struct strmap_entry *e;
1677 int original_cache_nr;
1679 if (strmap_empty(conflicted))
1682 original_cache_nr = index->cache_nr;
1684 /* Put every entry from paths into plist, then sort */
1685 strmap_for_each_entry(conflicted, &iter, e) {
1686 const char *path = e->key;
1687 struct conflict_info *ci = e->value;
1689 struct cache_entry *ce;
1695 * The index will already have a stage=0 entry for this path,
1696 * because we created an as-merged-as-possible version of the
1697 * file and checkout() moved the working copy and index over
1700 * However, previous iterations through this loop will have
1701 * added unstaged entries to the end of the cache which
1702 * ignore the standard alphabetical ordering of cache
1703 * entries and break invariants needed for index_name_pos()
1704 * to work. However, we know the entry we want is before
1705 * those appended cache entries, so do a temporary swap on
1706 * cache_nr to only look through entries of interest.
1708 SWAP(index->cache_nr, original_cache_nr);
1709 pos = index_name_pos(index, path, strlen(path));
1710 SWAP(index->cache_nr, original_cache_nr);
1712 if (ci->filemask != 1)
1713 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path);
1714 cache_tree_invalidate_path(index, path);
1716 ce = index->cache[pos];
1719 * Clean paths with CE_SKIP_WORKTREE set will not be
1720 * written to the working tree by the unpack_trees()
1721 * call in checkout(). Our conflicted entries would
1722 * have appeared clean to that code since we ignored
1723 * the higher order stages. Thus, we need override
1724 * the CE_SKIP_WORKTREE bit and manually write those
1725 * files to the working disk here.
1727 * TODO: Implement this CE_SKIP_WORKTREE fixup.
1731 * Mark this cache entry for removal and instead add
1732 * new stage>0 entries corresponding to the
1733 * conflicts. If there are many conflicted entries, we
1734 * want to avoid memmove'ing O(NM) entries by
1735 * inserting the new entries one at a time. So,
1736 * instead, we just add the new cache entries to the
1737 * end (ignoring normal index requirements on sort
1738 * order) and sort the index once we're all done.
1740 ce->ce_flags |= CE_REMOVE;
1743 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1744 struct version_info *vi;
1745 if (!(ci->filemask & (1ul << i)))
1747 vi = &ci->stages[i];
1748 ce = make_cache_entry(index, vi->mode, &vi->oid,
1750 add_index_entry(index, ce, ADD_CACHE_JUST_APPEND);
1755 * Remove the unused cache entries (and invalidate the relevant
1756 * cache-trees), then sort the index entries to get the conflicted
1757 * entries we added to the end into their right locations.
1759 remove_marked_cache_entries(index, 1);
1760 QSORT(index->cache, index->cache_nr, cmp_cache_name_compare);
1765 void merge_switch_to_result(struct merge_options *opt,
1767 struct merge_result *result,
1768 int update_worktree_and_index,
1769 int display_update_msgs)
1771 assert(opt->priv == NULL);
1772 if (result->clean >= 0 && update_worktree_and_index) {
1773 struct merge_options_internal *opti = result->priv;
1775 if (checkout(opt, head, result->tree)) {
1776 /* failure to function */
1781 if (record_conflicted_index_entries(opt, opt->repo->index,
1783 &opti->conflicted)) {
1784 /* failure to function */
1790 if (display_update_msgs) {
1791 struct merge_options_internal *opti = result->priv;
1792 struct hashmap_iter iter;
1793 struct strmap_entry *e;
1794 struct string_list olist = STRING_LIST_INIT_NODUP;
1797 /* Hack to pre-allocate olist to the desired size */
1798 ALLOC_GROW(olist.items, strmap_get_size(&opti->output),
1801 /* Put every entry from output into olist, then sort */
1802 strmap_for_each_entry(&opti->output, &iter, e) {
1803 string_list_append(&olist, e->key)->util = e->value;
1805 string_list_sort(&olist);
1807 /* Iterate over the items, printing them */
1808 for (i = 0; i < olist.nr; ++i) {
1809 struct strbuf *sb = olist.items[i].util;
1811 printf("%s", sb->buf);
1813 string_list_clear(&olist, 0);
1816 merge_finalize(opt, result);
1819 void merge_finalize(struct merge_options *opt,
1820 struct merge_result *result)
1822 struct merge_options_internal *opti = result->priv;
1824 assert(opt->priv == NULL);
1826 clear_internal_opts(opti, 0);
1827 FREE_AND_NULL(opti);
1830 /*** Function Grouping: helper functions for merge_incore_*() ***/
1832 static void merge_start(struct merge_options *opt, struct merge_result *result)
1834 /* Sanity checks on opt */
1837 assert(opt->branch1 && opt->branch2);
1839 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
1840 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
1841 assert(opt->rename_limit >= -1);
1842 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
1843 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
1845 assert(opt->xdl_opts >= 0);
1846 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
1847 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
1850 * detect_renames, verbosity, buffer_output, and obuf are ignored
1851 * fields that were used by "recursive" rather than "ort" -- but
1852 * sanity check them anyway.
1854 assert(opt->detect_renames >= -1 &&
1855 opt->detect_renames <= DIFF_DETECT_COPY);
1856 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
1857 assert(opt->buffer_output <= 2);
1858 assert(opt->obuf.len == 0);
1860 assert(opt->priv == NULL);
1862 /* Default to histogram diff. Actually, just hardcode it...for now. */
1863 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
1865 /* Initialization of opt->priv, our internal merge data */
1866 opt->priv = xcalloc(1, sizeof(*opt->priv));
1869 * Although we initialize opt->priv->paths with strdup_strings=0,
1870 * that's just to avoid making yet another copy of an allocated
1871 * string. Putting the entry into paths means we are taking
1872 * ownership, so we will later free it. paths_to_free is similar.
1874 * In contrast, conflicted just has a subset of keys from paths, so
1875 * we don't want to free those (it'd be a duplicate free).
1877 strmap_init_with_options(&opt->priv->paths, NULL, 0);
1878 strmap_init_with_options(&opt->priv->conflicted, NULL, 0);
1879 string_list_init(&opt->priv->paths_to_free, 0);
1882 * keys & strbufs in output will sometimes need to outlive "paths",
1883 * so it will have a copy of relevant keys. It's probably a small
1884 * subset of the overall paths that have special output.
1886 strmap_init(&opt->priv->output);
1889 /*** Function Grouping: merge_incore_*() and their internal variants ***/
1892 * Originally from merge_trees_internal(); heavily adapted, though.
1894 static void merge_ort_nonrecursive_internal(struct merge_options *opt,
1895 struct tree *merge_base,
1898 struct merge_result *result)
1900 struct object_id working_tree_oid;
1902 if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
1904 * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
1905 * base, and 2-3) the trees for the two trees we're merging.
1907 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
1908 oid_to_hex(&merge_base->object.oid),
1909 oid_to_hex(&side1->object.oid),
1910 oid_to_hex(&side2->object.oid));
1915 result->clean = detect_and_process_renames(opt, merge_base,
1917 process_entries(opt, &working_tree_oid);
1919 /* Set return values */
1920 result->tree = parse_tree_indirect(&working_tree_oid);
1921 /* existence of conflicted entries implies unclean */
1922 result->clean &= strmap_empty(&opt->priv->conflicted);
1923 if (!opt->priv->call_depth) {
1924 result->priv = opt->priv;
1929 void merge_incore_nonrecursive(struct merge_options *opt,
1930 struct tree *merge_base,
1933 struct merge_result *result)
1935 assert(opt->ancestor != NULL);
1936 merge_start(opt, result);
1937 merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
1940 void merge_incore_recursive(struct merge_options *opt,
1941 struct commit_list *merge_bases,
1942 struct commit *side1,
1943 struct commit *side2,
1944 struct merge_result *result)
1946 die("Not yet implemented");