merge-ort: implement unique_path() helper
[git/debian.git] / merge-ort.c
blob1adc27a11bcc34c7e9b87bed4eaf03e1de95f9dd
1 /*
2 * "Ostensibly Recursive's Twin" merge strategy, or "ort" for short. Meant
3 * as a drop-in replacement for the "recursive" merge strategy, allowing one
4 * to replace
6 * git merge [-s recursive]
8 * with
10 * git merge -s ort
12 * Note: git's parser allows the space between '-s' and its argument to be
13 * missing. (Should I have backronymed "ham", "alsa", "kip", "nap, "alvo",
14 * "cale", "peedy", or "ins" instead of "ort"?)
17 #include "cache.h"
18 #include "merge-ort.h"
20 #include "blob.h"
21 #include "cache-tree.h"
22 #include "commit-reach.h"
23 #include "diff.h"
24 #include "diffcore.h"
25 #include "dir.h"
26 #include "object-store.h"
27 #include "strmap.h"
28 #include "tree.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.
43 enum merge_side {
44 MERGE_BASE = 0,
45 MERGE_SIDE1 = 1,
46 MERGE_SIDE2 = 2
49 struct merge_options_internal {
51 * paths: primary data structure in all of merge ort.
53 * The keys of paths:
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).
82 struct strmap paths;
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
93 * relevant entries.
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 */
125 int call_depth;
128 struct version_info {
129 struct object_id oid;
130 unsigned short mode;
133 struct merged_info {
134 /* if is_null, ignore result. otherwise result has oid & mode */
135 struct version_info result;
136 unsigned is_null:1;
139 * clean: whether the path in question is cleanly merged.
141 * see conflict_info.merged for more details.
143 unsigned clean:1;
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).
211 unsigned filemask:3;
212 unsigned dirmask:3;
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); \
237 } while (0)
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); \
242 } while (0)
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,
255 int reinitialize)
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;
287 if (!reinitialize) {
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;
294 strbuf_release(sb);
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.
303 free(sb);
305 strmap_clear(&opti->output, 0);
309 static int err(struct merge_options *opt, const char *err, ...)
311 va_list params;
312 struct strbuf sb = STRBUF_INIT;
314 strbuf_addstr(&sb, "error: ");
315 va_start(params, err);
316 strbuf_vaddf(&sb, err, params);
317 va_end(params);
319 error("%s", sb.buf);
320 strbuf_release(&sb);
322 return -1;
325 __attribute__((format (printf, 4, 5)))
326 static void path_msg(struct merge_options *opt,
327 const char *path,
328 int omittable_hint, /* skippable under --remerge-diff */
329 const char *fmt, ...)
331 va_list ap;
332 struct strbuf *sb = strmap_get(&opt->priv->output, path);
333 if (!sb) {
334 sb = xmalloc(sizeof(*sb));
335 strbuf_init(sb, 0);
336 strmap_put(&opt->priv->output, path, sb);
339 va_start(ap, fmt);
340 strbuf_vaddf(sb, fmt, ap);
341 va_end(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)
349 size_t i = out->len;
350 strbuf_addstr(out, s);
351 for (; i < out->len; i++)
352 if (out->buf[i] == '/')
353 out->buf[i] = '_';
356 static char *unique_path(struct strmap *existing_paths,
357 const char *path,
358 const char *branch)
360 struct strbuf newpath = STRBUF_INIT;
361 int suffix = 0;
362 size_t base_len;
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 */
387 unsigned filemask,
388 unsigned dirmask,
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;
403 if (resolved) {
404 mi->result.mode = merged_version->mode;
405 oidcpy(&mi->result.oid, &merged_version->oid);
406 mi->is_null = !!is_null;
407 } else {
408 int i;
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;
420 if (dirmask)
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().
430 mi->is_null = 1;
432 strmap_put(&opt->priv->paths, fullpath, mi);
433 result->string = fullpath;
434 result->util = mi;
437 static int collect_merge_info_callback(int n,
438 unsigned long mask,
439 unsigned long dirmask,
440 struct name_entry *names,
441 struct traverse_info *info)
444 * n is 3. Always.
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;
454 size_t len;
455 char *fullpath;
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. */
489 if (n != 3)
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)
507 match_mask = 5;
508 else if (sides_match)
509 match_mask = 6;
512 * Get the name of the relevant filepath, which we'll pass to
513 * setup_path_info() for tracking.
515 p = names;
516 while (!p->mode)
517 p++;
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
527 * underneath.
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);
534 return mask;
538 * Record information about the path so we can resolve later in
539 * process_entries.
541 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
542 names, NULL, 0, df_conflict, filemask, dirmask, 0);
544 ci = pi.util;
545 VERIFY_CI(ci);
546 ci->match_mask = match_mask;
548 /* If dirmask, recurse into subdirectories */
549 if (dirmask) {
550 struct traverse_info newinfo;
551 struct tree_desc t[3];
552 void *buf[3] = {NULL, NULL, NULL};
553 const char *original_dir_name;
554 int i, ret;
556 ci->match_mask &= filemask;
557 newinfo = *info;
558 newinfo.prev = info;
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)
574 t[1] = t[0];
575 else if (i == 2 && side2_matches_mbase)
576 t[2] = t[0];
577 else if (i == 2 && sides_match)
578 t[2] = t[1];
579 else {
580 const struct object_id *oid = NULL;
581 if (dirmask & 1)
582 oid = &names[i].oid;
583 buf[i] = fill_tree_descriptor(opt->repo,
584 t + i, oid);
586 dirmask >>= 1;
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++)
595 free(buf[i]);
597 if (ret < 0)
598 return -1;
601 return mask;
604 static int collect_merge_info(struct merge_options *opt,
605 struct tree *merge_base,
606 struct tree *side1,
607 struct tree *side2)
609 int ret;
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;
617 info.data = opt;
618 info.show_all_errors = 1;
620 parse_tree(merge_base);
621 parse_tree(side1);
622 parse_tree(side2);
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);
629 return ret;
632 /*** Function Grouping: functions related to threeway content merges ***/
634 static int handle_content_merge(struct merge_options *opt,
635 const char *path,
636 const struct version_info *o,
637 const struct version_info *a,
638 const struct version_info *b,
639 const char *pathnames[3],
640 const int extra_marker_size,
641 struct version_info *result)
643 die("Not yet implemented");
646 /*** Function Grouping: functions related to detect_and_process_renames(), ***
647 *** which are split into directory and regular rename detection sections. ***/
649 /*** Function Grouping: functions related to directory rename detection ***/
651 /*** Function Grouping: functions related to regular rename detection ***/
653 static int detect_and_process_renames(struct merge_options *opt,
654 struct tree *merge_base,
655 struct tree *side1,
656 struct tree *side2)
658 int clean = 1;
661 * Rename detection works by detecting file similarity. Here we use
662 * a really easy-to-implement scheme: files are similar IFF they have
663 * the same filename. Therefore, by this scheme, there are no renames.
665 * TODO: Actually implement a real rename detection scheme.
667 return clean;
670 /*** Function Grouping: functions related to process_entries() ***/
672 static int string_list_df_name_compare(const char *one, const char *two)
674 int onelen = strlen(one);
675 int twolen = strlen(two);
677 * Here we only care that entries for D/F conflicts are
678 * adjacent, in particular with the file of the D/F conflict
679 * appearing before files below the corresponding directory.
680 * The order of the rest of the list is irrelevant for us.
682 * To achieve this, we sort with df_name_compare and provide
683 * the mode S_IFDIR so that D/F conflicts will sort correctly.
684 * We use the mode S_IFDIR for everything else for simplicity,
685 * since in other cases any changes in their order due to
686 * sorting cause no problems for us.
688 int cmp = df_name_compare(one, onelen, S_IFDIR,
689 two, twolen, S_IFDIR);
691 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
692 * that 'foo' comes before 'foo/bar'.
694 if (cmp)
695 return cmp;
696 return onelen - twolen;
699 struct directory_versions {
701 * versions: list of (basename -> version_info)
703 * The basenames are in reverse lexicographic order of full pathnames,
704 * as processed in process_entries(). This puts all entries within
705 * a directory together, and covers the directory itself after
706 * everything within it, allowing us to write subtrees before needing
707 * to record information for the tree itself.
709 struct string_list versions;
712 * offsets: list of (full relative path directories -> integer offsets)
714 * Since versions contains basenames from files in multiple different
715 * directories, we need to know which entries in versions correspond
716 * to which directories. Values of e.g.
717 * "" 0
718 * src 2
719 * src/moduleA 5
720 * Would mean that entries 0-1 of versions are files in the toplevel
721 * directory, entries 2-4 are files under src/, and the remaining
722 * entries starting at index 5 are files under src/moduleA/.
724 struct string_list offsets;
727 * last_directory: directory that previously processed file found in
729 * last_directory starts NULL, but records the directory in which the
730 * previous file was found within. As soon as
731 * directory(current_file) != last_directory
732 * then we need to start updating accounting in versions & offsets.
733 * Note that last_directory is always the last path in "offsets" (or
734 * NULL if "offsets" is empty) so this exists just for quick access.
736 const char *last_directory;
738 /* last_directory_len: cached computation of strlen(last_directory) */
739 unsigned last_directory_len;
742 static int tree_entry_order(const void *a_, const void *b_)
744 const struct string_list_item *a = a_;
745 const struct string_list_item *b = b_;
747 const struct merged_info *ami = a->util;
748 const struct merged_info *bmi = b->util;
749 return base_name_compare(a->string, strlen(a->string), ami->result.mode,
750 b->string, strlen(b->string), bmi->result.mode);
753 static void write_tree(struct object_id *result_oid,
754 struct string_list *versions,
755 unsigned int offset,
756 size_t hash_size)
758 size_t maxlen = 0, extra;
759 unsigned int nr = versions->nr - offset;
760 struct strbuf buf = STRBUF_INIT;
761 struct string_list relevant_entries = STRING_LIST_INIT_NODUP;
762 int i;
765 * We want to sort the last (versions->nr-offset) entries in versions.
766 * Do so by abusing the string_list API a bit: make another string_list
767 * that contains just those entries and then sort them.
769 * We won't use relevant_entries again and will let it just pop off the
770 * stack, so there won't be allocation worries or anything.
772 relevant_entries.items = versions->items + offset;
773 relevant_entries.nr = versions->nr - offset;
774 QSORT(relevant_entries.items, relevant_entries.nr, tree_entry_order);
776 /* Pre-allocate some space in buf */
777 extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
778 for (i = 0; i < nr; i++) {
779 maxlen += strlen(versions->items[offset+i].string) + extra;
781 strbuf_grow(&buf, maxlen);
783 /* Write each entry out to buf */
784 for (i = 0; i < nr; i++) {
785 struct merged_info *mi = versions->items[offset+i].util;
786 struct version_info *ri = &mi->result;
787 strbuf_addf(&buf, "%o %s%c",
788 ri->mode,
789 versions->items[offset+i].string, '\0');
790 strbuf_add(&buf, ri->oid.hash, hash_size);
793 /* Write this object file out, and record in result_oid */
794 write_object_file(buf.buf, buf.len, tree_type, result_oid);
795 strbuf_release(&buf);
798 static void record_entry_for_tree(struct directory_versions *dir_metadata,
799 const char *path,
800 struct merged_info *mi)
802 const char *basename;
804 if (mi->is_null)
805 /* nothing to record */
806 return;
808 basename = path + mi->basename_offset;
809 assert(strchr(basename, '/') == NULL);
810 string_list_append(&dir_metadata->versions,
811 basename)->util = &mi->result;
814 static void write_completed_directory(struct merge_options *opt,
815 const char *new_directory_name,
816 struct directory_versions *info)
818 const char *prev_dir;
819 struct merged_info *dir_info = NULL;
820 unsigned int offset;
823 * Some explanation of info->versions and info->offsets...
825 * process_entries() iterates over all relevant files AND
826 * directories in reverse lexicographic order, and calls this
827 * function. Thus, an example of the paths that process_entries()
828 * could operate on (along with the directories for those paths
829 * being shown) is:
831 * xtract.c ""
832 * tokens.txt ""
833 * src/moduleB/umm.c src/moduleB
834 * src/moduleB/stuff.h src/moduleB
835 * src/moduleB/baz.c src/moduleB
836 * src/moduleB src
837 * src/moduleA/foo.c src/moduleA
838 * src/moduleA/bar.c src/moduleA
839 * src/moduleA src
840 * src ""
841 * Makefile ""
843 * info->versions:
845 * always contains the unprocessed entries and their
846 * version_info information. For example, after the first five
847 * entries above, info->versions would be:
849 * xtract.c <xtract.c's version_info>
850 * token.txt <token.txt's version_info>
851 * umm.c <src/moduleB/umm.c's version_info>
852 * stuff.h <src/moduleB/stuff.h's version_info>
853 * baz.c <src/moduleB/baz.c's version_info>
855 * Once a subdirectory is completed we remove the entries in
856 * that subdirectory from info->versions, writing it as a tree
857 * (write_tree()). Thus, as soon as we get to src/moduleB,
858 * info->versions would be updated to
860 * xtract.c <xtract.c's version_info>
861 * token.txt <token.txt's version_info>
862 * moduleB <src/moduleB's version_info>
864 * info->offsets:
866 * helps us track which entries in info->versions correspond to
867 * which directories. When we are N directories deep (e.g. 4
868 * for src/modA/submod/subdir/), we have up to N+1 unprocessed
869 * directories (+1 because of toplevel dir). Corresponding to
870 * the info->versions example above, after processing five entries
871 * info->offsets will be:
873 * "" 0
874 * src/moduleB 2
876 * which is used to know that xtract.c & token.txt are from the
877 * toplevel dirctory, while umm.c & stuff.h & baz.c are from the
878 * src/moduleB directory. Again, following the example above,
879 * once we need to process src/moduleB, then info->offsets is
880 * updated to
882 * "" 0
883 * src 2
885 * which says that moduleB (and only moduleB so far) is in the
886 * src directory.
888 * One unique thing to note about info->offsets here is that
889 * "src" was not added to info->offsets until there was a path
890 * (a file OR directory) immediately below src/ that got
891 * processed.
893 * Since process_entry() just appends new entries to info->versions,
894 * write_completed_directory() only needs to do work if the next path
895 * is in a directory that is different than the last directory found
896 * in info->offsets.
900 * If we are working with the same directory as the last entry, there
901 * is no work to do. (See comments above the directory_name member of
902 * struct merged_info for why we can use pointer comparison instead of
903 * strcmp here.)
905 if (new_directory_name == info->last_directory)
906 return;
909 * If we are just starting (last_directory is NULL), or last_directory
910 * is a prefix of the current directory, then we can just update
911 * info->offsets to record the offset where we started this directory
912 * and update last_directory to have quick access to it.
914 if (info->last_directory == NULL ||
915 !strncmp(new_directory_name, info->last_directory,
916 info->last_directory_len)) {
917 uintptr_t offset = info->versions.nr;
919 info->last_directory = new_directory_name;
920 info->last_directory_len = strlen(info->last_directory);
922 * Record the offset into info->versions where we will
923 * start recording basenames of paths found within
924 * new_directory_name.
926 string_list_append(&info->offsets,
927 info->last_directory)->util = (void*)offset;
928 return;
932 * The next entry that will be processed will be within
933 * new_directory_name. Since at this point we know that
934 * new_directory_name is within a different directory than
935 * info->last_directory, we have all entries for info->last_directory
936 * in info->versions and we need to create a tree object for them.
938 dir_info = strmap_get(&opt->priv->paths, info->last_directory);
939 assert(dir_info);
940 offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
941 if (offset == info->versions.nr) {
943 * Actually, we don't need to create a tree object in this
944 * case. Whenever all files within a directory disappear
945 * during the merge (e.g. unmodified on one side and
946 * deleted on the other, or files were renamed elsewhere),
947 * then we get here and the directory itself needs to be
948 * omitted from its parent tree as well.
950 dir_info->is_null = 1;
951 } else {
953 * Write out the tree to the git object directory, and also
954 * record the mode and oid in dir_info->result.
956 dir_info->is_null = 0;
957 dir_info->result.mode = S_IFDIR;
958 write_tree(&dir_info->result.oid, &info->versions, offset,
959 opt->repo->hash_algo->rawsz);
963 * We've now used several entries from info->versions and one entry
964 * from info->offsets, so we get rid of those values.
966 info->offsets.nr--;
967 info->versions.nr = offset;
970 * Now we've taken care of the completed directory, but we need to
971 * prepare things since future entries will be in
972 * new_directory_name. (In particular, process_entry() will be
973 * appending new entries to info->versions.) So, we need to make
974 * sure new_directory_name is the last entry in info->offsets.
976 prev_dir = info->offsets.nr == 0 ? NULL :
977 info->offsets.items[info->offsets.nr-1].string;
978 if (new_directory_name != prev_dir) {
979 uintptr_t c = info->versions.nr;
980 string_list_append(&info->offsets,
981 new_directory_name)->util = (void*)c;
984 /* And, of course, we need to update last_directory to match. */
985 info->last_directory = new_directory_name;
986 info->last_directory_len = strlen(info->last_directory);
989 /* Per entry merge function */
990 static void process_entry(struct merge_options *opt,
991 const char *path,
992 struct conflict_info *ci,
993 struct directory_versions *dir_metadata)
995 int df_file_index = 0;
997 VERIFY_CI(ci);
998 assert(ci->filemask >= 0 && ci->filemask <= 7);
999 /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
1000 assert(ci->match_mask == 0 || ci->match_mask == 3 ||
1001 ci->match_mask == 5 || ci->match_mask == 6);
1003 if (ci->dirmask) {
1004 record_entry_for_tree(dir_metadata, path, &ci->merged);
1005 if (ci->filemask == 0)
1006 /* nothing else to handle */
1007 return;
1008 assert(ci->df_conflict);
1011 if (ci->df_conflict && ci->merged.result.mode == 0) {
1012 int i;
1015 * directory no longer in the way, but we do have a file we
1016 * need to place here so we need to clean away the "directory
1017 * merges to nothing" result.
1019 ci->df_conflict = 0;
1020 assert(ci->filemask != 0);
1021 ci->merged.clean = 0;
1022 ci->merged.is_null = 0;
1023 /* and we want to zero out any directory-related entries */
1024 ci->match_mask = (ci->match_mask & ~ci->dirmask);
1025 ci->dirmask = 0;
1026 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1027 if (ci->filemask & (1 << i))
1028 continue;
1029 ci->stages[i].mode = 0;
1030 oidcpy(&ci->stages[i].oid, &null_oid);
1032 } else if (ci->df_conflict && ci->merged.result.mode != 0) {
1034 * This started out as a D/F conflict, and the entries in
1035 * the competing directory were not removed by the merge as
1036 * evidenced by write_completed_directory() writing a value
1037 * to ci->merged.result.mode.
1039 struct conflict_info *new_ci;
1040 const char *branch;
1041 const char *old_path = path;
1042 int i;
1044 assert(ci->merged.result.mode == S_IFDIR);
1047 * If filemask is 1, we can just ignore the file as having
1048 * been deleted on both sides. We do not want to overwrite
1049 * ci->merged.result, since it stores the tree for all the
1050 * files under it.
1052 if (ci->filemask == 1) {
1053 ci->filemask = 0;
1054 return;
1058 * This file still exists on at least one side, and we want
1059 * the directory to remain here, so we need to move this
1060 * path to some new location.
1062 new_ci = xcalloc(1, sizeof(*new_ci));
1063 /* We don't really want new_ci->merged.result copied, but it'll
1064 * be overwritten below so it doesn't matter. We also don't
1065 * want any directory mode/oid values copied, but we'll zero
1066 * those out immediately. We do want the rest of ci copied.
1068 memcpy(new_ci, ci, sizeof(*ci));
1069 new_ci->match_mask = (new_ci->match_mask & ~new_ci->dirmask);
1070 new_ci->dirmask = 0;
1071 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1072 if (new_ci->filemask & (1 << i))
1073 continue;
1074 /* zero out any entries related to directories */
1075 new_ci->stages[i].mode = 0;
1076 oidcpy(&new_ci->stages[i].oid, &null_oid);
1080 * Find out which side this file came from; note that we
1081 * cannot just use ci->filemask, because renames could cause
1082 * the filemask to go back to 7. So we use dirmask, then
1083 * pick the opposite side's index.
1085 df_file_index = (ci->dirmask & (1 << 1)) ? 2 : 1;
1086 branch = (df_file_index == 1) ? opt->branch1 : opt->branch2;
1087 path = unique_path(&opt->priv->paths, path, branch);
1088 strmap_put(&opt->priv->paths, path, new_ci);
1090 path_msg(opt, path, 0,
1091 _("CONFLICT (file/directory): directory in the way "
1092 "of %s from %s; moving it to %s instead."),
1093 old_path, branch, path);
1096 * Zero out the filemask for the old ci. At this point, ci
1097 * was just an entry for a directory, so we don't need to
1098 * do anything more with it.
1100 ci->filemask = 0;
1103 * Now note that we're working on the new entry (path was
1104 * updated above.
1106 ci = new_ci;
1110 * NOTE: Below there is a long switch-like if-elseif-elseif... block
1111 * which the code goes through even for the df_conflict cases
1112 * above.
1114 if (ci->match_mask) {
1115 ci->merged.clean = 1;
1116 if (ci->match_mask == 6) {
1117 /* stages[1] == stages[2] */
1118 ci->merged.result.mode = ci->stages[1].mode;
1119 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
1120 } else {
1121 /* determine the mask of the side that didn't match */
1122 unsigned int othermask = 7 & ~ci->match_mask;
1123 int side = (othermask == 4) ? 2 : 1;
1125 ci->merged.result.mode = ci->stages[side].mode;
1126 ci->merged.is_null = !ci->merged.result.mode;
1127 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1129 assert(othermask == 2 || othermask == 4);
1130 assert(ci->merged.is_null ==
1131 (ci->filemask == ci->match_mask));
1133 } else if (ci->filemask >= 6 &&
1134 (S_IFMT & ci->stages[1].mode) !=
1135 (S_IFMT & ci->stages[2].mode)) {
1137 * Two different items from (file/submodule/symlink)
1139 die("Not yet implemented.");
1140 } else if (ci->filemask >= 6) {
1142 * TODO: Needs a two-way or three-way content merge, but we're
1143 * just being lazy and copying the version from HEAD and
1144 * leaving it as conflicted.
1146 ci->merged.clean = 0;
1147 ci->merged.result.mode = ci->stages[1].mode;
1148 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
1149 /* When we fix above, we'll call handle_content_merge() */
1150 (void)handle_content_merge;
1151 } else if (ci->filemask == 3 || ci->filemask == 5) {
1152 /* Modify/delete */
1153 const char *modify_branch, *delete_branch;
1154 int side = (ci->filemask == 5) ? 2 : 1;
1155 int index = opt->priv->call_depth ? 0 : side;
1157 ci->merged.result.mode = ci->stages[index].mode;
1158 oidcpy(&ci->merged.result.oid, &ci->stages[index].oid);
1159 ci->merged.clean = 0;
1161 modify_branch = (side == 1) ? opt->branch1 : opt->branch2;
1162 delete_branch = (side == 1) ? opt->branch2 : opt->branch1;
1164 path_msg(opt, path, 0,
1165 _("CONFLICT (modify/delete): %s deleted in %s "
1166 "and modified in %s. Version %s of %s left "
1167 "in tree."),
1168 path, delete_branch, modify_branch,
1169 modify_branch, path);
1170 } else if (ci->filemask == 2 || ci->filemask == 4) {
1171 /* Added on one side */
1172 int side = (ci->filemask == 4) ? 2 : 1;
1173 ci->merged.result.mode = ci->stages[side].mode;
1174 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1175 ci->merged.clean = !ci->df_conflict;
1176 } else if (ci->filemask == 1) {
1177 /* Deleted on both sides */
1178 ci->merged.is_null = 1;
1179 ci->merged.result.mode = 0;
1180 oidcpy(&ci->merged.result.oid, &null_oid);
1181 ci->merged.clean = 1;
1185 * If still conflicted, record it separately. This allows us to later
1186 * iterate over just conflicted entries when updating the index instead
1187 * of iterating over all entries.
1189 if (!ci->merged.clean)
1190 strmap_put(&opt->priv->conflicted, path, ci);
1191 record_entry_for_tree(dir_metadata, path, &ci->merged);
1194 static void process_entries(struct merge_options *opt,
1195 struct object_id *result_oid)
1197 struct hashmap_iter iter;
1198 struct strmap_entry *e;
1199 struct string_list plist = STRING_LIST_INIT_NODUP;
1200 struct string_list_item *entry;
1201 struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
1202 STRING_LIST_INIT_NODUP,
1203 NULL, 0 };
1205 if (strmap_empty(&opt->priv->paths)) {
1206 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
1207 return;
1210 /* Hack to pre-allocate plist to the desired size */
1211 ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
1213 /* Put every entry from paths into plist, then sort */
1214 strmap_for_each_entry(&opt->priv->paths, &iter, e) {
1215 string_list_append(&plist, e->key)->util = e->value;
1217 plist.cmp = string_list_df_name_compare;
1218 string_list_sort(&plist);
1221 * Iterate over the items in reverse order, so we can handle paths
1222 * below a directory before needing to handle the directory itself.
1224 * This allows us to write subtrees before we need to write trees,
1225 * and it also enables sane handling of directory/file conflicts
1226 * (because it allows us to know whether the directory is still in
1227 * the way when it is time to process the file at the same path).
1229 for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
1230 char *path = entry->string;
1232 * NOTE: mi may actually be a pointer to a conflict_info, but
1233 * we have to check mi->clean first to see if it's safe to
1234 * reassign to such a pointer type.
1236 struct merged_info *mi = entry->util;
1238 write_completed_directory(opt, mi->directory_name,
1239 &dir_metadata);
1240 if (mi->clean)
1241 record_entry_for_tree(&dir_metadata, path, mi);
1242 else {
1243 struct conflict_info *ci = (struct conflict_info *)mi;
1244 process_entry(opt, path, ci, &dir_metadata);
1248 if (dir_metadata.offsets.nr != 1 ||
1249 (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
1250 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
1251 dir_metadata.offsets.nr);
1252 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
1253 (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
1254 fflush(stdout);
1255 BUG("dir_metadata accounting completely off; shouldn't happen");
1257 write_tree(result_oid, &dir_metadata.versions, 0,
1258 opt->repo->hash_algo->rawsz);
1259 string_list_clear(&plist, 0);
1260 string_list_clear(&dir_metadata.versions, 0);
1261 string_list_clear(&dir_metadata.offsets, 0);
1264 /*** Function Grouping: functions related to merge_switch_to_result() ***/
1266 static int checkout(struct merge_options *opt,
1267 struct tree *prev,
1268 struct tree *next)
1270 /* Switch the index/working copy from old to new */
1271 int ret;
1272 struct tree_desc trees[2];
1273 struct unpack_trees_options unpack_opts;
1275 memset(&unpack_opts, 0, sizeof(unpack_opts));
1276 unpack_opts.head_idx = -1;
1277 unpack_opts.src_index = opt->repo->index;
1278 unpack_opts.dst_index = opt->repo->index;
1280 setup_unpack_trees_porcelain(&unpack_opts, "merge");
1283 * NOTE: if this were just "git checkout" code, we would probably
1284 * read or refresh the cache and check for a conflicted index, but
1285 * builtin/merge.c or sequencer.c really needs to read the index
1286 * and check for conflicted entries before starting merging for a
1287 * good user experience (no sense waiting for merges/rebases before
1288 * erroring out), so there's no reason to duplicate that work here.
1291 /* 2-way merge to the new branch */
1292 unpack_opts.update = 1;
1293 unpack_opts.merge = 1;
1294 unpack_opts.quiet = 0; /* FIXME: sequencer might want quiet? */
1295 unpack_opts.verbose_update = (opt->verbosity > 2);
1296 unpack_opts.fn = twoway_merge;
1297 if (1/* FIXME: opts->overwrite_ignore*/) {
1298 unpack_opts.dir = xcalloc(1, sizeof(*unpack_opts.dir));
1299 unpack_opts.dir->flags |= DIR_SHOW_IGNORED;
1300 setup_standard_excludes(unpack_opts.dir);
1302 parse_tree(prev);
1303 init_tree_desc(&trees[0], prev->buffer, prev->size);
1304 parse_tree(next);
1305 init_tree_desc(&trees[1], next->buffer, next->size);
1307 ret = unpack_trees(2, trees, &unpack_opts);
1308 clear_unpack_trees_porcelain(&unpack_opts);
1309 dir_clear(unpack_opts.dir);
1310 FREE_AND_NULL(unpack_opts.dir);
1311 return ret;
1314 static int record_conflicted_index_entries(struct merge_options *opt,
1315 struct index_state *index,
1316 struct strmap *paths,
1317 struct strmap *conflicted)
1319 struct hashmap_iter iter;
1320 struct strmap_entry *e;
1321 int errs = 0;
1322 int original_cache_nr;
1324 if (strmap_empty(conflicted))
1325 return 0;
1327 original_cache_nr = index->cache_nr;
1329 /* Put every entry from paths into plist, then sort */
1330 strmap_for_each_entry(conflicted, &iter, e) {
1331 const char *path = e->key;
1332 struct conflict_info *ci = e->value;
1333 int pos;
1334 struct cache_entry *ce;
1335 int i;
1337 VERIFY_CI(ci);
1340 * The index will already have a stage=0 entry for this path,
1341 * because we created an as-merged-as-possible version of the
1342 * file and checkout() moved the working copy and index over
1343 * to that version.
1345 * However, previous iterations through this loop will have
1346 * added unstaged entries to the end of the cache which
1347 * ignore the standard alphabetical ordering of cache
1348 * entries and break invariants needed for index_name_pos()
1349 * to work. However, we know the entry we want is before
1350 * those appended cache entries, so do a temporary swap on
1351 * cache_nr to only look through entries of interest.
1353 SWAP(index->cache_nr, original_cache_nr);
1354 pos = index_name_pos(index, path, strlen(path));
1355 SWAP(index->cache_nr, original_cache_nr);
1356 if (pos < 0) {
1357 if (ci->filemask != 1)
1358 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path);
1359 cache_tree_invalidate_path(index, path);
1360 } else {
1361 ce = index->cache[pos];
1364 * Clean paths with CE_SKIP_WORKTREE set will not be
1365 * written to the working tree by the unpack_trees()
1366 * call in checkout(). Our conflicted entries would
1367 * have appeared clean to that code since we ignored
1368 * the higher order stages. Thus, we need override
1369 * the CE_SKIP_WORKTREE bit and manually write those
1370 * files to the working disk here.
1372 * TODO: Implement this CE_SKIP_WORKTREE fixup.
1376 * Mark this cache entry for removal and instead add
1377 * new stage>0 entries corresponding to the
1378 * conflicts. If there are many conflicted entries, we
1379 * want to avoid memmove'ing O(NM) entries by
1380 * inserting the new entries one at a time. So,
1381 * instead, we just add the new cache entries to the
1382 * end (ignoring normal index requirements on sort
1383 * order) and sort the index once we're all done.
1385 ce->ce_flags |= CE_REMOVE;
1388 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1389 struct version_info *vi;
1390 if (!(ci->filemask & (1ul << i)))
1391 continue;
1392 vi = &ci->stages[i];
1393 ce = make_cache_entry(index, vi->mode, &vi->oid,
1394 path, i+1, 0);
1395 add_index_entry(index, ce, ADD_CACHE_JUST_APPEND);
1400 * Remove the unused cache entries (and invalidate the relevant
1401 * cache-trees), then sort the index entries to get the conflicted
1402 * entries we added to the end into their right locations.
1404 remove_marked_cache_entries(index, 1);
1405 QSORT(index->cache, index->cache_nr, cmp_cache_name_compare);
1407 return errs;
1410 void merge_switch_to_result(struct merge_options *opt,
1411 struct tree *head,
1412 struct merge_result *result,
1413 int update_worktree_and_index,
1414 int display_update_msgs)
1416 assert(opt->priv == NULL);
1417 if (result->clean >= 0 && update_worktree_and_index) {
1418 struct merge_options_internal *opti = result->priv;
1420 if (checkout(opt, head, result->tree)) {
1421 /* failure to function */
1422 result->clean = -1;
1423 return;
1426 if (record_conflicted_index_entries(opt, opt->repo->index,
1427 &opti->paths,
1428 &opti->conflicted)) {
1429 /* failure to function */
1430 result->clean = -1;
1431 return;
1435 if (display_update_msgs) {
1436 struct merge_options_internal *opti = result->priv;
1437 struct hashmap_iter iter;
1438 struct strmap_entry *e;
1439 struct string_list olist = STRING_LIST_INIT_NODUP;
1440 int i;
1442 /* Hack to pre-allocate olist to the desired size */
1443 ALLOC_GROW(olist.items, strmap_get_size(&opti->output),
1444 olist.alloc);
1446 /* Put every entry from output into olist, then sort */
1447 strmap_for_each_entry(&opti->output, &iter, e) {
1448 string_list_append(&olist, e->key)->util = e->value;
1450 string_list_sort(&olist);
1452 /* Iterate over the items, printing them */
1453 for (i = 0; i < olist.nr; ++i) {
1454 struct strbuf *sb = olist.items[i].util;
1456 printf("%s", sb->buf);
1458 string_list_clear(&olist, 0);
1461 merge_finalize(opt, result);
1464 void merge_finalize(struct merge_options *opt,
1465 struct merge_result *result)
1467 struct merge_options_internal *opti = result->priv;
1469 assert(opt->priv == NULL);
1471 clear_internal_opts(opti, 0);
1472 FREE_AND_NULL(opti);
1475 /*** Function Grouping: helper functions for merge_incore_*() ***/
1477 static void merge_start(struct merge_options *opt, struct merge_result *result)
1479 /* Sanity checks on opt */
1480 assert(opt->repo);
1482 assert(opt->branch1 && opt->branch2);
1484 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
1485 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
1486 assert(opt->rename_limit >= -1);
1487 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
1488 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
1490 assert(opt->xdl_opts >= 0);
1491 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
1492 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
1495 * detect_renames, verbosity, buffer_output, and obuf are ignored
1496 * fields that were used by "recursive" rather than "ort" -- but
1497 * sanity check them anyway.
1499 assert(opt->detect_renames >= -1 &&
1500 opt->detect_renames <= DIFF_DETECT_COPY);
1501 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
1502 assert(opt->buffer_output <= 2);
1503 assert(opt->obuf.len == 0);
1505 assert(opt->priv == NULL);
1507 /* Default to histogram diff. Actually, just hardcode it...for now. */
1508 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
1510 /* Initialization of opt->priv, our internal merge data */
1511 opt->priv = xcalloc(1, sizeof(*opt->priv));
1514 * Although we initialize opt->priv->paths with strdup_strings=0,
1515 * that's just to avoid making yet another copy of an allocated
1516 * string. Putting the entry into paths means we are taking
1517 * ownership, so we will later free it. paths_to_free is similar.
1519 * In contrast, conflicted just has a subset of keys from paths, so
1520 * we don't want to free those (it'd be a duplicate free).
1522 strmap_init_with_options(&opt->priv->paths, NULL, 0);
1523 strmap_init_with_options(&opt->priv->conflicted, NULL, 0);
1524 string_list_init(&opt->priv->paths_to_free, 0);
1527 * keys & strbufs in output will sometimes need to outlive "paths",
1528 * so it will have a copy of relevant keys. It's probably a small
1529 * subset of the overall paths that have special output.
1531 strmap_init(&opt->priv->output);
1534 /*** Function Grouping: merge_incore_*() and their internal variants ***/
1537 * Originally from merge_trees_internal(); heavily adapted, though.
1539 static void merge_ort_nonrecursive_internal(struct merge_options *opt,
1540 struct tree *merge_base,
1541 struct tree *side1,
1542 struct tree *side2,
1543 struct merge_result *result)
1545 struct object_id working_tree_oid;
1547 if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
1549 * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
1550 * base, and 2-3) the trees for the two trees we're merging.
1552 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
1553 oid_to_hex(&merge_base->object.oid),
1554 oid_to_hex(&side1->object.oid),
1555 oid_to_hex(&side2->object.oid));
1556 result->clean = -1;
1557 return;
1560 result->clean = detect_and_process_renames(opt, merge_base,
1561 side1, side2);
1562 process_entries(opt, &working_tree_oid);
1564 /* Set return values */
1565 result->tree = parse_tree_indirect(&working_tree_oid);
1566 /* existence of conflicted entries implies unclean */
1567 result->clean &= strmap_empty(&opt->priv->conflicted);
1568 if (!opt->priv->call_depth) {
1569 result->priv = opt->priv;
1570 opt->priv = NULL;
1574 void merge_incore_nonrecursive(struct merge_options *opt,
1575 struct tree *merge_base,
1576 struct tree *side1,
1577 struct tree *side2,
1578 struct merge_result *result)
1580 assert(opt->ancestor != NULL);
1581 merge_start(opt, result);
1582 merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
1585 void merge_incore_recursive(struct merge_options *opt,
1586 struct commit_list *merge_bases,
1587 struct commit *side1,
1588 struct commit *side2,
1589 struct merge_result *result)
1591 die("Not yet implemented");