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"
22 #include "object-store.h"
25 #include "xdiff-interface.h"
28 * We have many arrays of size 3. Whenever we have such an array, the
29 * indices refer to one of the sides of the three-way merge. This is so
30 * pervasive that the constants 0, 1, and 2 are used in many places in the
31 * code (especially in arithmetic operations to find the other side's index
32 * or to compute a relevant mask), but sometimes these enum names are used
33 * to aid code clarity.
35 * See also 'filemask' and 'dirmask' in struct conflict_info; the "ith side"
36 * referred to there is one of these three sides.
44 struct merge_options_internal {
46 * paths: primary data structure in all of merge ort.
49 * * are full relative paths from the toplevel of the repository
50 * (e.g. "drivers/firmware/raspberrypi.c").
51 * * store all relevant paths in the repo, both directories and
52 * files (e.g. drivers, drivers/firmware would also be included)
53 * * these keys serve to intern all the path strings, which allows
54 * us to do pointer comparison on directory names instead of
55 * strcmp; we just have to be careful to use the interned strings.
57 * The values of paths:
58 * * either a pointer to a merged_info, or a conflict_info struct
59 * * merged_info contains all relevant information for a
60 * non-conflicted entry.
61 * * conflict_info contains a merged_info, plus any additional
62 * information about a conflict such as the higher orders stages
63 * involved and the names of the paths those came from (handy
64 * once renames get involved).
65 * * a path may start "conflicted" (i.e. point to a conflict_info)
66 * and then a later step (e.g. three-way content merge) determines
67 * it can be cleanly merged, at which point it'll be marked clean
68 * and the algorithm will ignore any data outside the contained
69 * merged_info for that entry
70 * * If an entry remains conflicted, the merged_info portion of a
71 * conflict_info will later be filled with whatever version of
72 * the file should be placed in the working directory (e.g. an
73 * as-merged-as-possible variation that contains conflict markers).
78 * conflicted: a subset of keys->values from "paths"
80 * conflicted is basically an optimization between process_entries()
81 * and record_conflicted_index_entries(); the latter could loop over
82 * ALL the entries in paths AGAIN and look for the ones that are
83 * still conflicted, but since process_entries() has to loop over
84 * all of them, it saves the ones it couldn't resolve in this strmap
85 * so that record_conflicted_index_entries() can iterate just the
88 struct strmap conflicted;
91 * current_dir_name: temporary var used in collect_merge_info_callback()
93 * Used to set merged_info.directory_name; see documentation for that
94 * variable and the requirements placed on that field.
96 const char *current_dir_name;
98 /* call_depth: recursion level counter for merging merge bases */
102 struct version_info {
103 struct object_id oid;
108 /* if is_null, ignore result. otherwise result has oid & mode */
109 struct version_info result;
113 * clean: whether the path in question is cleanly merged.
115 * see conflict_info.merged for more details.
120 * basename_offset: offset of basename of path.
122 * perf optimization to avoid recomputing offset of final '/'
123 * character in pathname (0 if no '/' in pathname).
125 size_t basename_offset;
128 * directory_name: containing directory name.
130 * Note that we assume directory_name is constructed such that
131 * strcmp(dir1_name, dir2_name) == 0 iff dir1_name == dir2_name,
132 * i.e. string equality is equivalent to pointer equality. For this
133 * to hold, we have to be careful setting directory_name.
135 const char *directory_name;
138 struct conflict_info {
140 * merged: the version of the path that will be written to working tree
142 * WARNING: It is critical to check merged.clean and ensure it is 0
143 * before reading any conflict_info fields outside of merged.
144 * Allocated merge_info structs will always have clean set to 1.
145 * Allocated conflict_info structs will have merged.clean set to 0
146 * initially. The merged.clean field is how we know if it is safe
147 * to access other parts of conflict_info besides merged; if a
148 * conflict_info's merged.clean is changed to 1, the rest of the
149 * algorithm is not allowed to look at anything outside of the
150 * merged member anymore.
152 struct merged_info merged;
154 /* oids & modes from each of the three trees for this path */
155 struct version_info stages[3];
157 /* pathnames for each stage; may differ due to rename detection */
158 const char *pathnames[3];
160 /* Whether this path is/was involved in a directory/file conflict */
161 unsigned df_conflict:1;
164 * For filemask and dirmask, the ith bit corresponds to whether the
165 * ith entry is a file (filemask) or a directory (dirmask). Thus,
166 * filemask & dirmask is always zero, and filemask | dirmask is at
167 * most 7 but can be less when a path does not appear as either a
168 * file or a directory on at least one side of history.
170 * Note that these masks are related to enum merge_side, as the ith
171 * entry corresponds to side i.
173 * These values come from a traverse_trees() call; more info may be
174 * found looking at tree-walk.h's struct traverse_info,
175 * particularly the documentation above the "fn" member (note that
176 * filemask = mask & ~dirmask from that documentation).
182 * Optimization to track which stages match, to avoid the need to
183 * recompute it in multiple steps. Either 0 or at least 2 bits are
184 * set; if at least 2 bits are set, their corresponding stages match.
186 unsigned match_mask:3;
190 * For the next three macros, see warning for conflict_info.merged.
192 * In each of the below, mi is a struct merged_info*, and ci was defined
193 * as a struct conflict_info* (but we need to verify ci isn't actually
194 * pointed at a struct merged_info*).
196 * INITIALIZE_CI: Assign ci to mi but only if it's safe; set to NULL otherwise.
197 * VERIFY_CI: Ensure that something we assigned to a conflict_info* is one.
198 * ASSIGN_AND_VERIFY_CI: Similar to VERIFY_CI but do assignment first.
200 #define INITIALIZE_CI(ci, mi) do { \
201 (ci) = (!(mi) || (mi)->clean) ? NULL : (struct conflict_info *)(mi); \
203 #define VERIFY_CI(ci) assert(ci && !ci->merged.clean);
204 #define ASSIGN_AND_VERIFY_CI(ci, mi) do { \
205 (ci) = (struct conflict_info *)(mi); \
206 assert((ci) && !(mi)->clean); \
209 static int err(struct merge_options *opt, const char *err, ...)
212 struct strbuf sb = STRBUF_INIT;
214 strbuf_addstr(&sb, "error: ");
215 va_start(params, err);
216 strbuf_vaddf(&sb, err, params);
225 static void setup_path_info(struct merge_options *opt,
226 struct string_list_item *result,
227 const char *current_dir_name,
228 int current_dir_name_len,
229 char *fullpath, /* we'll take over ownership */
230 struct name_entry *names,
231 struct name_entry *merged_version,
232 unsigned is_null, /* boolean */
233 unsigned df_conflict, /* boolean */
236 int resolved /* boolean */)
238 /* result->util is void*, so mi is a convenience typed variable */
239 struct merged_info *mi;
241 assert(!is_null || resolved);
242 assert(!df_conflict || !resolved); /* df_conflict implies !resolved */
243 assert(resolved == (merged_version != NULL));
245 mi = xcalloc(1, resolved ? sizeof(struct merged_info) :
246 sizeof(struct conflict_info));
247 mi->directory_name = current_dir_name;
248 mi->basename_offset = current_dir_name_len;
249 mi->clean = !!resolved;
251 mi->result.mode = merged_version->mode;
252 oidcpy(&mi->result.oid, &merged_version->oid);
253 mi->is_null = !!is_null;
256 struct conflict_info *ci;
258 ASSIGN_AND_VERIFY_CI(ci, mi);
259 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
260 ci->pathnames[i] = fullpath;
261 ci->stages[i].mode = names[i].mode;
262 oidcpy(&ci->stages[i].oid, &names[i].oid);
264 ci->filemask = filemask;
265 ci->dirmask = dirmask;
266 ci->df_conflict = !!df_conflict;
269 * Assume is_null for now, but if we have entries
270 * under the directory then when it is complete in
271 * write_completed_directory() it'll update this.
272 * Also, for D/F conflicts, we have to handle the
273 * directory first, then clear this bit and process
274 * the file to see how it is handled -- that occurs
275 * near the top of process_entry().
279 strmap_put(&opt->priv->paths, fullpath, mi);
280 result->string = fullpath;
284 static int collect_merge_info_callback(int n,
286 unsigned long dirmask,
287 struct name_entry *names,
288 struct traverse_info *info)
292 * common ancestor (mbase) has mask 1, and stored in index 0 of names
293 * head of side 1 (side1) has mask 2, and stored in index 1 of names
294 * head of side 2 (side2) has mask 4, and stored in index 2 of names
296 struct merge_options *opt = info->data;
297 struct merge_options_internal *opti = opt->priv;
298 struct string_list_item pi; /* Path Info */
299 struct conflict_info *ci; /* typed alias to pi.util (which is void*) */
300 struct name_entry *p;
303 const char *dirname = opti->current_dir_name;
304 unsigned filemask = mask & ~dirmask;
305 unsigned match_mask = 0; /* will be updated below */
306 unsigned mbase_null = !(mask & 1);
307 unsigned side1_null = !(mask & 2);
308 unsigned side2_null = !(mask & 4);
309 unsigned side1_matches_mbase = (!side1_null && !mbase_null &&
310 names[0].mode == names[1].mode &&
311 oideq(&names[0].oid, &names[1].oid));
312 unsigned side2_matches_mbase = (!side2_null && !mbase_null &&
313 names[0].mode == names[2].mode &&
314 oideq(&names[0].oid, &names[2].oid));
315 unsigned sides_match = (!side1_null && !side2_null &&
316 names[1].mode == names[2].mode &&
317 oideq(&names[1].oid, &names[2].oid));
320 * Note: When a path is a file on one side of history and a directory
321 * in another, we have a directory/file conflict. In such cases, if
322 * the conflict doesn't resolve from renames and deletions, then we
323 * always leave directories where they are and move files out of the
324 * way. Thus, while struct conflict_info has a df_conflict field to
325 * track such conflicts, we ignore that field for any directories at
326 * a path and only pay attention to it for files at the given path.
327 * The fact that we leave directories were they are also means that
328 * we do not need to worry about getting additional df_conflict
329 * information propagated from parent directories down to children
330 * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
331 * sets a newinfo.df_conflicts field specifically to propagate it).
333 unsigned df_conflict = (filemask != 0) && (dirmask != 0);
335 /* n = 3 is a fundamental assumption. */
337 BUG("Called collect_merge_info_callback wrong");
340 * A bunch of sanity checks verifying that traverse_trees() calls
341 * us the way I expect. Could just remove these at some point,
342 * though maybe they are helpful to future code readers.
344 assert(mbase_null == is_null_oid(&names[0].oid));
345 assert(side1_null == is_null_oid(&names[1].oid));
346 assert(side2_null == is_null_oid(&names[2].oid));
347 assert(!mbase_null || !side1_null || !side2_null);
348 assert(mask > 0 && mask < 8);
350 /* Determine match_mask */
351 if (side1_matches_mbase)
352 match_mask = (side2_matches_mbase ? 7 : 3);
353 else if (side2_matches_mbase)
355 else if (sides_match)
359 * Get the name of the relevant filepath, which we'll pass to
360 * setup_path_info() for tracking.
365 len = traverse_path_len(info, p->pathlen);
367 /* +1 in both of the following lines to include the NUL byte */
368 fullpath = xmalloc(len + 1);
369 make_traverse_path(fullpath, len + 1, info, p->path, p->pathlen);
372 * If mbase, side1, and side2 all match, we can resolve early. Even
373 * if these are trees, there will be no renames or anything
376 if (side1_matches_mbase && side2_matches_mbase) {
377 /* mbase, side1, & side2 all match; use mbase as resolution */
378 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
379 names, names+0, mbase_null, 0,
380 filemask, dirmask, 1);
385 * Record information about the path so we can resolve later in
388 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
389 names, NULL, 0, df_conflict, filemask, dirmask, 0);
393 ci->match_mask = match_mask;
395 /* If dirmask, recurse into subdirectories */
397 struct traverse_info newinfo;
398 struct tree_desc t[3];
399 void *buf[3] = {NULL, NULL, NULL};
400 const char *original_dir_name;
403 ci->match_mask &= filemask;
406 newinfo.name = p->path;
407 newinfo.namelen = p->pathlen;
408 newinfo.pathlen = st_add3(newinfo.pathlen, p->pathlen, 1);
410 * If this directory we are about to recurse into cared about
411 * its parent directory (the current directory) having a D/F
412 * conflict, then we'd propagate the masks in this way:
413 * newinfo.df_conflicts |= (mask & ~dirmask);
414 * But we don't worry about propagating D/F conflicts. (See
415 * comment near setting of local df_conflict variable near
416 * the beginning of this function).
419 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
420 if (i == 1 && side1_matches_mbase)
422 else if (i == 2 && side2_matches_mbase)
424 else if (i == 2 && sides_match)
427 const struct object_id *oid = NULL;
430 buf[i] = fill_tree_descriptor(opt->repo,
436 original_dir_name = opti->current_dir_name;
437 opti->current_dir_name = pi.string;
438 ret = traverse_trees(NULL, 3, t, &newinfo);
439 opti->current_dir_name = original_dir_name;
441 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
451 static int collect_merge_info(struct merge_options *opt,
452 struct tree *merge_base,
457 struct tree_desc t[3];
458 struct traverse_info info;
459 const char *toplevel_dir_placeholder = "";
461 opt->priv->current_dir_name = toplevel_dir_placeholder;
462 setup_traverse_info(&info, toplevel_dir_placeholder);
463 info.fn = collect_merge_info_callback;
465 info.show_all_errors = 1;
467 parse_tree(merge_base);
470 init_tree_desc(t + 0, merge_base->buffer, merge_base->size);
471 init_tree_desc(t + 1, side1->buffer, side1->size);
472 init_tree_desc(t + 2, side2->buffer, side2->size);
474 ret = traverse_trees(NULL, 3, t, &info);
479 static int detect_and_process_renames(struct merge_options *opt,
480 struct tree *merge_base,
487 * Rename detection works by detecting file similarity. Here we use
488 * a really easy-to-implement scheme: files are similar IFF they have
489 * the same filename. Therefore, by this scheme, there are no renames.
491 * TODO: Actually implement a real rename detection scheme.
496 static int string_list_df_name_compare(const char *one, const char *two)
498 int onelen = strlen(one);
499 int twolen = strlen(two);
501 * Here we only care that entries for D/F conflicts are
502 * adjacent, in particular with the file of the D/F conflict
503 * appearing before files below the corresponding directory.
504 * The order of the rest of the list is irrelevant for us.
506 * To achieve this, we sort with df_name_compare and provide
507 * the mode S_IFDIR so that D/F conflicts will sort correctly.
508 * We use the mode S_IFDIR for everything else for simplicity,
509 * since in other cases any changes in their order due to
510 * sorting cause no problems for us.
512 int cmp = df_name_compare(one, onelen, S_IFDIR,
513 two, twolen, S_IFDIR);
515 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
516 * that 'foo' comes before 'foo/bar'.
520 return onelen - twolen;
523 struct directory_versions {
525 * versions: list of (basename -> version_info)
527 * The basenames are in reverse lexicographic order of full pathnames,
528 * as processed in process_entries(). This puts all entries within
529 * a directory together, and covers the directory itself after
530 * everything within it, allowing us to write subtrees before needing
531 * to record information for the tree itself.
533 struct string_list versions;
536 * offsets: list of (full relative path directories -> integer offsets)
538 * Since versions contains basenames from files in multiple different
539 * directories, we need to know which entries in versions correspond
540 * to which directories. Values of e.g.
544 * Would mean that entries 0-1 of versions are files in the toplevel
545 * directory, entries 2-4 are files under src/, and the remaining
546 * entries starting at index 5 are files under src/moduleA/.
548 struct string_list offsets;
551 * last_directory: directory that previously processed file found in
553 * last_directory starts NULL, but records the directory in which the
554 * previous file was found within. As soon as
555 * directory(current_file) != last_directory
556 * then we need to start updating accounting in versions & offsets.
557 * Note that last_directory is always the last path in "offsets" (or
558 * NULL if "offsets" is empty) so this exists just for quick access.
560 const char *last_directory;
562 /* last_directory_len: cached computation of strlen(last_directory) */
563 unsigned last_directory_len;
566 static int tree_entry_order(const void *a_, const void *b_)
568 const struct string_list_item *a = a_;
569 const struct string_list_item *b = b_;
571 const struct merged_info *ami = a->util;
572 const struct merged_info *bmi = b->util;
573 return base_name_compare(a->string, strlen(a->string), ami->result.mode,
574 b->string, strlen(b->string), bmi->result.mode);
577 static void write_tree(struct object_id *result_oid,
578 struct string_list *versions,
582 size_t maxlen = 0, extra;
583 unsigned int nr = versions->nr - offset;
584 struct strbuf buf = STRBUF_INIT;
585 struct string_list relevant_entries = STRING_LIST_INIT_NODUP;
589 * We want to sort the last (versions->nr-offset) entries in versions.
590 * Do so by abusing the string_list API a bit: make another string_list
591 * that contains just those entries and then sort them.
593 * We won't use relevant_entries again and will let it just pop off the
594 * stack, so there won't be allocation worries or anything.
596 relevant_entries.items = versions->items + offset;
597 relevant_entries.nr = versions->nr - offset;
598 QSORT(relevant_entries.items, relevant_entries.nr, tree_entry_order);
600 /* Pre-allocate some space in buf */
601 extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
602 for (i = 0; i < nr; i++) {
603 maxlen += strlen(versions->items[offset+i].string) + extra;
605 strbuf_grow(&buf, maxlen);
607 /* Write each entry out to buf */
608 for (i = 0; i < nr; i++) {
609 struct merged_info *mi = versions->items[offset+i].util;
610 struct version_info *ri = &mi->result;
611 strbuf_addf(&buf, "%o %s%c",
613 versions->items[offset+i].string, '\0');
614 strbuf_add(&buf, ri->oid.hash, hash_size);
617 /* Write this object file out, and record in result_oid */
618 write_object_file(buf.buf, buf.len, tree_type, result_oid);
619 strbuf_release(&buf);
622 static void record_entry_for_tree(struct directory_versions *dir_metadata,
624 struct merged_info *mi)
626 const char *basename;
629 /* nothing to record */
632 basename = path + mi->basename_offset;
633 assert(strchr(basename, '/') == NULL);
634 string_list_append(&dir_metadata->versions,
635 basename)->util = &mi->result;
638 static void write_completed_directory(struct merge_options *opt,
639 const char *new_directory_name,
640 struct directory_versions *info)
642 const char *prev_dir;
643 struct merged_info *dir_info = NULL;
647 * Some explanation of info->versions and info->offsets...
649 * process_entries() iterates over all relevant files AND
650 * directories in reverse lexicographic order, and calls this
651 * function. Thus, an example of the paths that process_entries()
652 * could operate on (along with the directories for those paths
657 * src/moduleB/umm.c src/moduleB
658 * src/moduleB/stuff.h src/moduleB
659 * src/moduleB/baz.c src/moduleB
661 * src/moduleA/foo.c src/moduleA
662 * src/moduleA/bar.c src/moduleA
669 * always contains the unprocessed entries and their
670 * version_info information. For example, after the first five
671 * entries above, info->versions would be:
673 * xtract.c <xtract.c's version_info>
674 * token.txt <token.txt's version_info>
675 * umm.c <src/moduleB/umm.c's version_info>
676 * stuff.h <src/moduleB/stuff.h's version_info>
677 * baz.c <src/moduleB/baz.c's version_info>
679 * Once a subdirectory is completed we remove the entries in
680 * that subdirectory from info->versions, writing it as a tree
681 * (write_tree()). Thus, as soon as we get to src/moduleB,
682 * info->versions would be updated to
684 * xtract.c <xtract.c's version_info>
685 * token.txt <token.txt's version_info>
686 * moduleB <src/moduleB's version_info>
690 * helps us track which entries in info->versions correspond to
691 * which directories. When we are N directories deep (e.g. 4
692 * for src/modA/submod/subdir/), we have up to N+1 unprocessed
693 * directories (+1 because of toplevel dir). Corresponding to
694 * the info->versions example above, after processing five entries
695 * info->offsets will be:
700 * which is used to know that xtract.c & token.txt are from the
701 * toplevel dirctory, while umm.c & stuff.h & baz.c are from the
702 * src/moduleB directory. Again, following the example above,
703 * once we need to process src/moduleB, then info->offsets is
709 * which says that moduleB (and only moduleB so far) is in the
712 * One unique thing to note about info->offsets here is that
713 * "src" was not added to info->offsets until there was a path
714 * (a file OR directory) immediately below src/ that got
717 * Since process_entry() just appends new entries to info->versions,
718 * write_completed_directory() only needs to do work if the next path
719 * is in a directory that is different than the last directory found
724 * If we are working with the same directory as the last entry, there
725 * is no work to do. (See comments above the directory_name member of
726 * struct merged_info for why we can use pointer comparison instead of
729 if (new_directory_name == info->last_directory)
733 * If we are just starting (last_directory is NULL), or last_directory
734 * is a prefix of the current directory, then we can just update
735 * info->offsets to record the offset where we started this directory
736 * and update last_directory to have quick access to it.
738 if (info->last_directory == NULL ||
739 !strncmp(new_directory_name, info->last_directory,
740 info->last_directory_len)) {
741 uintptr_t offset = info->versions.nr;
743 info->last_directory = new_directory_name;
744 info->last_directory_len = strlen(info->last_directory);
746 * Record the offset into info->versions where we will
747 * start recording basenames of paths found within
748 * new_directory_name.
750 string_list_append(&info->offsets,
751 info->last_directory)->util = (void*)offset;
756 * The next entry that will be processed will be within
757 * new_directory_name. Since at this point we know that
758 * new_directory_name is within a different directory than
759 * info->last_directory, we have all entries for info->last_directory
760 * in info->versions and we need to create a tree object for them.
762 dir_info = strmap_get(&opt->priv->paths, info->last_directory);
764 offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
765 if (offset == info->versions.nr) {
767 * Actually, we don't need to create a tree object in this
768 * case. Whenever all files within a directory disappear
769 * during the merge (e.g. unmodified on one side and
770 * deleted on the other, or files were renamed elsewhere),
771 * then we get here and the directory itself needs to be
772 * omitted from its parent tree as well.
774 dir_info->is_null = 1;
777 * Write out the tree to the git object directory, and also
778 * record the mode and oid in dir_info->result.
780 dir_info->is_null = 0;
781 dir_info->result.mode = S_IFDIR;
782 write_tree(&dir_info->result.oid, &info->versions, offset,
783 opt->repo->hash_algo->rawsz);
787 * We've now used several entries from info->versions and one entry
788 * from info->offsets, so we get rid of those values.
791 info->versions.nr = offset;
794 * Now we've taken care of the completed directory, but we need to
795 * prepare things since future entries will be in
796 * new_directory_name. (In particular, process_entry() will be
797 * appending new entries to info->versions.) So, we need to make
798 * sure new_directory_name is the last entry in info->offsets.
800 prev_dir = info->offsets.nr == 0 ? NULL :
801 info->offsets.items[info->offsets.nr-1].string;
802 if (new_directory_name != prev_dir) {
803 uintptr_t c = info->versions.nr;
804 string_list_append(&info->offsets,
805 new_directory_name)->util = (void*)c;
808 /* And, of course, we need to update last_directory to match. */
809 info->last_directory = new_directory_name;
810 info->last_directory_len = strlen(info->last_directory);
813 /* Per entry merge function */
814 static void process_entry(struct merge_options *opt,
816 struct conflict_info *ci,
817 struct directory_versions *dir_metadata)
820 assert(ci->filemask >= 0 && ci->filemask <= 7);
821 /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
822 assert(ci->match_mask == 0 || ci->match_mask == 3 ||
823 ci->match_mask == 5 || ci->match_mask == 6);
826 record_entry_for_tree(dir_metadata, path, &ci->merged);
827 if (ci->filemask == 0)
828 /* nothing else to handle */
830 assert(ci->df_conflict);
833 if (ci->df_conflict) {
834 die("Not yet implemented.");
838 * NOTE: Below there is a long switch-like if-elseif-elseif... block
839 * which the code goes through even for the df_conflict cases
840 * above. Well, it will once we don't die-not-implemented above.
842 if (ci->match_mask) {
843 ci->merged.clean = 1;
844 if (ci->match_mask == 6) {
845 /* stages[1] == stages[2] */
846 ci->merged.result.mode = ci->stages[1].mode;
847 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
849 /* determine the mask of the side that didn't match */
850 unsigned int othermask = 7 & ~ci->match_mask;
851 int side = (othermask == 4) ? 2 : 1;
853 ci->merged.result.mode = ci->stages[side].mode;
854 ci->merged.is_null = !ci->merged.result.mode;
855 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
857 assert(othermask == 2 || othermask == 4);
858 assert(ci->merged.is_null ==
859 (ci->filemask == ci->match_mask));
861 } else if (ci->filemask >= 6 &&
862 (S_IFMT & ci->stages[1].mode) !=
863 (S_IFMT & ci->stages[2].mode)) {
865 * Two different items from (file/submodule/symlink)
867 die("Not yet implemented.");
868 } else if (ci->filemask >= 6) {
870 * TODO: Needs a two-way or three-way content merge, but we're
871 * just being lazy and copying the version from HEAD and
872 * leaving it as conflicted.
874 ci->merged.clean = 0;
875 ci->merged.result.mode = ci->stages[1].mode;
876 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
877 } else if (ci->filemask == 3 || ci->filemask == 5) {
879 die("Not yet implemented.");
880 } else if (ci->filemask == 2 || ci->filemask == 4) {
881 /* Added on one side */
882 int side = (ci->filemask == 4) ? 2 : 1;
883 ci->merged.result.mode = ci->stages[side].mode;
884 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
885 ci->merged.clean = !ci->df_conflict;
886 } else if (ci->filemask == 1) {
887 /* Deleted on both sides */
888 ci->merged.is_null = 1;
889 ci->merged.result.mode = 0;
890 oidcpy(&ci->merged.result.oid, &null_oid);
891 ci->merged.clean = 1;
895 * If still conflicted, record it separately. This allows us to later
896 * iterate over just conflicted entries when updating the index instead
897 * of iterating over all entries.
899 if (!ci->merged.clean)
900 strmap_put(&opt->priv->conflicted, path, ci);
901 record_entry_for_tree(dir_metadata, path, &ci->merged);
904 static void process_entries(struct merge_options *opt,
905 struct object_id *result_oid)
907 struct hashmap_iter iter;
908 struct strmap_entry *e;
909 struct string_list plist = STRING_LIST_INIT_NODUP;
910 struct string_list_item *entry;
911 struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
912 STRING_LIST_INIT_NODUP,
915 if (strmap_empty(&opt->priv->paths)) {
916 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
920 /* Hack to pre-allocate plist to the desired size */
921 ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
923 /* Put every entry from paths into plist, then sort */
924 strmap_for_each_entry(&opt->priv->paths, &iter, e) {
925 string_list_append(&plist, e->key)->util = e->value;
927 plist.cmp = string_list_df_name_compare;
928 string_list_sort(&plist);
931 * Iterate over the items in reverse order, so we can handle paths
932 * below a directory before needing to handle the directory itself.
934 * This allows us to write subtrees before we need to write trees,
935 * and it also enables sane handling of directory/file conflicts
936 * (because it allows us to know whether the directory is still in
937 * the way when it is time to process the file at the same path).
939 for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
940 char *path = entry->string;
942 * NOTE: mi may actually be a pointer to a conflict_info, but
943 * we have to check mi->clean first to see if it's safe to
944 * reassign to such a pointer type.
946 struct merged_info *mi = entry->util;
948 write_completed_directory(opt, mi->directory_name,
951 record_entry_for_tree(&dir_metadata, path, mi);
953 struct conflict_info *ci = (struct conflict_info *)mi;
954 process_entry(opt, path, ci, &dir_metadata);
958 if (dir_metadata.offsets.nr != 1 ||
959 (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
960 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
961 dir_metadata.offsets.nr);
962 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
963 (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
965 BUG("dir_metadata accounting completely off; shouldn't happen");
967 write_tree(result_oid, &dir_metadata.versions, 0,
968 opt->repo->hash_algo->rawsz);
969 string_list_clear(&plist, 0);
970 string_list_clear(&dir_metadata.versions, 0);
971 string_list_clear(&dir_metadata.offsets, 0);
974 static int checkout(struct merge_options *opt,
978 die("Not yet implemented.");
981 static int record_conflicted_index_entries(struct merge_options *opt,
982 struct index_state *index,
983 struct strmap *paths,
984 struct strmap *conflicted)
986 if (strmap_empty(conflicted))
989 die("Not yet implemented.");
992 void merge_switch_to_result(struct merge_options *opt,
994 struct merge_result *result,
995 int update_worktree_and_index,
996 int display_update_msgs)
998 assert(opt->priv == NULL);
999 if (result->clean >= 0 && update_worktree_and_index) {
1000 struct merge_options_internal *opti = result->priv;
1002 if (checkout(opt, head, result->tree)) {
1003 /* failure to function */
1008 if (record_conflicted_index_entries(opt, opt->repo->index,
1010 &opti->conflicted)) {
1011 /* failure to function */
1017 if (display_update_msgs) {
1018 /* TODO: print out CONFLICT and other informational messages. */
1021 merge_finalize(opt, result);
1024 void merge_finalize(struct merge_options *opt,
1025 struct merge_result *result)
1027 die("Not yet implemented");
1030 static void merge_start(struct merge_options *opt, struct merge_result *result)
1032 /* Sanity checks on opt */
1035 assert(opt->branch1 && opt->branch2);
1037 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
1038 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
1039 assert(opt->rename_limit >= -1);
1040 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
1041 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
1043 assert(opt->xdl_opts >= 0);
1044 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
1045 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
1048 * detect_renames, verbosity, buffer_output, and obuf are ignored
1049 * fields that were used by "recursive" rather than "ort" -- but
1050 * sanity check them anyway.
1052 assert(opt->detect_renames >= -1 &&
1053 opt->detect_renames <= DIFF_DETECT_COPY);
1054 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
1055 assert(opt->buffer_output <= 2);
1056 assert(opt->obuf.len == 0);
1058 assert(opt->priv == NULL);
1060 /* Default to histogram diff. Actually, just hardcode it...for now. */
1061 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
1063 /* Initialization of opt->priv, our internal merge data */
1064 opt->priv = xcalloc(1, sizeof(*opt->priv));
1067 * Although we initialize opt->priv->paths with strdup_strings=0,
1068 * that's just to avoid making yet another copy of an allocated
1069 * string. Putting the entry into paths means we are taking
1070 * ownership, so we will later free it.
1072 * In contrast, conflicted just has a subset of keys from paths, so
1073 * we don't want to free those (it'd be a duplicate free).
1075 strmap_init_with_options(&opt->priv->paths, NULL, 0);
1076 strmap_init_with_options(&opt->priv->conflicted, NULL, 0);
1080 * Originally from merge_trees_internal(); heavily adapted, though.
1082 static void merge_ort_nonrecursive_internal(struct merge_options *opt,
1083 struct tree *merge_base,
1086 struct merge_result *result)
1088 struct object_id working_tree_oid;
1090 if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
1092 * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
1093 * base, and 2-3) the trees for the two trees we're merging.
1095 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
1096 oid_to_hex(&merge_base->object.oid),
1097 oid_to_hex(&side1->object.oid),
1098 oid_to_hex(&side2->object.oid));
1103 result->clean = detect_and_process_renames(opt, merge_base,
1105 process_entries(opt, &working_tree_oid);
1107 /* Set return values */
1108 result->tree = parse_tree_indirect(&working_tree_oid);
1109 /* existence of conflicted entries implies unclean */
1110 result->clean &= strmap_empty(&opt->priv->conflicted);
1111 if (!opt->priv->call_depth) {
1112 result->priv = opt->priv;
1117 void merge_incore_nonrecursive(struct merge_options *opt,
1118 struct tree *merge_base,
1121 struct merge_result *result)
1123 assert(opt->ancestor != NULL);
1124 merge_start(opt, result);
1125 merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
1128 void merge_incore_recursive(struct merge_options *opt,
1129 struct commit_list *merge_bases,
1130 struct commit *side1,
1131 struct commit *side2,
1132 struct merge_result *result)
1134 die("Not yet implemented");