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 die("Not yet implemented.");
334 __attribute__((format (printf, 4, 5)))
335 static void path_msg(struct merge_options *opt,
337 int omittable_hint, /* skippable under --remerge-diff */
338 const char *fmt, ...)
341 struct strbuf *sb = strmap_get(&opt->priv->output, path);
343 sb = xmalloc(sizeof(*sb));
345 strmap_put(&opt->priv->output, path, sb);
349 strbuf_vaddf(sb, fmt, ap);
352 strbuf_addch(sb, '\n');
355 /* add a string to a strbuf, but converting "/" to "_" */
356 static void add_flattened_path(struct strbuf *out, const char *s)
359 strbuf_addstr(out, s);
360 for (; i < out->len; i++)
361 if (out->buf[i] == '/')
365 static char *unique_path(struct strmap *existing_paths,
369 struct strbuf newpath = STRBUF_INIT;
373 strbuf_addf(&newpath, "%s~", path);
374 add_flattened_path(&newpath, branch);
376 base_len = newpath.len;
377 while (strmap_contains(existing_paths, newpath.buf)) {
378 strbuf_setlen(&newpath, base_len);
379 strbuf_addf(&newpath, "_%d", suffix++);
382 return strbuf_detach(&newpath, NULL);
385 /*** Function Grouping: functions related to collect_merge_info() ***/
387 static void setup_path_info(struct merge_options *opt,
388 struct string_list_item *result,
389 const char *current_dir_name,
390 int current_dir_name_len,
391 char *fullpath, /* we'll take over ownership */
392 struct name_entry *names,
393 struct name_entry *merged_version,
394 unsigned is_null, /* boolean */
395 unsigned df_conflict, /* boolean */
398 int resolved /* boolean */)
400 /* result->util is void*, so mi is a convenience typed variable */
401 struct merged_info *mi;
403 assert(!is_null || resolved);
404 assert(!df_conflict || !resolved); /* df_conflict implies !resolved */
405 assert(resolved == (merged_version != NULL));
407 mi = xcalloc(1, resolved ? sizeof(struct merged_info) :
408 sizeof(struct conflict_info));
409 mi->directory_name = current_dir_name;
410 mi->basename_offset = current_dir_name_len;
411 mi->clean = !!resolved;
413 mi->result.mode = merged_version->mode;
414 oidcpy(&mi->result.oid, &merged_version->oid);
415 mi->is_null = !!is_null;
418 struct conflict_info *ci;
420 ASSIGN_AND_VERIFY_CI(ci, mi);
421 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
422 ci->pathnames[i] = fullpath;
423 ci->stages[i].mode = names[i].mode;
424 oidcpy(&ci->stages[i].oid, &names[i].oid);
426 ci->filemask = filemask;
427 ci->dirmask = dirmask;
428 ci->df_conflict = !!df_conflict;
431 * Assume is_null for now, but if we have entries
432 * under the directory then when it is complete in
433 * write_completed_directory() it'll update this.
434 * Also, for D/F conflicts, we have to handle the
435 * directory first, then clear this bit and process
436 * the file to see how it is handled -- that occurs
437 * near the top of process_entry().
441 strmap_put(&opt->priv->paths, fullpath, mi);
442 result->string = fullpath;
446 static int collect_merge_info_callback(int n,
448 unsigned long dirmask,
449 struct name_entry *names,
450 struct traverse_info *info)
454 * common ancestor (mbase) has mask 1, and stored in index 0 of names
455 * head of side 1 (side1) has mask 2, and stored in index 1 of names
456 * head of side 2 (side2) has mask 4, and stored in index 2 of names
458 struct merge_options *opt = info->data;
459 struct merge_options_internal *opti = opt->priv;
460 struct string_list_item pi; /* Path Info */
461 struct conflict_info *ci; /* typed alias to pi.util (which is void*) */
462 struct name_entry *p;
465 const char *dirname = opti->current_dir_name;
466 unsigned filemask = mask & ~dirmask;
467 unsigned match_mask = 0; /* will be updated below */
468 unsigned mbase_null = !(mask & 1);
469 unsigned side1_null = !(mask & 2);
470 unsigned side2_null = !(mask & 4);
471 unsigned side1_matches_mbase = (!side1_null && !mbase_null &&
472 names[0].mode == names[1].mode &&
473 oideq(&names[0].oid, &names[1].oid));
474 unsigned side2_matches_mbase = (!side2_null && !mbase_null &&
475 names[0].mode == names[2].mode &&
476 oideq(&names[0].oid, &names[2].oid));
477 unsigned sides_match = (!side1_null && !side2_null &&
478 names[1].mode == names[2].mode &&
479 oideq(&names[1].oid, &names[2].oid));
482 * Note: When a path is a file on one side of history and a directory
483 * in another, we have a directory/file conflict. In such cases, if
484 * the conflict doesn't resolve from renames and deletions, then we
485 * always leave directories where they are and move files out of the
486 * way. Thus, while struct conflict_info has a df_conflict field to
487 * track such conflicts, we ignore that field for any directories at
488 * a path and only pay attention to it for files at the given path.
489 * The fact that we leave directories were they are also means that
490 * we do not need to worry about getting additional df_conflict
491 * information propagated from parent directories down to children
492 * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
493 * sets a newinfo.df_conflicts field specifically to propagate it).
495 unsigned df_conflict = (filemask != 0) && (dirmask != 0);
497 /* n = 3 is a fundamental assumption. */
499 BUG("Called collect_merge_info_callback wrong");
502 * A bunch of sanity checks verifying that traverse_trees() calls
503 * us the way I expect. Could just remove these at some point,
504 * though maybe they are helpful to future code readers.
506 assert(mbase_null == is_null_oid(&names[0].oid));
507 assert(side1_null == is_null_oid(&names[1].oid));
508 assert(side2_null == is_null_oid(&names[2].oid));
509 assert(!mbase_null || !side1_null || !side2_null);
510 assert(mask > 0 && mask < 8);
512 /* Determine match_mask */
513 if (side1_matches_mbase)
514 match_mask = (side2_matches_mbase ? 7 : 3);
515 else if (side2_matches_mbase)
517 else if (sides_match)
521 * Get the name of the relevant filepath, which we'll pass to
522 * setup_path_info() for tracking.
527 len = traverse_path_len(info, p->pathlen);
529 /* +1 in both of the following lines to include the NUL byte */
530 fullpath = xmalloc(len + 1);
531 make_traverse_path(fullpath, len + 1, info, p->path, p->pathlen);
534 * If mbase, side1, and side2 all match, we can resolve early. Even
535 * if these are trees, there will be no renames or anything
538 if (side1_matches_mbase && side2_matches_mbase) {
539 /* mbase, side1, & side2 all match; use mbase as resolution */
540 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
541 names, names+0, mbase_null, 0,
542 filemask, dirmask, 1);
547 * Record information about the path so we can resolve later in
550 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
551 names, NULL, 0, df_conflict, filemask, dirmask, 0);
555 ci->match_mask = match_mask;
557 /* If dirmask, recurse into subdirectories */
559 struct traverse_info newinfo;
560 struct tree_desc t[3];
561 void *buf[3] = {NULL, NULL, NULL};
562 const char *original_dir_name;
565 ci->match_mask &= filemask;
568 newinfo.name = p->path;
569 newinfo.namelen = p->pathlen;
570 newinfo.pathlen = st_add3(newinfo.pathlen, p->pathlen, 1);
572 * If this directory we are about to recurse into cared about
573 * its parent directory (the current directory) having a D/F
574 * conflict, then we'd propagate the masks in this way:
575 * newinfo.df_conflicts |= (mask & ~dirmask);
576 * But we don't worry about propagating D/F conflicts. (See
577 * comment near setting of local df_conflict variable near
578 * the beginning of this function).
581 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
582 if (i == 1 && side1_matches_mbase)
584 else if (i == 2 && side2_matches_mbase)
586 else if (i == 2 && sides_match)
589 const struct object_id *oid = NULL;
592 buf[i] = fill_tree_descriptor(opt->repo,
598 original_dir_name = opti->current_dir_name;
599 opti->current_dir_name = pi.string;
600 ret = traverse_trees(NULL, 3, t, &newinfo);
601 opti->current_dir_name = original_dir_name;
603 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
613 static int collect_merge_info(struct merge_options *opt,
614 struct tree *merge_base,
619 struct tree_desc t[3];
620 struct traverse_info info;
621 const char *toplevel_dir_placeholder = "";
623 opt->priv->current_dir_name = toplevel_dir_placeholder;
624 setup_traverse_info(&info, toplevel_dir_placeholder);
625 info.fn = collect_merge_info_callback;
627 info.show_all_errors = 1;
629 parse_tree(merge_base);
632 init_tree_desc(t + 0, merge_base->buffer, merge_base->size);
633 init_tree_desc(t + 1, side1->buffer, side1->size);
634 init_tree_desc(t + 2, side2->buffer, side2->size);
636 ret = traverse_trees(NULL, 3, t, &info);
641 /*** Function Grouping: functions related to threeway content merges ***/
643 static int find_first_merges(struct repository *repo,
647 struct object_array *result)
649 die("Not yet implemented.");
652 static int merge_submodule(struct merge_options *opt,
654 const struct object_id *o,
655 const struct object_id *a,
656 const struct object_id *b,
657 struct object_id *result)
659 struct commit *commit_o, *commit_a, *commit_b;
661 struct object_array merges;
662 struct strbuf sb = STRBUF_INIT;
665 int search = !opt->priv->call_depth;
667 /* store fallback answer in result in case we fail */
668 oidcpy(result, opt->priv->call_depth ? o : a);
670 /* we can not handle deletion conflicts */
678 if (add_submodule_odb(path)) {
679 path_msg(opt, path, 0,
680 _("Failed to merge submodule %s (not checked out)"),
685 if (!(commit_o = lookup_commit_reference(opt->repo, o)) ||
686 !(commit_a = lookup_commit_reference(opt->repo, a)) ||
687 !(commit_b = lookup_commit_reference(opt->repo, b))) {
688 path_msg(opt, path, 0,
689 _("Failed to merge submodule %s (commits not present)"),
694 /* check whether both changes are forward */
695 if (!in_merge_bases(commit_o, commit_a) ||
696 !in_merge_bases(commit_o, commit_b)) {
697 path_msg(opt, path, 0,
698 _("Failed to merge submodule %s "
699 "(commits don't follow merge-base)"),
704 /* Case #1: a is contained in b or vice versa */
705 if (in_merge_bases(commit_a, commit_b)) {
707 path_msg(opt, path, 1,
708 _("Note: Fast-forwarding submodule %s to %s"),
709 path, oid_to_hex(b));
712 if (in_merge_bases(commit_b, commit_a)) {
714 path_msg(opt, path, 1,
715 _("Note: Fast-forwarding submodule %s to %s"),
716 path, oid_to_hex(a));
721 * Case #2: There are one or more merges that contain a and b in
722 * the submodule. If there is only one, then present it as a
723 * suggestion to the user, but leave it marked unmerged so the
724 * user needs to confirm the resolution.
727 /* Skip the search if makes no sense to the calling context. */
731 /* find commit which merges them */
732 parent_count = find_first_merges(opt->repo, path, commit_a, commit_b,
734 switch (parent_count) {
736 path_msg(opt, path, 0, _("Failed to merge submodule %s"), path);
740 format_commit(&sb, 4,
741 (struct commit *)merges.objects[0].item);
742 path_msg(opt, path, 0,
743 _("Failed to merge submodule %s, but a possible merge "
744 "resolution exists:\n%s\n"),
746 path_msg(opt, path, 1,
747 _("If this is correct simply add it to the index "
750 " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
751 "which will accept this suggestion.\n"),
752 oid_to_hex(&merges.objects[0].item->oid), path);
756 for (i = 0; i < merges.nr; i++)
757 format_commit(&sb, 4,
758 (struct commit *)merges.objects[i].item);
759 path_msg(opt, path, 0,
760 _("Failed to merge submodule %s, but multiple "
761 "possible merges exist:\n%s"), path, sb.buf);
765 object_array_clear(&merges);
769 static int merge_3way(struct merge_options *opt,
771 const struct object_id *o,
772 const struct object_id *a,
773 const struct object_id *b,
774 const char *pathnames[3],
775 const int extra_marker_size,
776 mmbuffer_t *result_buf)
778 mmfile_t orig, src1, src2;
779 struct ll_merge_options ll_opts = {0};
780 char *base, *name1, *name2;
783 ll_opts.renormalize = opt->renormalize;
784 ll_opts.extra_marker_size = extra_marker_size;
785 ll_opts.xdl_opts = opt->xdl_opts;
787 if (opt->priv->call_depth) {
788 ll_opts.virtual_ancestor = 1;
791 switch (opt->recursive_variant) {
792 case MERGE_VARIANT_OURS:
793 ll_opts.variant = XDL_MERGE_FAVOR_OURS;
795 case MERGE_VARIANT_THEIRS:
796 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
804 assert(pathnames[0] && pathnames[1] && pathnames[2] && opt->ancestor);
805 if (pathnames[0] == pathnames[1] && pathnames[1] == pathnames[2]) {
806 base = mkpathdup("%s", opt->ancestor);
807 name1 = mkpathdup("%s", opt->branch1);
808 name2 = mkpathdup("%s", opt->branch2);
810 base = mkpathdup("%s:%s", opt->ancestor, pathnames[0]);
811 name1 = mkpathdup("%s:%s", opt->branch1, pathnames[1]);
812 name2 = mkpathdup("%s:%s", opt->branch2, pathnames[2]);
815 read_mmblob(&orig, o);
816 read_mmblob(&src1, a);
817 read_mmblob(&src2, b);
819 merge_status = ll_merge(result_buf, path, &orig, base,
820 &src1, name1, &src2, name2,
821 opt->repo->index, &ll_opts);
832 static int handle_content_merge(struct merge_options *opt,
834 const struct version_info *o,
835 const struct version_info *a,
836 const struct version_info *b,
837 const char *pathnames[3],
838 const int extra_marker_size,
839 struct version_info *result)
842 * path is the target location where we want to put the file, and
843 * is used to determine any normalization rules in ll_merge.
845 * The normal case is that path and all entries in pathnames are
846 * identical, though renames can affect which path we got one of
847 * the three blobs to merge on various sides of history.
849 * extra_marker_size is the amount to extend conflict markers in
850 * ll_merge; this is neeed if we have content merges of content
851 * merges, which happens for example with rename/rename(2to1) and
852 * rename/add conflicts.
857 * handle_content_merge() needs both files to be of the same type, i.e.
858 * both files OR both submodules OR both symlinks. Conflicting types
859 * needs to be handled elsewhere.
861 assert((S_IFMT & a->mode) == (S_IFMT & b->mode));
864 if (a->mode == b->mode || a->mode == o->mode)
865 result->mode = b->mode;
867 /* must be the 100644/100755 case */
868 assert(S_ISREG(a->mode));
869 result->mode = a->mode;
870 clean = (b->mode == o->mode);
872 * FIXME: If opt->priv->call_depth && !clean, then we really
873 * should not make result->mode match either a->mode or
874 * b->mode; that causes t6036 "check conflicting mode for
875 * regular file" to fail. It would be best to use some other
876 * mode, but we'll confuse all kinds of stuff if we use one
877 * where S_ISREG(result->mode) isn't true, and if we use
878 * something like 0100666, then tree-walk.c's calls to
879 * canon_mode() will just normalize that to 100644 for us and
880 * thus not solve anything.
882 * Figure out if there's some kind of way we can work around
890 * Note: While one might assume that the next four lines would
891 * be unnecessary due to the fact that match_mask is often
892 * setup and already handled, renames don't always take care
895 if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
896 oidcpy(&result->oid, &b->oid);
897 else if (oideq(&b->oid, &o->oid))
898 oidcpy(&result->oid, &a->oid);
900 /* Remaining rules depend on file vs. submodule vs. symlink. */
901 else if (S_ISREG(a->mode)) {
902 mmbuffer_t result_buf;
903 int ret = 0, merge_status;
907 * If 'o' is different type, treat it as null so we do a
910 two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
912 merge_status = merge_3way(opt, path,
913 two_way ? &null_oid : &o->oid,
915 pathnames, extra_marker_size,
918 if ((merge_status < 0) || !result_buf.ptr)
919 ret = err(opt, _("Failed to execute internal merge"));
922 write_object_file(result_buf.ptr, result_buf.size,
923 blob_type, &result->oid))
924 ret = err(opt, _("Unable to add %s to database"),
927 free(result_buf.ptr);
930 clean &= (merge_status == 0);
931 path_msg(opt, path, 1, _("Auto-merging %s"), path);
932 } else if (S_ISGITLINK(a->mode)) {
933 int two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
934 clean = merge_submodule(opt, pathnames[0],
935 two_way ? &null_oid : &o->oid,
936 &a->oid, &b->oid, &result->oid);
937 if (opt->priv->call_depth && two_way && !clean) {
938 result->mode = o->mode;
939 oidcpy(&result->oid, &o->oid);
941 } else if (S_ISLNK(a->mode)) {
942 if (opt->priv->call_depth) {
944 result->mode = o->mode;
945 oidcpy(&result->oid, &o->oid);
947 switch (opt->recursive_variant) {
948 case MERGE_VARIANT_NORMAL:
950 oidcpy(&result->oid, &a->oid);
952 case MERGE_VARIANT_OURS:
953 oidcpy(&result->oid, &a->oid);
955 case MERGE_VARIANT_THEIRS:
956 oidcpy(&result->oid, &b->oid);
961 BUG("unsupported object type in the tree: %06o for %s",
967 /*** Function Grouping: functions related to detect_and_process_renames(), ***
968 *** which are split into directory and regular rename detection sections. ***/
970 /*** Function Grouping: functions related to directory rename detection ***/
972 /*** Function Grouping: functions related to regular rename detection ***/
974 static int detect_and_process_renames(struct merge_options *opt,
975 struct tree *merge_base,
982 * Rename detection works by detecting file similarity. Here we use
983 * a really easy-to-implement scheme: files are similar IFF they have
984 * the same filename. Therefore, by this scheme, there are no renames.
986 * TODO: Actually implement a real rename detection scheme.
991 /*** Function Grouping: functions related to process_entries() ***/
993 static int string_list_df_name_compare(const char *one, const char *two)
995 int onelen = strlen(one);
996 int twolen = strlen(two);
998 * Here we only care that entries for D/F conflicts are
999 * adjacent, in particular with the file of the D/F conflict
1000 * appearing before files below the corresponding directory.
1001 * The order of the rest of the list is irrelevant for us.
1003 * To achieve this, we sort with df_name_compare and provide
1004 * the mode S_IFDIR so that D/F conflicts will sort correctly.
1005 * We use the mode S_IFDIR for everything else for simplicity,
1006 * since in other cases any changes in their order due to
1007 * sorting cause no problems for us.
1009 int cmp = df_name_compare(one, onelen, S_IFDIR,
1010 two, twolen, S_IFDIR);
1012 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
1013 * that 'foo' comes before 'foo/bar'.
1017 return onelen - twolen;
1020 struct directory_versions {
1022 * versions: list of (basename -> version_info)
1024 * The basenames are in reverse lexicographic order of full pathnames,
1025 * as processed in process_entries(). This puts all entries within
1026 * a directory together, and covers the directory itself after
1027 * everything within it, allowing us to write subtrees before needing
1028 * to record information for the tree itself.
1030 struct string_list versions;
1033 * offsets: list of (full relative path directories -> integer offsets)
1035 * Since versions contains basenames from files in multiple different
1036 * directories, we need to know which entries in versions correspond
1037 * to which directories. Values of e.g.
1041 * Would mean that entries 0-1 of versions are files in the toplevel
1042 * directory, entries 2-4 are files under src/, and the remaining
1043 * entries starting at index 5 are files under src/moduleA/.
1045 struct string_list offsets;
1048 * last_directory: directory that previously processed file found in
1050 * last_directory starts NULL, but records the directory in which the
1051 * previous file was found within. As soon as
1052 * directory(current_file) != last_directory
1053 * then we need to start updating accounting in versions & offsets.
1054 * Note that last_directory is always the last path in "offsets" (or
1055 * NULL if "offsets" is empty) so this exists just for quick access.
1057 const char *last_directory;
1059 /* last_directory_len: cached computation of strlen(last_directory) */
1060 unsigned last_directory_len;
1063 static int tree_entry_order(const void *a_, const void *b_)
1065 const struct string_list_item *a = a_;
1066 const struct string_list_item *b = b_;
1068 const struct merged_info *ami = a->util;
1069 const struct merged_info *bmi = b->util;
1070 return base_name_compare(a->string, strlen(a->string), ami->result.mode,
1071 b->string, strlen(b->string), bmi->result.mode);
1074 static void write_tree(struct object_id *result_oid,
1075 struct string_list *versions,
1076 unsigned int offset,
1079 size_t maxlen = 0, extra;
1080 unsigned int nr = versions->nr - offset;
1081 struct strbuf buf = STRBUF_INIT;
1082 struct string_list relevant_entries = STRING_LIST_INIT_NODUP;
1086 * We want to sort the last (versions->nr-offset) entries in versions.
1087 * Do so by abusing the string_list API a bit: make another string_list
1088 * that contains just those entries and then sort them.
1090 * We won't use relevant_entries again and will let it just pop off the
1091 * stack, so there won't be allocation worries or anything.
1093 relevant_entries.items = versions->items + offset;
1094 relevant_entries.nr = versions->nr - offset;
1095 QSORT(relevant_entries.items, relevant_entries.nr, tree_entry_order);
1097 /* Pre-allocate some space in buf */
1098 extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
1099 for (i = 0; i < nr; i++) {
1100 maxlen += strlen(versions->items[offset+i].string) + extra;
1102 strbuf_grow(&buf, maxlen);
1104 /* Write each entry out to buf */
1105 for (i = 0; i < nr; i++) {
1106 struct merged_info *mi = versions->items[offset+i].util;
1107 struct version_info *ri = &mi->result;
1108 strbuf_addf(&buf, "%o %s%c",
1110 versions->items[offset+i].string, '\0');
1111 strbuf_add(&buf, ri->oid.hash, hash_size);
1114 /* Write this object file out, and record in result_oid */
1115 write_object_file(buf.buf, buf.len, tree_type, result_oid);
1116 strbuf_release(&buf);
1119 static void record_entry_for_tree(struct directory_versions *dir_metadata,
1121 struct merged_info *mi)
1123 const char *basename;
1126 /* nothing to record */
1129 basename = path + mi->basename_offset;
1130 assert(strchr(basename, '/') == NULL);
1131 string_list_append(&dir_metadata->versions,
1132 basename)->util = &mi->result;
1135 static void write_completed_directory(struct merge_options *opt,
1136 const char *new_directory_name,
1137 struct directory_versions *info)
1139 const char *prev_dir;
1140 struct merged_info *dir_info = NULL;
1141 unsigned int offset;
1144 * Some explanation of info->versions and info->offsets...
1146 * process_entries() iterates over all relevant files AND
1147 * directories in reverse lexicographic order, and calls this
1148 * function. Thus, an example of the paths that process_entries()
1149 * could operate on (along with the directories for those paths
1154 * src/moduleB/umm.c src/moduleB
1155 * src/moduleB/stuff.h src/moduleB
1156 * src/moduleB/baz.c src/moduleB
1158 * src/moduleA/foo.c src/moduleA
1159 * src/moduleA/bar.c src/moduleA
1166 * always contains the unprocessed entries and their
1167 * version_info information. For example, after the first five
1168 * entries above, info->versions would be:
1170 * xtract.c <xtract.c's version_info>
1171 * token.txt <token.txt's version_info>
1172 * umm.c <src/moduleB/umm.c's version_info>
1173 * stuff.h <src/moduleB/stuff.h's version_info>
1174 * baz.c <src/moduleB/baz.c's version_info>
1176 * Once a subdirectory is completed we remove the entries in
1177 * that subdirectory from info->versions, writing it as a tree
1178 * (write_tree()). Thus, as soon as we get to src/moduleB,
1179 * info->versions would be updated to
1181 * xtract.c <xtract.c's version_info>
1182 * token.txt <token.txt's version_info>
1183 * moduleB <src/moduleB's version_info>
1187 * helps us track which entries in info->versions correspond to
1188 * which directories. When we are N directories deep (e.g. 4
1189 * for src/modA/submod/subdir/), we have up to N+1 unprocessed
1190 * directories (+1 because of toplevel dir). Corresponding to
1191 * the info->versions example above, after processing five entries
1192 * info->offsets will be:
1197 * which is used to know that xtract.c & token.txt are from the
1198 * toplevel dirctory, while umm.c & stuff.h & baz.c are from the
1199 * src/moduleB directory. Again, following the example above,
1200 * once we need to process src/moduleB, then info->offsets is
1206 * which says that moduleB (and only moduleB so far) is in the
1209 * One unique thing to note about info->offsets here is that
1210 * "src" was not added to info->offsets until there was a path
1211 * (a file OR directory) immediately below src/ that got
1214 * Since process_entry() just appends new entries to info->versions,
1215 * write_completed_directory() only needs to do work if the next path
1216 * is in a directory that is different than the last directory found
1221 * If we are working with the same directory as the last entry, there
1222 * is no work to do. (See comments above the directory_name member of
1223 * struct merged_info for why we can use pointer comparison instead of
1226 if (new_directory_name == info->last_directory)
1230 * If we are just starting (last_directory is NULL), or last_directory
1231 * is a prefix of the current directory, then we can just update
1232 * info->offsets to record the offset where we started this directory
1233 * and update last_directory to have quick access to it.
1235 if (info->last_directory == NULL ||
1236 !strncmp(new_directory_name, info->last_directory,
1237 info->last_directory_len)) {
1238 uintptr_t offset = info->versions.nr;
1240 info->last_directory = new_directory_name;
1241 info->last_directory_len = strlen(info->last_directory);
1243 * Record the offset into info->versions where we will
1244 * start recording basenames of paths found within
1245 * new_directory_name.
1247 string_list_append(&info->offsets,
1248 info->last_directory)->util = (void*)offset;
1253 * The next entry that will be processed will be within
1254 * new_directory_name. Since at this point we know that
1255 * new_directory_name is within a different directory than
1256 * info->last_directory, we have all entries for info->last_directory
1257 * in info->versions and we need to create a tree object for them.
1259 dir_info = strmap_get(&opt->priv->paths, info->last_directory);
1261 offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
1262 if (offset == info->versions.nr) {
1264 * Actually, we don't need to create a tree object in this
1265 * case. Whenever all files within a directory disappear
1266 * during the merge (e.g. unmodified on one side and
1267 * deleted on the other, or files were renamed elsewhere),
1268 * then we get here and the directory itself needs to be
1269 * omitted from its parent tree as well.
1271 dir_info->is_null = 1;
1274 * Write out the tree to the git object directory, and also
1275 * record the mode and oid in dir_info->result.
1277 dir_info->is_null = 0;
1278 dir_info->result.mode = S_IFDIR;
1279 write_tree(&dir_info->result.oid, &info->versions, offset,
1280 opt->repo->hash_algo->rawsz);
1284 * We've now used several entries from info->versions and one entry
1285 * from info->offsets, so we get rid of those values.
1288 info->versions.nr = offset;
1291 * Now we've taken care of the completed directory, but we need to
1292 * prepare things since future entries will be in
1293 * new_directory_name. (In particular, process_entry() will be
1294 * appending new entries to info->versions.) So, we need to make
1295 * sure new_directory_name is the last entry in info->offsets.
1297 prev_dir = info->offsets.nr == 0 ? NULL :
1298 info->offsets.items[info->offsets.nr-1].string;
1299 if (new_directory_name != prev_dir) {
1300 uintptr_t c = info->versions.nr;
1301 string_list_append(&info->offsets,
1302 new_directory_name)->util = (void*)c;
1305 /* And, of course, we need to update last_directory to match. */
1306 info->last_directory = new_directory_name;
1307 info->last_directory_len = strlen(info->last_directory);
1310 /* Per entry merge function */
1311 static void process_entry(struct merge_options *opt,
1313 struct conflict_info *ci,
1314 struct directory_versions *dir_metadata)
1316 int df_file_index = 0;
1319 assert(ci->filemask >= 0 && ci->filemask <= 7);
1320 /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
1321 assert(ci->match_mask == 0 || ci->match_mask == 3 ||
1322 ci->match_mask == 5 || ci->match_mask == 6);
1325 record_entry_for_tree(dir_metadata, path, &ci->merged);
1326 if (ci->filemask == 0)
1327 /* nothing else to handle */
1329 assert(ci->df_conflict);
1332 if (ci->df_conflict && ci->merged.result.mode == 0) {
1336 * directory no longer in the way, but we do have a file we
1337 * need to place here so we need to clean away the "directory
1338 * merges to nothing" result.
1340 ci->df_conflict = 0;
1341 assert(ci->filemask != 0);
1342 ci->merged.clean = 0;
1343 ci->merged.is_null = 0;
1344 /* and we want to zero out any directory-related entries */
1345 ci->match_mask = (ci->match_mask & ~ci->dirmask);
1347 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1348 if (ci->filemask & (1 << i))
1350 ci->stages[i].mode = 0;
1351 oidcpy(&ci->stages[i].oid, &null_oid);
1353 } else if (ci->df_conflict && ci->merged.result.mode != 0) {
1355 * This started out as a D/F conflict, and the entries in
1356 * the competing directory were not removed by the merge as
1357 * evidenced by write_completed_directory() writing a value
1358 * to ci->merged.result.mode.
1360 struct conflict_info *new_ci;
1362 const char *old_path = path;
1365 assert(ci->merged.result.mode == S_IFDIR);
1368 * If filemask is 1, we can just ignore the file as having
1369 * been deleted on both sides. We do not want to overwrite
1370 * ci->merged.result, since it stores the tree for all the
1373 if (ci->filemask == 1) {
1379 * This file still exists on at least one side, and we want
1380 * the directory to remain here, so we need to move this
1381 * path to some new location.
1383 new_ci = xcalloc(1, sizeof(*new_ci));
1384 /* We don't really want new_ci->merged.result copied, but it'll
1385 * be overwritten below so it doesn't matter. We also don't
1386 * want any directory mode/oid values copied, but we'll zero
1387 * those out immediately. We do want the rest of ci copied.
1389 memcpy(new_ci, ci, sizeof(*ci));
1390 new_ci->match_mask = (new_ci->match_mask & ~new_ci->dirmask);
1391 new_ci->dirmask = 0;
1392 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1393 if (new_ci->filemask & (1 << i))
1395 /* zero out any entries related to directories */
1396 new_ci->stages[i].mode = 0;
1397 oidcpy(&new_ci->stages[i].oid, &null_oid);
1401 * Find out which side this file came from; note that we
1402 * cannot just use ci->filemask, because renames could cause
1403 * the filemask to go back to 7. So we use dirmask, then
1404 * pick the opposite side's index.
1406 df_file_index = (ci->dirmask & (1 << 1)) ? 2 : 1;
1407 branch = (df_file_index == 1) ? opt->branch1 : opt->branch2;
1408 path = unique_path(&opt->priv->paths, path, branch);
1409 strmap_put(&opt->priv->paths, path, new_ci);
1411 path_msg(opt, path, 0,
1412 _("CONFLICT (file/directory): directory in the way "
1413 "of %s from %s; moving it to %s instead."),
1414 old_path, branch, path);
1417 * Zero out the filemask for the old ci. At this point, ci
1418 * was just an entry for a directory, so we don't need to
1419 * do anything more with it.
1424 * Now note that we're working on the new entry (path was
1431 * NOTE: Below there is a long switch-like if-elseif-elseif... block
1432 * which the code goes through even for the df_conflict cases
1435 if (ci->match_mask) {
1436 ci->merged.clean = 1;
1437 if (ci->match_mask == 6) {
1438 /* stages[1] == stages[2] */
1439 ci->merged.result.mode = ci->stages[1].mode;
1440 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
1442 /* determine the mask of the side that didn't match */
1443 unsigned int othermask = 7 & ~ci->match_mask;
1444 int side = (othermask == 4) ? 2 : 1;
1446 ci->merged.result.mode = ci->stages[side].mode;
1447 ci->merged.is_null = !ci->merged.result.mode;
1448 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1450 assert(othermask == 2 || othermask == 4);
1451 assert(ci->merged.is_null ==
1452 (ci->filemask == ci->match_mask));
1454 } else if (ci->filemask >= 6 &&
1455 (S_IFMT & ci->stages[1].mode) !=
1456 (S_IFMT & ci->stages[2].mode)) {
1458 * Two different items from (file/submodule/symlink)
1460 die("Not yet implemented.");
1461 } else if (ci->filemask >= 6) {
1462 /* Need a two-way or three-way content merge */
1463 struct version_info merged_file;
1464 unsigned clean_merge;
1465 struct version_info *o = &ci->stages[0];
1466 struct version_info *a = &ci->stages[1];
1467 struct version_info *b = &ci->stages[2];
1469 clean_merge = handle_content_merge(opt, path, o, a, b,
1471 opt->priv->call_depth * 2,
1473 ci->merged.clean = clean_merge &&
1474 !ci->df_conflict && !ci->path_conflict;
1475 ci->merged.result.mode = merged_file.mode;
1476 ci->merged.is_null = (merged_file.mode == 0);
1477 oidcpy(&ci->merged.result.oid, &merged_file.oid);
1478 if (clean_merge && ci->df_conflict) {
1479 assert(df_file_index == 1 || df_file_index == 2);
1480 ci->filemask = 1 << df_file_index;
1481 ci->stages[df_file_index].mode = merged_file.mode;
1482 oidcpy(&ci->stages[df_file_index].oid, &merged_file.oid);
1485 const char *reason = _("content");
1486 if (ci->filemask == 6)
1487 reason = _("add/add");
1488 if (S_ISGITLINK(merged_file.mode))
1489 reason = _("submodule");
1490 path_msg(opt, path, 0,
1491 _("CONFLICT (%s): Merge conflict in %s"),
1494 } else if (ci->filemask == 3 || ci->filemask == 5) {
1496 const char *modify_branch, *delete_branch;
1497 int side = (ci->filemask == 5) ? 2 : 1;
1498 int index = opt->priv->call_depth ? 0 : side;
1500 ci->merged.result.mode = ci->stages[index].mode;
1501 oidcpy(&ci->merged.result.oid, &ci->stages[index].oid);
1502 ci->merged.clean = 0;
1504 modify_branch = (side == 1) ? opt->branch1 : opt->branch2;
1505 delete_branch = (side == 1) ? opt->branch2 : opt->branch1;
1507 path_msg(opt, path, 0,
1508 _("CONFLICT (modify/delete): %s deleted in %s "
1509 "and modified in %s. Version %s of %s left "
1511 path, delete_branch, modify_branch,
1512 modify_branch, path);
1513 } else if (ci->filemask == 2 || ci->filemask == 4) {
1514 /* Added on one side */
1515 int side = (ci->filemask == 4) ? 2 : 1;
1516 ci->merged.result.mode = ci->stages[side].mode;
1517 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1518 ci->merged.clean = !ci->df_conflict;
1519 } else if (ci->filemask == 1) {
1520 /* Deleted on both sides */
1521 ci->merged.is_null = 1;
1522 ci->merged.result.mode = 0;
1523 oidcpy(&ci->merged.result.oid, &null_oid);
1524 ci->merged.clean = 1;
1528 * If still conflicted, record it separately. This allows us to later
1529 * iterate over just conflicted entries when updating the index instead
1530 * of iterating over all entries.
1532 if (!ci->merged.clean)
1533 strmap_put(&opt->priv->conflicted, path, ci);
1534 record_entry_for_tree(dir_metadata, path, &ci->merged);
1537 static void process_entries(struct merge_options *opt,
1538 struct object_id *result_oid)
1540 struct hashmap_iter iter;
1541 struct strmap_entry *e;
1542 struct string_list plist = STRING_LIST_INIT_NODUP;
1543 struct string_list_item *entry;
1544 struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
1545 STRING_LIST_INIT_NODUP,
1548 if (strmap_empty(&opt->priv->paths)) {
1549 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
1553 /* Hack to pre-allocate plist to the desired size */
1554 ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
1556 /* Put every entry from paths into plist, then sort */
1557 strmap_for_each_entry(&opt->priv->paths, &iter, e) {
1558 string_list_append(&plist, e->key)->util = e->value;
1560 plist.cmp = string_list_df_name_compare;
1561 string_list_sort(&plist);
1564 * Iterate over the items in reverse order, so we can handle paths
1565 * below a directory before needing to handle the directory itself.
1567 * This allows us to write subtrees before we need to write trees,
1568 * and it also enables sane handling of directory/file conflicts
1569 * (because it allows us to know whether the directory is still in
1570 * the way when it is time to process the file at the same path).
1572 for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
1573 char *path = entry->string;
1575 * NOTE: mi may actually be a pointer to a conflict_info, but
1576 * we have to check mi->clean first to see if it's safe to
1577 * reassign to such a pointer type.
1579 struct merged_info *mi = entry->util;
1581 write_completed_directory(opt, mi->directory_name,
1584 record_entry_for_tree(&dir_metadata, path, mi);
1586 struct conflict_info *ci = (struct conflict_info *)mi;
1587 process_entry(opt, path, ci, &dir_metadata);
1591 if (dir_metadata.offsets.nr != 1 ||
1592 (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
1593 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
1594 dir_metadata.offsets.nr);
1595 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
1596 (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
1598 BUG("dir_metadata accounting completely off; shouldn't happen");
1600 write_tree(result_oid, &dir_metadata.versions, 0,
1601 opt->repo->hash_algo->rawsz);
1602 string_list_clear(&plist, 0);
1603 string_list_clear(&dir_metadata.versions, 0);
1604 string_list_clear(&dir_metadata.offsets, 0);
1607 /*** Function Grouping: functions related to merge_switch_to_result() ***/
1609 static int checkout(struct merge_options *opt,
1613 /* Switch the index/working copy from old to new */
1615 struct tree_desc trees[2];
1616 struct unpack_trees_options unpack_opts;
1618 memset(&unpack_opts, 0, sizeof(unpack_opts));
1619 unpack_opts.head_idx = -1;
1620 unpack_opts.src_index = opt->repo->index;
1621 unpack_opts.dst_index = opt->repo->index;
1623 setup_unpack_trees_porcelain(&unpack_opts, "merge");
1626 * NOTE: if this were just "git checkout" code, we would probably
1627 * read or refresh the cache and check for a conflicted index, but
1628 * builtin/merge.c or sequencer.c really needs to read the index
1629 * and check for conflicted entries before starting merging for a
1630 * good user experience (no sense waiting for merges/rebases before
1631 * erroring out), so there's no reason to duplicate that work here.
1634 /* 2-way merge to the new branch */
1635 unpack_opts.update = 1;
1636 unpack_opts.merge = 1;
1637 unpack_opts.quiet = 0; /* FIXME: sequencer might want quiet? */
1638 unpack_opts.verbose_update = (opt->verbosity > 2);
1639 unpack_opts.fn = twoway_merge;
1640 if (1/* FIXME: opts->overwrite_ignore*/) {
1641 unpack_opts.dir = xcalloc(1, sizeof(*unpack_opts.dir));
1642 unpack_opts.dir->flags |= DIR_SHOW_IGNORED;
1643 setup_standard_excludes(unpack_opts.dir);
1646 init_tree_desc(&trees[0], prev->buffer, prev->size);
1648 init_tree_desc(&trees[1], next->buffer, next->size);
1650 ret = unpack_trees(2, trees, &unpack_opts);
1651 clear_unpack_trees_porcelain(&unpack_opts);
1652 dir_clear(unpack_opts.dir);
1653 FREE_AND_NULL(unpack_opts.dir);
1657 static int record_conflicted_index_entries(struct merge_options *opt,
1658 struct index_state *index,
1659 struct strmap *paths,
1660 struct strmap *conflicted)
1662 struct hashmap_iter iter;
1663 struct strmap_entry *e;
1665 int original_cache_nr;
1667 if (strmap_empty(conflicted))
1670 original_cache_nr = index->cache_nr;
1672 /* Put every entry from paths into plist, then sort */
1673 strmap_for_each_entry(conflicted, &iter, e) {
1674 const char *path = e->key;
1675 struct conflict_info *ci = e->value;
1677 struct cache_entry *ce;
1683 * The index will already have a stage=0 entry for this path,
1684 * because we created an as-merged-as-possible version of the
1685 * file and checkout() moved the working copy and index over
1688 * However, previous iterations through this loop will have
1689 * added unstaged entries to the end of the cache which
1690 * ignore the standard alphabetical ordering of cache
1691 * entries and break invariants needed for index_name_pos()
1692 * to work. However, we know the entry we want is before
1693 * those appended cache entries, so do a temporary swap on
1694 * cache_nr to only look through entries of interest.
1696 SWAP(index->cache_nr, original_cache_nr);
1697 pos = index_name_pos(index, path, strlen(path));
1698 SWAP(index->cache_nr, original_cache_nr);
1700 if (ci->filemask != 1)
1701 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path);
1702 cache_tree_invalidate_path(index, path);
1704 ce = index->cache[pos];
1707 * Clean paths with CE_SKIP_WORKTREE set will not be
1708 * written to the working tree by the unpack_trees()
1709 * call in checkout(). Our conflicted entries would
1710 * have appeared clean to that code since we ignored
1711 * the higher order stages. Thus, we need override
1712 * the CE_SKIP_WORKTREE bit and manually write those
1713 * files to the working disk here.
1715 * TODO: Implement this CE_SKIP_WORKTREE fixup.
1719 * Mark this cache entry for removal and instead add
1720 * new stage>0 entries corresponding to the
1721 * conflicts. If there are many conflicted entries, we
1722 * want to avoid memmove'ing O(NM) entries by
1723 * inserting the new entries one at a time. So,
1724 * instead, we just add the new cache entries to the
1725 * end (ignoring normal index requirements on sort
1726 * order) and sort the index once we're all done.
1728 ce->ce_flags |= CE_REMOVE;
1731 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1732 struct version_info *vi;
1733 if (!(ci->filemask & (1ul << i)))
1735 vi = &ci->stages[i];
1736 ce = make_cache_entry(index, vi->mode, &vi->oid,
1738 add_index_entry(index, ce, ADD_CACHE_JUST_APPEND);
1743 * Remove the unused cache entries (and invalidate the relevant
1744 * cache-trees), then sort the index entries to get the conflicted
1745 * entries we added to the end into their right locations.
1747 remove_marked_cache_entries(index, 1);
1748 QSORT(index->cache, index->cache_nr, cmp_cache_name_compare);
1753 void merge_switch_to_result(struct merge_options *opt,
1755 struct merge_result *result,
1756 int update_worktree_and_index,
1757 int display_update_msgs)
1759 assert(opt->priv == NULL);
1760 if (result->clean >= 0 && update_worktree_and_index) {
1761 struct merge_options_internal *opti = result->priv;
1763 if (checkout(opt, head, result->tree)) {
1764 /* failure to function */
1769 if (record_conflicted_index_entries(opt, opt->repo->index,
1771 &opti->conflicted)) {
1772 /* failure to function */
1778 if (display_update_msgs) {
1779 struct merge_options_internal *opti = result->priv;
1780 struct hashmap_iter iter;
1781 struct strmap_entry *e;
1782 struct string_list olist = STRING_LIST_INIT_NODUP;
1785 /* Hack to pre-allocate olist to the desired size */
1786 ALLOC_GROW(olist.items, strmap_get_size(&opti->output),
1789 /* Put every entry from output into olist, then sort */
1790 strmap_for_each_entry(&opti->output, &iter, e) {
1791 string_list_append(&olist, e->key)->util = e->value;
1793 string_list_sort(&olist);
1795 /* Iterate over the items, printing them */
1796 for (i = 0; i < olist.nr; ++i) {
1797 struct strbuf *sb = olist.items[i].util;
1799 printf("%s", sb->buf);
1801 string_list_clear(&olist, 0);
1804 merge_finalize(opt, result);
1807 void merge_finalize(struct merge_options *opt,
1808 struct merge_result *result)
1810 struct merge_options_internal *opti = result->priv;
1812 assert(opt->priv == NULL);
1814 clear_internal_opts(opti, 0);
1815 FREE_AND_NULL(opti);
1818 /*** Function Grouping: helper functions for merge_incore_*() ***/
1820 static void merge_start(struct merge_options *opt, struct merge_result *result)
1822 /* Sanity checks on opt */
1825 assert(opt->branch1 && opt->branch2);
1827 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
1828 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
1829 assert(opt->rename_limit >= -1);
1830 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
1831 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
1833 assert(opt->xdl_opts >= 0);
1834 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
1835 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
1838 * detect_renames, verbosity, buffer_output, and obuf are ignored
1839 * fields that were used by "recursive" rather than "ort" -- but
1840 * sanity check them anyway.
1842 assert(opt->detect_renames >= -1 &&
1843 opt->detect_renames <= DIFF_DETECT_COPY);
1844 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
1845 assert(opt->buffer_output <= 2);
1846 assert(opt->obuf.len == 0);
1848 assert(opt->priv == NULL);
1850 /* Default to histogram diff. Actually, just hardcode it...for now. */
1851 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
1853 /* Initialization of opt->priv, our internal merge data */
1854 opt->priv = xcalloc(1, sizeof(*opt->priv));
1857 * Although we initialize opt->priv->paths with strdup_strings=0,
1858 * that's just to avoid making yet another copy of an allocated
1859 * string. Putting the entry into paths means we are taking
1860 * ownership, so we will later free it. paths_to_free is similar.
1862 * In contrast, conflicted just has a subset of keys from paths, so
1863 * we don't want to free those (it'd be a duplicate free).
1865 strmap_init_with_options(&opt->priv->paths, NULL, 0);
1866 strmap_init_with_options(&opt->priv->conflicted, NULL, 0);
1867 string_list_init(&opt->priv->paths_to_free, 0);
1870 * keys & strbufs in output will sometimes need to outlive "paths",
1871 * so it will have a copy of relevant keys. It's probably a small
1872 * subset of the overall paths that have special output.
1874 strmap_init(&opt->priv->output);
1877 /*** Function Grouping: merge_incore_*() and their internal variants ***/
1880 * Originally from merge_trees_internal(); heavily adapted, though.
1882 static void merge_ort_nonrecursive_internal(struct merge_options *opt,
1883 struct tree *merge_base,
1886 struct merge_result *result)
1888 struct object_id working_tree_oid;
1890 if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
1892 * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
1893 * base, and 2-3) the trees for the two trees we're merging.
1895 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
1896 oid_to_hex(&merge_base->object.oid),
1897 oid_to_hex(&side1->object.oid),
1898 oid_to_hex(&side2->object.oid));
1903 result->clean = detect_and_process_renames(opt, merge_base,
1905 process_entries(opt, &working_tree_oid);
1907 /* Set return values */
1908 result->tree = parse_tree_indirect(&working_tree_oid);
1909 /* existence of conflicted entries implies unclean */
1910 result->clean &= strmap_empty(&opt->priv->conflicted);
1911 if (!opt->priv->call_depth) {
1912 result->priv = opt->priv;
1917 void merge_incore_nonrecursive(struct merge_options *opt,
1918 struct tree *merge_base,
1921 struct merge_result *result)
1923 assert(opt->ancestor != NULL);
1924 merge_start(opt, result);
1925 merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
1928 void merge_incore_recursive(struct merge_options *opt,
1929 struct commit_list *merge_bases,
1930 struct commit *side1,
1931 struct commit *side2,
1932 struct merge_result *result)
1934 die("Not yet implemented");