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"
26 #include "object-store.h"
29 #include "unpack-trees.h"
30 #include "xdiff-interface.h"
33 * We have many arrays of size 3. Whenever we have such an array, the
34 * indices refer to one of the sides of the three-way merge. This is so
35 * pervasive that the constants 0, 1, and 2 are used in many places in the
36 * code (especially in arithmetic operations to find the other side's index
37 * or to compute a relevant mask), but sometimes these enum names are used
38 * to aid code clarity.
40 * See also 'filemask' and 'dirmask' in struct conflict_info; the "ith side"
41 * referred to there is one of these three sides.
49 struct merge_options_internal {
51 * paths: primary data structure in all of merge ort.
54 * * are full relative paths from the toplevel of the repository
55 * (e.g. "drivers/firmware/raspberrypi.c").
56 * * store all relevant paths in the repo, both directories and
57 * files (e.g. drivers, drivers/firmware would also be included)
58 * * these keys serve to intern all the path strings, which allows
59 * us to do pointer comparison on directory names instead of
60 * strcmp; we just have to be careful to use the interned strings.
61 * (Technically paths_to_free may track some strings that were
62 * removed from froms paths.)
64 * The values of paths:
65 * * either a pointer to a merged_info, or a conflict_info struct
66 * * merged_info contains all relevant information for a
67 * non-conflicted entry.
68 * * conflict_info contains a merged_info, plus any additional
69 * information about a conflict such as the higher orders stages
70 * involved and the names of the paths those came from (handy
71 * once renames get involved).
72 * * a path may start "conflicted" (i.e. point to a conflict_info)
73 * and then a later step (e.g. three-way content merge) determines
74 * it can be cleanly merged, at which point it'll be marked clean
75 * and the algorithm will ignore any data outside the contained
76 * merged_info for that entry
77 * * If an entry remains conflicted, the merged_info portion of a
78 * conflict_info will later be filled with whatever version of
79 * the file should be placed in the working directory (e.g. an
80 * as-merged-as-possible variation that contains conflict markers).
85 * conflicted: a subset of keys->values from "paths"
87 * conflicted is basically an optimization between process_entries()
88 * and record_conflicted_index_entries(); the latter could loop over
89 * ALL the entries in paths AGAIN and look for the ones that are
90 * still conflicted, but since process_entries() has to loop over
91 * all of them, it saves the ones it couldn't resolve in this strmap
92 * so that record_conflicted_index_entries() can iterate just the
95 struct strmap conflicted;
98 * paths_to_free: additional list of strings to free
100 * If keys are removed from "paths", they are added to paths_to_free
101 * to ensure they are later freed. We avoid free'ing immediately since
102 * other places (e.g. conflict_info.pathnames[]) may still be
103 * referencing these paths.
105 struct string_list paths_to_free;
108 * output: special messages and conflict notices for various paths
110 * This is a map of pathnames (a subset of the keys in "paths" above)
111 * to strbufs. It gathers various warning/conflict/notice messages
112 * for later processing.
114 struct strmap output;
117 * current_dir_name: temporary var used in collect_merge_info_callback()
119 * Used to set merged_info.directory_name; see documentation for that
120 * variable and the requirements placed on that field.
122 const char *current_dir_name;
124 /* call_depth: recursion level counter for merging merge bases */
128 struct version_info {
129 struct object_id oid;
134 /* if is_null, ignore result. otherwise result has oid & mode */
135 struct version_info result;
139 * clean: whether the path in question is cleanly merged.
141 * see conflict_info.merged for more details.
146 * basename_offset: offset of basename of path.
148 * perf optimization to avoid recomputing offset of final '/'
149 * character in pathname (0 if no '/' in pathname).
151 size_t basename_offset;
154 * directory_name: containing directory name.
156 * Note that we assume directory_name is constructed such that
157 * strcmp(dir1_name, dir2_name) == 0 iff dir1_name == dir2_name,
158 * i.e. string equality is equivalent to pointer equality. For this
159 * to hold, we have to be careful setting directory_name.
161 const char *directory_name;
164 struct conflict_info {
166 * merged: the version of the path that will be written to working tree
168 * WARNING: It is critical to check merged.clean and ensure it is 0
169 * before reading any conflict_info fields outside of merged.
170 * Allocated merge_info structs will always have clean set to 1.
171 * Allocated conflict_info structs will have merged.clean set to 0
172 * initially. The merged.clean field is how we know if it is safe
173 * to access other parts of conflict_info besides merged; if a
174 * conflict_info's merged.clean is changed to 1, the rest of the
175 * algorithm is not allowed to look at anything outside of the
176 * merged member anymore.
178 struct merged_info merged;
180 /* oids & modes from each of the three trees for this path */
181 struct version_info stages[3];
183 /* pathnames for each stage; may differ due to rename detection */
184 const char *pathnames[3];
186 /* Whether this path is/was involved in a directory/file conflict */
187 unsigned df_conflict:1;
190 * Whether this path is/was involved in a non-content conflict other
191 * than a directory/file conflict (e.g. rename/rename, rename/delete,
192 * file location based on possible directory rename).
194 unsigned path_conflict:1;
197 * For filemask and dirmask, the ith bit corresponds to whether the
198 * ith entry is a file (filemask) or a directory (dirmask). Thus,
199 * filemask & dirmask is always zero, and filemask | dirmask is at
200 * most 7 but can be less when a path does not appear as either a
201 * file or a directory on at least one side of history.
203 * Note that these masks are related to enum merge_side, as the ith
204 * entry corresponds to side i.
206 * These values come from a traverse_trees() call; more info may be
207 * found looking at tree-walk.h's struct traverse_info,
208 * particularly the documentation above the "fn" member (note that
209 * filemask = mask & ~dirmask from that documentation).
215 * Optimization to track which stages match, to avoid the need to
216 * recompute it in multiple steps. Either 0 or at least 2 bits are
217 * set; if at least 2 bits are set, their corresponding stages match.
219 unsigned match_mask:3;
222 /*** Function Grouping: various utility functions ***/
225 * For the next three macros, see warning for conflict_info.merged.
227 * In each of the below, mi is a struct merged_info*, and ci was defined
228 * as a struct conflict_info* (but we need to verify ci isn't actually
229 * pointed at a struct merged_info*).
231 * INITIALIZE_CI: Assign ci to mi but only if it's safe; set to NULL otherwise.
232 * VERIFY_CI: Ensure that something we assigned to a conflict_info* is one.
233 * ASSIGN_AND_VERIFY_CI: Similar to VERIFY_CI but do assignment first.
235 #define INITIALIZE_CI(ci, mi) do { \
236 (ci) = (!(mi) || (mi)->clean) ? NULL : (struct conflict_info *)(mi); \
238 #define VERIFY_CI(ci) assert(ci && !ci->merged.clean);
239 #define ASSIGN_AND_VERIFY_CI(ci, mi) do { \
240 (ci) = (struct conflict_info *)(mi); \
241 assert((ci) && !(mi)->clean); \
244 static void free_strmap_strings(struct strmap *map)
246 struct hashmap_iter iter;
247 struct strmap_entry *entry;
249 strmap_for_each_entry(map, &iter, entry) {
250 free((char*)entry->key);
254 static void clear_internal_opts(struct merge_options_internal *opti,
257 assert(!reinitialize);
260 * We marked opti->paths with strdup_strings = 0, so that we
261 * wouldn't have to make another copy of the fullpath created by
262 * make_traverse_path from setup_path_info(). But, now that we've
263 * used it and have no other references to these strings, it is time
264 * to deallocate them.
266 free_strmap_strings(&opti->paths);
267 strmap_clear(&opti->paths, 1);
270 * All keys and values in opti->conflicted are a subset of those in
271 * opti->paths. We don't want to deallocate anything twice, so we
272 * don't free the keys and we pass 0 for free_values.
274 strmap_clear(&opti->conflicted, 0);
277 * opti->paths_to_free is similar to opti->paths; we created it with
278 * strdup_strings = 0 to avoid making _another_ copy of the fullpath
279 * but now that we've used it and have no other references to these
280 * strings, it is time to deallocate them. We do so by temporarily
281 * setting strdup_strings to 1.
283 opti->paths_to_free.strdup_strings = 1;
284 string_list_clear(&opti->paths_to_free, 0);
285 opti->paths_to_free.strdup_strings = 0;
288 struct hashmap_iter iter;
289 struct strmap_entry *e;
291 /* Release and free each strbuf found in output */
292 strmap_for_each_entry(&opti->output, &iter, e) {
293 struct strbuf *sb = e->value;
296 * While strictly speaking we don't need to free(sb)
297 * here because we could pass free_values=1 when
298 * calling strmap_clear() on opti->output, that would
299 * require strmap_clear to do another
300 * strmap_for_each_entry() loop, so we just free it
301 * while we're iterating anyway.
305 strmap_clear(&opti->output, 0);
309 static int err(struct merge_options *opt, const char *err, ...)
312 struct strbuf sb = STRBUF_INIT;
314 strbuf_addstr(&sb, "error: ");
315 va_start(params, err);
316 strbuf_vaddf(&sb, err, params);
325 __attribute__((format (printf, 4, 5)))
326 static void path_msg(struct merge_options *opt,
328 int omittable_hint, /* skippable under --remerge-diff */
329 const char *fmt, ...)
332 struct strbuf *sb = strmap_get(&opt->priv->output, path);
334 sb = xmalloc(sizeof(*sb));
336 strmap_put(&opt->priv->output, path, sb);
340 strbuf_vaddf(sb, fmt, ap);
343 strbuf_addch(sb, '\n');
346 /* add a string to a strbuf, but converting "/" to "_" */
347 static void add_flattened_path(struct strbuf *out, const char *s)
350 strbuf_addstr(out, s);
351 for (; i < out->len; i++)
352 if (out->buf[i] == '/')
356 static char *unique_path(struct strmap *existing_paths,
360 struct strbuf newpath = STRBUF_INIT;
364 strbuf_addf(&newpath, "%s~", path);
365 add_flattened_path(&newpath, branch);
367 base_len = newpath.len;
368 while (strmap_contains(existing_paths, newpath.buf)) {
369 strbuf_setlen(&newpath, base_len);
370 strbuf_addf(&newpath, "_%d", suffix++);
373 return strbuf_detach(&newpath, NULL);
376 /*** Function Grouping: functions related to collect_merge_info() ***/
378 static void setup_path_info(struct merge_options *opt,
379 struct string_list_item *result,
380 const char *current_dir_name,
381 int current_dir_name_len,
382 char *fullpath, /* we'll take over ownership */
383 struct name_entry *names,
384 struct name_entry *merged_version,
385 unsigned is_null, /* boolean */
386 unsigned df_conflict, /* boolean */
389 int resolved /* boolean */)
391 /* result->util is void*, so mi is a convenience typed variable */
392 struct merged_info *mi;
394 assert(!is_null || resolved);
395 assert(!df_conflict || !resolved); /* df_conflict implies !resolved */
396 assert(resolved == (merged_version != NULL));
398 mi = xcalloc(1, resolved ? sizeof(struct merged_info) :
399 sizeof(struct conflict_info));
400 mi->directory_name = current_dir_name;
401 mi->basename_offset = current_dir_name_len;
402 mi->clean = !!resolved;
404 mi->result.mode = merged_version->mode;
405 oidcpy(&mi->result.oid, &merged_version->oid);
406 mi->is_null = !!is_null;
409 struct conflict_info *ci;
411 ASSIGN_AND_VERIFY_CI(ci, mi);
412 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
413 ci->pathnames[i] = fullpath;
414 ci->stages[i].mode = names[i].mode;
415 oidcpy(&ci->stages[i].oid, &names[i].oid);
417 ci->filemask = filemask;
418 ci->dirmask = dirmask;
419 ci->df_conflict = !!df_conflict;
422 * Assume is_null for now, but if we have entries
423 * under the directory then when it is complete in
424 * write_completed_directory() it'll update this.
425 * Also, for D/F conflicts, we have to handle the
426 * directory first, then clear this bit and process
427 * the file to see how it is handled -- that occurs
428 * near the top of process_entry().
432 strmap_put(&opt->priv->paths, fullpath, mi);
433 result->string = fullpath;
437 static int collect_merge_info_callback(int n,
439 unsigned long dirmask,
440 struct name_entry *names,
441 struct traverse_info *info)
445 * common ancestor (mbase) has mask 1, and stored in index 0 of names
446 * head of side 1 (side1) has mask 2, and stored in index 1 of names
447 * head of side 2 (side2) has mask 4, and stored in index 2 of names
449 struct merge_options *opt = info->data;
450 struct merge_options_internal *opti = opt->priv;
451 struct string_list_item pi; /* Path Info */
452 struct conflict_info *ci; /* typed alias to pi.util (which is void*) */
453 struct name_entry *p;
456 const char *dirname = opti->current_dir_name;
457 unsigned filemask = mask & ~dirmask;
458 unsigned match_mask = 0; /* will be updated below */
459 unsigned mbase_null = !(mask & 1);
460 unsigned side1_null = !(mask & 2);
461 unsigned side2_null = !(mask & 4);
462 unsigned side1_matches_mbase = (!side1_null && !mbase_null &&
463 names[0].mode == names[1].mode &&
464 oideq(&names[0].oid, &names[1].oid));
465 unsigned side2_matches_mbase = (!side2_null && !mbase_null &&
466 names[0].mode == names[2].mode &&
467 oideq(&names[0].oid, &names[2].oid));
468 unsigned sides_match = (!side1_null && !side2_null &&
469 names[1].mode == names[2].mode &&
470 oideq(&names[1].oid, &names[2].oid));
473 * Note: When a path is a file on one side of history and a directory
474 * in another, we have a directory/file conflict. In such cases, if
475 * the conflict doesn't resolve from renames and deletions, then we
476 * always leave directories where they are and move files out of the
477 * way. Thus, while struct conflict_info has a df_conflict field to
478 * track such conflicts, we ignore that field for any directories at
479 * a path and only pay attention to it for files at the given path.
480 * The fact that we leave directories were they are also means that
481 * we do not need to worry about getting additional df_conflict
482 * information propagated from parent directories down to children
483 * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
484 * sets a newinfo.df_conflicts field specifically to propagate it).
486 unsigned df_conflict = (filemask != 0) && (dirmask != 0);
488 /* n = 3 is a fundamental assumption. */
490 BUG("Called collect_merge_info_callback wrong");
493 * A bunch of sanity checks verifying that traverse_trees() calls
494 * us the way I expect. Could just remove these at some point,
495 * though maybe they are helpful to future code readers.
497 assert(mbase_null == is_null_oid(&names[0].oid));
498 assert(side1_null == is_null_oid(&names[1].oid));
499 assert(side2_null == is_null_oid(&names[2].oid));
500 assert(!mbase_null || !side1_null || !side2_null);
501 assert(mask > 0 && mask < 8);
503 /* Determine match_mask */
504 if (side1_matches_mbase)
505 match_mask = (side2_matches_mbase ? 7 : 3);
506 else if (side2_matches_mbase)
508 else if (sides_match)
512 * Get the name of the relevant filepath, which we'll pass to
513 * setup_path_info() for tracking.
518 len = traverse_path_len(info, p->pathlen);
520 /* +1 in both of the following lines to include the NUL byte */
521 fullpath = xmalloc(len + 1);
522 make_traverse_path(fullpath, len + 1, info, p->path, p->pathlen);
525 * If mbase, side1, and side2 all match, we can resolve early. Even
526 * if these are trees, there will be no renames or anything
529 if (side1_matches_mbase && side2_matches_mbase) {
530 /* mbase, side1, & side2 all match; use mbase as resolution */
531 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
532 names, names+0, mbase_null, 0,
533 filemask, dirmask, 1);
538 * Record information about the path so we can resolve later in
541 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
542 names, NULL, 0, df_conflict, filemask, dirmask, 0);
546 ci->match_mask = match_mask;
548 /* If dirmask, recurse into subdirectories */
550 struct traverse_info newinfo;
551 struct tree_desc t[3];
552 void *buf[3] = {NULL, NULL, NULL};
553 const char *original_dir_name;
556 ci->match_mask &= filemask;
559 newinfo.name = p->path;
560 newinfo.namelen = p->pathlen;
561 newinfo.pathlen = st_add3(newinfo.pathlen, p->pathlen, 1);
563 * If this directory we are about to recurse into cared about
564 * its parent directory (the current directory) having a D/F
565 * conflict, then we'd propagate the masks in this way:
566 * newinfo.df_conflicts |= (mask & ~dirmask);
567 * But we don't worry about propagating D/F conflicts. (See
568 * comment near setting of local df_conflict variable near
569 * the beginning of this function).
572 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
573 if (i == 1 && side1_matches_mbase)
575 else if (i == 2 && side2_matches_mbase)
577 else if (i == 2 && sides_match)
580 const struct object_id *oid = NULL;
583 buf[i] = fill_tree_descriptor(opt->repo,
589 original_dir_name = opti->current_dir_name;
590 opti->current_dir_name = pi.string;
591 ret = traverse_trees(NULL, 3, t, &newinfo);
592 opti->current_dir_name = original_dir_name;
594 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
604 static int collect_merge_info(struct merge_options *opt,
605 struct tree *merge_base,
610 struct tree_desc t[3];
611 struct traverse_info info;
612 const char *toplevel_dir_placeholder = "";
614 opt->priv->current_dir_name = toplevel_dir_placeholder;
615 setup_traverse_info(&info, toplevel_dir_placeholder);
616 info.fn = collect_merge_info_callback;
618 info.show_all_errors = 1;
620 parse_tree(merge_base);
623 init_tree_desc(t + 0, merge_base->buffer, merge_base->size);
624 init_tree_desc(t + 1, side1->buffer, side1->size);
625 init_tree_desc(t + 2, side2->buffer, side2->size);
627 ret = traverse_trees(NULL, 3, t, &info);
632 /*** Function Grouping: functions related to threeway content merges ***/
634 static int merge_submodule(struct merge_options *opt,
636 const struct object_id *o,
637 const struct object_id *a,
638 const struct object_id *b,
639 struct object_id *result)
641 die("Not yet implemented.");
644 static int merge_3way(struct merge_options *opt,
646 const struct object_id *o,
647 const struct object_id *a,
648 const struct object_id *b,
649 const char *pathnames[3],
650 const int extra_marker_size,
651 mmbuffer_t *result_buf)
653 die("Not yet implemented.");
656 static int handle_content_merge(struct merge_options *opt,
658 const struct version_info *o,
659 const struct version_info *a,
660 const struct version_info *b,
661 const char *pathnames[3],
662 const int extra_marker_size,
663 struct version_info *result)
666 * path is the target location where we want to put the file, and
667 * is used to determine any normalization rules in ll_merge.
669 * The normal case is that path and all entries in pathnames are
670 * identical, though renames can affect which path we got one of
671 * the three blobs to merge on various sides of history.
673 * extra_marker_size is the amount to extend conflict markers in
674 * ll_merge; this is neeed if we have content merges of content
675 * merges, which happens for example with rename/rename(2to1) and
676 * rename/add conflicts.
681 * handle_content_merge() needs both files to be of the same type, i.e.
682 * both files OR both submodules OR both symlinks. Conflicting types
683 * needs to be handled elsewhere.
685 assert((S_IFMT & a->mode) == (S_IFMT & b->mode));
688 if (a->mode == b->mode || a->mode == o->mode)
689 result->mode = b->mode;
691 /* must be the 100644/100755 case */
692 assert(S_ISREG(a->mode));
693 result->mode = a->mode;
694 clean = (b->mode == o->mode);
696 * FIXME: If opt->priv->call_depth && !clean, then we really
697 * should not make result->mode match either a->mode or
698 * b->mode; that causes t6036 "check conflicting mode for
699 * regular file" to fail. It would be best to use some other
700 * mode, but we'll confuse all kinds of stuff if we use one
701 * where S_ISREG(result->mode) isn't true, and if we use
702 * something like 0100666, then tree-walk.c's calls to
703 * canon_mode() will just normalize that to 100644 for us and
704 * thus not solve anything.
706 * Figure out if there's some kind of way we can work around
714 * Note: While one might assume that the next four lines would
715 * be unnecessary due to the fact that match_mask is often
716 * setup and already handled, renames don't always take care
719 if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
720 oidcpy(&result->oid, &b->oid);
721 else if (oideq(&b->oid, &o->oid))
722 oidcpy(&result->oid, &a->oid);
724 /* Remaining rules depend on file vs. submodule vs. symlink. */
725 else if (S_ISREG(a->mode)) {
726 mmbuffer_t result_buf;
727 int ret = 0, merge_status;
731 * If 'o' is different type, treat it as null so we do a
734 two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
736 merge_status = merge_3way(opt, path,
737 two_way ? &null_oid : &o->oid,
739 pathnames, extra_marker_size,
742 if ((merge_status < 0) || !result_buf.ptr)
743 ret = err(opt, _("Failed to execute internal merge"));
746 write_object_file(result_buf.ptr, result_buf.size,
747 blob_type, &result->oid))
748 ret = err(opt, _("Unable to add %s to database"),
751 free(result_buf.ptr);
754 clean &= (merge_status == 0);
755 path_msg(opt, path, 1, _("Auto-merging %s"), path);
756 } else if (S_ISGITLINK(a->mode)) {
757 int two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
758 clean = merge_submodule(opt, pathnames[0],
759 two_way ? &null_oid : &o->oid,
760 &a->oid, &b->oid, &result->oid);
761 if (opt->priv->call_depth && two_way && !clean) {
762 result->mode = o->mode;
763 oidcpy(&result->oid, &o->oid);
765 } else if (S_ISLNK(a->mode)) {
766 if (opt->priv->call_depth) {
768 result->mode = o->mode;
769 oidcpy(&result->oid, &o->oid);
771 switch (opt->recursive_variant) {
772 case MERGE_VARIANT_NORMAL:
774 oidcpy(&result->oid, &a->oid);
776 case MERGE_VARIANT_OURS:
777 oidcpy(&result->oid, &a->oid);
779 case MERGE_VARIANT_THEIRS:
780 oidcpy(&result->oid, &b->oid);
785 BUG("unsupported object type in the tree: %06o for %s",
791 /*** Function Grouping: functions related to detect_and_process_renames(), ***
792 *** which are split into directory and regular rename detection sections. ***/
794 /*** Function Grouping: functions related to directory rename detection ***/
796 /*** Function Grouping: functions related to regular rename detection ***/
798 static int detect_and_process_renames(struct merge_options *opt,
799 struct tree *merge_base,
806 * Rename detection works by detecting file similarity. Here we use
807 * a really easy-to-implement scheme: files are similar IFF they have
808 * the same filename. Therefore, by this scheme, there are no renames.
810 * TODO: Actually implement a real rename detection scheme.
815 /*** Function Grouping: functions related to process_entries() ***/
817 static int string_list_df_name_compare(const char *one, const char *two)
819 int onelen = strlen(one);
820 int twolen = strlen(two);
822 * Here we only care that entries for D/F conflicts are
823 * adjacent, in particular with the file of the D/F conflict
824 * appearing before files below the corresponding directory.
825 * The order of the rest of the list is irrelevant for us.
827 * To achieve this, we sort with df_name_compare and provide
828 * the mode S_IFDIR so that D/F conflicts will sort correctly.
829 * We use the mode S_IFDIR for everything else for simplicity,
830 * since in other cases any changes in their order due to
831 * sorting cause no problems for us.
833 int cmp = df_name_compare(one, onelen, S_IFDIR,
834 two, twolen, S_IFDIR);
836 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
837 * that 'foo' comes before 'foo/bar'.
841 return onelen - twolen;
844 struct directory_versions {
846 * versions: list of (basename -> version_info)
848 * The basenames are in reverse lexicographic order of full pathnames,
849 * as processed in process_entries(). This puts all entries within
850 * a directory together, and covers the directory itself after
851 * everything within it, allowing us to write subtrees before needing
852 * to record information for the tree itself.
854 struct string_list versions;
857 * offsets: list of (full relative path directories -> integer offsets)
859 * Since versions contains basenames from files in multiple different
860 * directories, we need to know which entries in versions correspond
861 * to which directories. Values of e.g.
865 * Would mean that entries 0-1 of versions are files in the toplevel
866 * directory, entries 2-4 are files under src/, and the remaining
867 * entries starting at index 5 are files under src/moduleA/.
869 struct string_list offsets;
872 * last_directory: directory that previously processed file found in
874 * last_directory starts NULL, but records the directory in which the
875 * previous file was found within. As soon as
876 * directory(current_file) != last_directory
877 * then we need to start updating accounting in versions & offsets.
878 * Note that last_directory is always the last path in "offsets" (or
879 * NULL if "offsets" is empty) so this exists just for quick access.
881 const char *last_directory;
883 /* last_directory_len: cached computation of strlen(last_directory) */
884 unsigned last_directory_len;
887 static int tree_entry_order(const void *a_, const void *b_)
889 const struct string_list_item *a = a_;
890 const struct string_list_item *b = b_;
892 const struct merged_info *ami = a->util;
893 const struct merged_info *bmi = b->util;
894 return base_name_compare(a->string, strlen(a->string), ami->result.mode,
895 b->string, strlen(b->string), bmi->result.mode);
898 static void write_tree(struct object_id *result_oid,
899 struct string_list *versions,
903 size_t maxlen = 0, extra;
904 unsigned int nr = versions->nr - offset;
905 struct strbuf buf = STRBUF_INIT;
906 struct string_list relevant_entries = STRING_LIST_INIT_NODUP;
910 * We want to sort the last (versions->nr-offset) entries in versions.
911 * Do so by abusing the string_list API a bit: make another string_list
912 * that contains just those entries and then sort them.
914 * We won't use relevant_entries again and will let it just pop off the
915 * stack, so there won't be allocation worries or anything.
917 relevant_entries.items = versions->items + offset;
918 relevant_entries.nr = versions->nr - offset;
919 QSORT(relevant_entries.items, relevant_entries.nr, tree_entry_order);
921 /* Pre-allocate some space in buf */
922 extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
923 for (i = 0; i < nr; i++) {
924 maxlen += strlen(versions->items[offset+i].string) + extra;
926 strbuf_grow(&buf, maxlen);
928 /* Write each entry out to buf */
929 for (i = 0; i < nr; i++) {
930 struct merged_info *mi = versions->items[offset+i].util;
931 struct version_info *ri = &mi->result;
932 strbuf_addf(&buf, "%o %s%c",
934 versions->items[offset+i].string, '\0');
935 strbuf_add(&buf, ri->oid.hash, hash_size);
938 /* Write this object file out, and record in result_oid */
939 write_object_file(buf.buf, buf.len, tree_type, result_oid);
940 strbuf_release(&buf);
943 static void record_entry_for_tree(struct directory_versions *dir_metadata,
945 struct merged_info *mi)
947 const char *basename;
950 /* nothing to record */
953 basename = path + mi->basename_offset;
954 assert(strchr(basename, '/') == NULL);
955 string_list_append(&dir_metadata->versions,
956 basename)->util = &mi->result;
959 static void write_completed_directory(struct merge_options *opt,
960 const char *new_directory_name,
961 struct directory_versions *info)
963 const char *prev_dir;
964 struct merged_info *dir_info = NULL;
968 * Some explanation of info->versions and info->offsets...
970 * process_entries() iterates over all relevant files AND
971 * directories in reverse lexicographic order, and calls this
972 * function. Thus, an example of the paths that process_entries()
973 * could operate on (along with the directories for those paths
978 * src/moduleB/umm.c src/moduleB
979 * src/moduleB/stuff.h src/moduleB
980 * src/moduleB/baz.c src/moduleB
982 * src/moduleA/foo.c src/moduleA
983 * src/moduleA/bar.c src/moduleA
990 * always contains the unprocessed entries and their
991 * version_info information. For example, after the first five
992 * entries above, info->versions would be:
994 * xtract.c <xtract.c's version_info>
995 * token.txt <token.txt's version_info>
996 * umm.c <src/moduleB/umm.c's version_info>
997 * stuff.h <src/moduleB/stuff.h's version_info>
998 * baz.c <src/moduleB/baz.c's version_info>
1000 * Once a subdirectory is completed we remove the entries in
1001 * that subdirectory from info->versions, writing it as a tree
1002 * (write_tree()). Thus, as soon as we get to src/moduleB,
1003 * info->versions would be updated to
1005 * xtract.c <xtract.c's version_info>
1006 * token.txt <token.txt's version_info>
1007 * moduleB <src/moduleB's version_info>
1011 * helps us track which entries in info->versions correspond to
1012 * which directories. When we are N directories deep (e.g. 4
1013 * for src/modA/submod/subdir/), we have up to N+1 unprocessed
1014 * directories (+1 because of toplevel dir). Corresponding to
1015 * the info->versions example above, after processing five entries
1016 * info->offsets will be:
1021 * which is used to know that xtract.c & token.txt are from the
1022 * toplevel dirctory, while umm.c & stuff.h & baz.c are from the
1023 * src/moduleB directory. Again, following the example above,
1024 * once we need to process src/moduleB, then info->offsets is
1030 * which says that moduleB (and only moduleB so far) is in the
1033 * One unique thing to note about info->offsets here is that
1034 * "src" was not added to info->offsets until there was a path
1035 * (a file OR directory) immediately below src/ that got
1038 * Since process_entry() just appends new entries to info->versions,
1039 * write_completed_directory() only needs to do work if the next path
1040 * is in a directory that is different than the last directory found
1045 * If we are working with the same directory as the last entry, there
1046 * is no work to do. (See comments above the directory_name member of
1047 * struct merged_info for why we can use pointer comparison instead of
1050 if (new_directory_name == info->last_directory)
1054 * If we are just starting (last_directory is NULL), or last_directory
1055 * is a prefix of the current directory, then we can just update
1056 * info->offsets to record the offset where we started this directory
1057 * and update last_directory to have quick access to it.
1059 if (info->last_directory == NULL ||
1060 !strncmp(new_directory_name, info->last_directory,
1061 info->last_directory_len)) {
1062 uintptr_t offset = info->versions.nr;
1064 info->last_directory = new_directory_name;
1065 info->last_directory_len = strlen(info->last_directory);
1067 * Record the offset into info->versions where we will
1068 * start recording basenames of paths found within
1069 * new_directory_name.
1071 string_list_append(&info->offsets,
1072 info->last_directory)->util = (void*)offset;
1077 * The next entry that will be processed will be within
1078 * new_directory_name. Since at this point we know that
1079 * new_directory_name is within a different directory than
1080 * info->last_directory, we have all entries for info->last_directory
1081 * in info->versions and we need to create a tree object for them.
1083 dir_info = strmap_get(&opt->priv->paths, info->last_directory);
1085 offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
1086 if (offset == info->versions.nr) {
1088 * Actually, we don't need to create a tree object in this
1089 * case. Whenever all files within a directory disappear
1090 * during the merge (e.g. unmodified on one side and
1091 * deleted on the other, or files were renamed elsewhere),
1092 * then we get here and the directory itself needs to be
1093 * omitted from its parent tree as well.
1095 dir_info->is_null = 1;
1098 * Write out the tree to the git object directory, and also
1099 * record the mode and oid in dir_info->result.
1101 dir_info->is_null = 0;
1102 dir_info->result.mode = S_IFDIR;
1103 write_tree(&dir_info->result.oid, &info->versions, offset,
1104 opt->repo->hash_algo->rawsz);
1108 * We've now used several entries from info->versions and one entry
1109 * from info->offsets, so we get rid of those values.
1112 info->versions.nr = offset;
1115 * Now we've taken care of the completed directory, but we need to
1116 * prepare things since future entries will be in
1117 * new_directory_name. (In particular, process_entry() will be
1118 * appending new entries to info->versions.) So, we need to make
1119 * sure new_directory_name is the last entry in info->offsets.
1121 prev_dir = info->offsets.nr == 0 ? NULL :
1122 info->offsets.items[info->offsets.nr-1].string;
1123 if (new_directory_name != prev_dir) {
1124 uintptr_t c = info->versions.nr;
1125 string_list_append(&info->offsets,
1126 new_directory_name)->util = (void*)c;
1129 /* And, of course, we need to update last_directory to match. */
1130 info->last_directory = new_directory_name;
1131 info->last_directory_len = strlen(info->last_directory);
1134 /* Per entry merge function */
1135 static void process_entry(struct merge_options *opt,
1137 struct conflict_info *ci,
1138 struct directory_versions *dir_metadata)
1140 int df_file_index = 0;
1143 assert(ci->filemask >= 0 && ci->filemask <= 7);
1144 /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
1145 assert(ci->match_mask == 0 || ci->match_mask == 3 ||
1146 ci->match_mask == 5 || ci->match_mask == 6);
1149 record_entry_for_tree(dir_metadata, path, &ci->merged);
1150 if (ci->filemask == 0)
1151 /* nothing else to handle */
1153 assert(ci->df_conflict);
1156 if (ci->df_conflict && ci->merged.result.mode == 0) {
1160 * directory no longer in the way, but we do have a file we
1161 * need to place here so we need to clean away the "directory
1162 * merges to nothing" result.
1164 ci->df_conflict = 0;
1165 assert(ci->filemask != 0);
1166 ci->merged.clean = 0;
1167 ci->merged.is_null = 0;
1168 /* and we want to zero out any directory-related entries */
1169 ci->match_mask = (ci->match_mask & ~ci->dirmask);
1171 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1172 if (ci->filemask & (1 << i))
1174 ci->stages[i].mode = 0;
1175 oidcpy(&ci->stages[i].oid, &null_oid);
1177 } else if (ci->df_conflict && ci->merged.result.mode != 0) {
1179 * This started out as a D/F conflict, and the entries in
1180 * the competing directory were not removed by the merge as
1181 * evidenced by write_completed_directory() writing a value
1182 * to ci->merged.result.mode.
1184 struct conflict_info *new_ci;
1186 const char *old_path = path;
1189 assert(ci->merged.result.mode == S_IFDIR);
1192 * If filemask is 1, we can just ignore the file as having
1193 * been deleted on both sides. We do not want to overwrite
1194 * ci->merged.result, since it stores the tree for all the
1197 if (ci->filemask == 1) {
1203 * This file still exists on at least one side, and we want
1204 * the directory to remain here, so we need to move this
1205 * path to some new location.
1207 new_ci = xcalloc(1, sizeof(*new_ci));
1208 /* We don't really want new_ci->merged.result copied, but it'll
1209 * be overwritten below so it doesn't matter. We also don't
1210 * want any directory mode/oid values copied, but we'll zero
1211 * those out immediately. We do want the rest of ci copied.
1213 memcpy(new_ci, ci, sizeof(*ci));
1214 new_ci->match_mask = (new_ci->match_mask & ~new_ci->dirmask);
1215 new_ci->dirmask = 0;
1216 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1217 if (new_ci->filemask & (1 << i))
1219 /* zero out any entries related to directories */
1220 new_ci->stages[i].mode = 0;
1221 oidcpy(&new_ci->stages[i].oid, &null_oid);
1225 * Find out which side this file came from; note that we
1226 * cannot just use ci->filemask, because renames could cause
1227 * the filemask to go back to 7. So we use dirmask, then
1228 * pick the opposite side's index.
1230 df_file_index = (ci->dirmask & (1 << 1)) ? 2 : 1;
1231 branch = (df_file_index == 1) ? opt->branch1 : opt->branch2;
1232 path = unique_path(&opt->priv->paths, path, branch);
1233 strmap_put(&opt->priv->paths, path, new_ci);
1235 path_msg(opt, path, 0,
1236 _("CONFLICT (file/directory): directory in the way "
1237 "of %s from %s; moving it to %s instead."),
1238 old_path, branch, path);
1241 * Zero out the filemask for the old ci. At this point, ci
1242 * was just an entry for a directory, so we don't need to
1243 * do anything more with it.
1248 * Now note that we're working on the new entry (path was
1255 * NOTE: Below there is a long switch-like if-elseif-elseif... block
1256 * which the code goes through even for the df_conflict cases
1259 if (ci->match_mask) {
1260 ci->merged.clean = 1;
1261 if (ci->match_mask == 6) {
1262 /* stages[1] == stages[2] */
1263 ci->merged.result.mode = ci->stages[1].mode;
1264 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
1266 /* determine the mask of the side that didn't match */
1267 unsigned int othermask = 7 & ~ci->match_mask;
1268 int side = (othermask == 4) ? 2 : 1;
1270 ci->merged.result.mode = ci->stages[side].mode;
1271 ci->merged.is_null = !ci->merged.result.mode;
1272 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1274 assert(othermask == 2 || othermask == 4);
1275 assert(ci->merged.is_null ==
1276 (ci->filemask == ci->match_mask));
1278 } else if (ci->filemask >= 6 &&
1279 (S_IFMT & ci->stages[1].mode) !=
1280 (S_IFMT & ci->stages[2].mode)) {
1282 * Two different items from (file/submodule/symlink)
1284 die("Not yet implemented.");
1285 } else if (ci->filemask >= 6) {
1286 /* Need a two-way or three-way content merge */
1287 struct version_info merged_file;
1288 unsigned clean_merge;
1289 struct version_info *o = &ci->stages[0];
1290 struct version_info *a = &ci->stages[1];
1291 struct version_info *b = &ci->stages[2];
1293 clean_merge = handle_content_merge(opt, path, o, a, b,
1295 opt->priv->call_depth * 2,
1297 ci->merged.clean = clean_merge &&
1298 !ci->df_conflict && !ci->path_conflict;
1299 ci->merged.result.mode = merged_file.mode;
1300 ci->merged.is_null = (merged_file.mode == 0);
1301 oidcpy(&ci->merged.result.oid, &merged_file.oid);
1302 if (clean_merge && ci->df_conflict) {
1303 assert(df_file_index == 1 || df_file_index == 2);
1304 ci->filemask = 1 << df_file_index;
1305 ci->stages[df_file_index].mode = merged_file.mode;
1306 oidcpy(&ci->stages[df_file_index].oid, &merged_file.oid);
1309 const char *reason = _("content");
1310 if (ci->filemask == 6)
1311 reason = _("add/add");
1312 if (S_ISGITLINK(merged_file.mode))
1313 reason = _("submodule");
1314 path_msg(opt, path, 0,
1315 _("CONFLICT (%s): Merge conflict in %s"),
1318 } else if (ci->filemask == 3 || ci->filemask == 5) {
1320 const char *modify_branch, *delete_branch;
1321 int side = (ci->filemask == 5) ? 2 : 1;
1322 int index = opt->priv->call_depth ? 0 : side;
1324 ci->merged.result.mode = ci->stages[index].mode;
1325 oidcpy(&ci->merged.result.oid, &ci->stages[index].oid);
1326 ci->merged.clean = 0;
1328 modify_branch = (side == 1) ? opt->branch1 : opt->branch2;
1329 delete_branch = (side == 1) ? opt->branch2 : opt->branch1;
1331 path_msg(opt, path, 0,
1332 _("CONFLICT (modify/delete): %s deleted in %s "
1333 "and modified in %s. Version %s of %s left "
1335 path, delete_branch, modify_branch,
1336 modify_branch, path);
1337 } else if (ci->filemask == 2 || ci->filemask == 4) {
1338 /* Added on one side */
1339 int side = (ci->filemask == 4) ? 2 : 1;
1340 ci->merged.result.mode = ci->stages[side].mode;
1341 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1342 ci->merged.clean = !ci->df_conflict;
1343 } else if (ci->filemask == 1) {
1344 /* Deleted on both sides */
1345 ci->merged.is_null = 1;
1346 ci->merged.result.mode = 0;
1347 oidcpy(&ci->merged.result.oid, &null_oid);
1348 ci->merged.clean = 1;
1352 * If still conflicted, record it separately. This allows us to later
1353 * iterate over just conflicted entries when updating the index instead
1354 * of iterating over all entries.
1356 if (!ci->merged.clean)
1357 strmap_put(&opt->priv->conflicted, path, ci);
1358 record_entry_for_tree(dir_metadata, path, &ci->merged);
1361 static void process_entries(struct merge_options *opt,
1362 struct object_id *result_oid)
1364 struct hashmap_iter iter;
1365 struct strmap_entry *e;
1366 struct string_list plist = STRING_LIST_INIT_NODUP;
1367 struct string_list_item *entry;
1368 struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
1369 STRING_LIST_INIT_NODUP,
1372 if (strmap_empty(&opt->priv->paths)) {
1373 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
1377 /* Hack to pre-allocate plist to the desired size */
1378 ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
1380 /* Put every entry from paths into plist, then sort */
1381 strmap_for_each_entry(&opt->priv->paths, &iter, e) {
1382 string_list_append(&plist, e->key)->util = e->value;
1384 plist.cmp = string_list_df_name_compare;
1385 string_list_sort(&plist);
1388 * Iterate over the items in reverse order, so we can handle paths
1389 * below a directory before needing to handle the directory itself.
1391 * This allows us to write subtrees before we need to write trees,
1392 * and it also enables sane handling of directory/file conflicts
1393 * (because it allows us to know whether the directory is still in
1394 * the way when it is time to process the file at the same path).
1396 for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
1397 char *path = entry->string;
1399 * NOTE: mi may actually be a pointer to a conflict_info, but
1400 * we have to check mi->clean first to see if it's safe to
1401 * reassign to such a pointer type.
1403 struct merged_info *mi = entry->util;
1405 write_completed_directory(opt, mi->directory_name,
1408 record_entry_for_tree(&dir_metadata, path, mi);
1410 struct conflict_info *ci = (struct conflict_info *)mi;
1411 process_entry(opt, path, ci, &dir_metadata);
1415 if (dir_metadata.offsets.nr != 1 ||
1416 (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
1417 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
1418 dir_metadata.offsets.nr);
1419 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
1420 (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
1422 BUG("dir_metadata accounting completely off; shouldn't happen");
1424 write_tree(result_oid, &dir_metadata.versions, 0,
1425 opt->repo->hash_algo->rawsz);
1426 string_list_clear(&plist, 0);
1427 string_list_clear(&dir_metadata.versions, 0);
1428 string_list_clear(&dir_metadata.offsets, 0);
1431 /*** Function Grouping: functions related to merge_switch_to_result() ***/
1433 static int checkout(struct merge_options *opt,
1437 /* Switch the index/working copy from old to new */
1439 struct tree_desc trees[2];
1440 struct unpack_trees_options unpack_opts;
1442 memset(&unpack_opts, 0, sizeof(unpack_opts));
1443 unpack_opts.head_idx = -1;
1444 unpack_opts.src_index = opt->repo->index;
1445 unpack_opts.dst_index = opt->repo->index;
1447 setup_unpack_trees_porcelain(&unpack_opts, "merge");
1450 * NOTE: if this were just "git checkout" code, we would probably
1451 * read or refresh the cache and check for a conflicted index, but
1452 * builtin/merge.c or sequencer.c really needs to read the index
1453 * and check for conflicted entries before starting merging for a
1454 * good user experience (no sense waiting for merges/rebases before
1455 * erroring out), so there's no reason to duplicate that work here.
1458 /* 2-way merge to the new branch */
1459 unpack_opts.update = 1;
1460 unpack_opts.merge = 1;
1461 unpack_opts.quiet = 0; /* FIXME: sequencer might want quiet? */
1462 unpack_opts.verbose_update = (opt->verbosity > 2);
1463 unpack_opts.fn = twoway_merge;
1464 if (1/* FIXME: opts->overwrite_ignore*/) {
1465 unpack_opts.dir = xcalloc(1, sizeof(*unpack_opts.dir));
1466 unpack_opts.dir->flags |= DIR_SHOW_IGNORED;
1467 setup_standard_excludes(unpack_opts.dir);
1470 init_tree_desc(&trees[0], prev->buffer, prev->size);
1472 init_tree_desc(&trees[1], next->buffer, next->size);
1474 ret = unpack_trees(2, trees, &unpack_opts);
1475 clear_unpack_trees_porcelain(&unpack_opts);
1476 dir_clear(unpack_opts.dir);
1477 FREE_AND_NULL(unpack_opts.dir);
1481 static int record_conflicted_index_entries(struct merge_options *opt,
1482 struct index_state *index,
1483 struct strmap *paths,
1484 struct strmap *conflicted)
1486 struct hashmap_iter iter;
1487 struct strmap_entry *e;
1489 int original_cache_nr;
1491 if (strmap_empty(conflicted))
1494 original_cache_nr = index->cache_nr;
1496 /* Put every entry from paths into plist, then sort */
1497 strmap_for_each_entry(conflicted, &iter, e) {
1498 const char *path = e->key;
1499 struct conflict_info *ci = e->value;
1501 struct cache_entry *ce;
1507 * The index will already have a stage=0 entry for this path,
1508 * because we created an as-merged-as-possible version of the
1509 * file and checkout() moved the working copy and index over
1512 * However, previous iterations through this loop will have
1513 * added unstaged entries to the end of the cache which
1514 * ignore the standard alphabetical ordering of cache
1515 * entries and break invariants needed for index_name_pos()
1516 * to work. However, we know the entry we want is before
1517 * those appended cache entries, so do a temporary swap on
1518 * cache_nr to only look through entries of interest.
1520 SWAP(index->cache_nr, original_cache_nr);
1521 pos = index_name_pos(index, path, strlen(path));
1522 SWAP(index->cache_nr, original_cache_nr);
1524 if (ci->filemask != 1)
1525 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path);
1526 cache_tree_invalidate_path(index, path);
1528 ce = index->cache[pos];
1531 * Clean paths with CE_SKIP_WORKTREE set will not be
1532 * written to the working tree by the unpack_trees()
1533 * call in checkout(). Our conflicted entries would
1534 * have appeared clean to that code since we ignored
1535 * the higher order stages. Thus, we need override
1536 * the CE_SKIP_WORKTREE bit and manually write those
1537 * files to the working disk here.
1539 * TODO: Implement this CE_SKIP_WORKTREE fixup.
1543 * Mark this cache entry for removal and instead add
1544 * new stage>0 entries corresponding to the
1545 * conflicts. If there are many conflicted entries, we
1546 * want to avoid memmove'ing O(NM) entries by
1547 * inserting the new entries one at a time. So,
1548 * instead, we just add the new cache entries to the
1549 * end (ignoring normal index requirements on sort
1550 * order) and sort the index once we're all done.
1552 ce->ce_flags |= CE_REMOVE;
1555 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1556 struct version_info *vi;
1557 if (!(ci->filemask & (1ul << i)))
1559 vi = &ci->stages[i];
1560 ce = make_cache_entry(index, vi->mode, &vi->oid,
1562 add_index_entry(index, ce, ADD_CACHE_JUST_APPEND);
1567 * Remove the unused cache entries (and invalidate the relevant
1568 * cache-trees), then sort the index entries to get the conflicted
1569 * entries we added to the end into their right locations.
1571 remove_marked_cache_entries(index, 1);
1572 QSORT(index->cache, index->cache_nr, cmp_cache_name_compare);
1577 void merge_switch_to_result(struct merge_options *opt,
1579 struct merge_result *result,
1580 int update_worktree_and_index,
1581 int display_update_msgs)
1583 assert(opt->priv == NULL);
1584 if (result->clean >= 0 && update_worktree_and_index) {
1585 struct merge_options_internal *opti = result->priv;
1587 if (checkout(opt, head, result->tree)) {
1588 /* failure to function */
1593 if (record_conflicted_index_entries(opt, opt->repo->index,
1595 &opti->conflicted)) {
1596 /* failure to function */
1602 if (display_update_msgs) {
1603 struct merge_options_internal *opti = result->priv;
1604 struct hashmap_iter iter;
1605 struct strmap_entry *e;
1606 struct string_list olist = STRING_LIST_INIT_NODUP;
1609 /* Hack to pre-allocate olist to the desired size */
1610 ALLOC_GROW(olist.items, strmap_get_size(&opti->output),
1613 /* Put every entry from output into olist, then sort */
1614 strmap_for_each_entry(&opti->output, &iter, e) {
1615 string_list_append(&olist, e->key)->util = e->value;
1617 string_list_sort(&olist);
1619 /* Iterate over the items, printing them */
1620 for (i = 0; i < olist.nr; ++i) {
1621 struct strbuf *sb = olist.items[i].util;
1623 printf("%s", sb->buf);
1625 string_list_clear(&olist, 0);
1628 merge_finalize(opt, result);
1631 void merge_finalize(struct merge_options *opt,
1632 struct merge_result *result)
1634 struct merge_options_internal *opti = result->priv;
1636 assert(opt->priv == NULL);
1638 clear_internal_opts(opti, 0);
1639 FREE_AND_NULL(opti);
1642 /*** Function Grouping: helper functions for merge_incore_*() ***/
1644 static void merge_start(struct merge_options *opt, struct merge_result *result)
1646 /* Sanity checks on opt */
1649 assert(opt->branch1 && opt->branch2);
1651 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
1652 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
1653 assert(opt->rename_limit >= -1);
1654 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
1655 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
1657 assert(opt->xdl_opts >= 0);
1658 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
1659 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
1662 * detect_renames, verbosity, buffer_output, and obuf are ignored
1663 * fields that were used by "recursive" rather than "ort" -- but
1664 * sanity check them anyway.
1666 assert(opt->detect_renames >= -1 &&
1667 opt->detect_renames <= DIFF_DETECT_COPY);
1668 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
1669 assert(opt->buffer_output <= 2);
1670 assert(opt->obuf.len == 0);
1672 assert(opt->priv == NULL);
1674 /* Default to histogram diff. Actually, just hardcode it...for now. */
1675 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
1677 /* Initialization of opt->priv, our internal merge data */
1678 opt->priv = xcalloc(1, sizeof(*opt->priv));
1681 * Although we initialize opt->priv->paths with strdup_strings=0,
1682 * that's just to avoid making yet another copy of an allocated
1683 * string. Putting the entry into paths means we are taking
1684 * ownership, so we will later free it. paths_to_free is similar.
1686 * In contrast, conflicted just has a subset of keys from paths, so
1687 * we don't want to free those (it'd be a duplicate free).
1689 strmap_init_with_options(&opt->priv->paths, NULL, 0);
1690 strmap_init_with_options(&opt->priv->conflicted, NULL, 0);
1691 string_list_init(&opt->priv->paths_to_free, 0);
1694 * keys & strbufs in output will sometimes need to outlive "paths",
1695 * so it will have a copy of relevant keys. It's probably a small
1696 * subset of the overall paths that have special output.
1698 strmap_init(&opt->priv->output);
1701 /*** Function Grouping: merge_incore_*() and their internal variants ***/
1704 * Originally from merge_trees_internal(); heavily adapted, though.
1706 static void merge_ort_nonrecursive_internal(struct merge_options *opt,
1707 struct tree *merge_base,
1710 struct merge_result *result)
1712 struct object_id working_tree_oid;
1714 if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
1716 * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
1717 * base, and 2-3) the trees for the two trees we're merging.
1719 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
1720 oid_to_hex(&merge_base->object.oid),
1721 oid_to_hex(&side1->object.oid),
1722 oid_to_hex(&side2->object.oid));
1727 result->clean = detect_and_process_renames(opt, merge_base,
1729 process_entries(opt, &working_tree_oid);
1731 /* Set return values */
1732 result->tree = parse_tree_indirect(&working_tree_oid);
1733 /* existence of conflicted entries implies unclean */
1734 result->clean &= strmap_empty(&opt->priv->conflicted);
1735 if (!opt->priv->call_depth) {
1736 result->priv = opt->priv;
1741 void merge_incore_nonrecursive(struct merge_options *opt,
1742 struct tree *merge_base,
1745 struct merge_result *result)
1747 assert(opt->ancestor != NULL);
1748 merge_start(opt, result);
1749 merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
1752 void merge_incore_recursive(struct merge_options *opt,
1753 struct commit_list *merge_bases,
1754 struct commit *side1,
1755 struct commit *side2,
1756 struct merge_result *result)
1758 die("Not yet implemented");