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 "cache-tree.h"
24 #include "commit-reach.h"
29 #include "object-store.h"
32 #include "submodule.h"
34 #include "unpack-trees.h"
35 #include "xdiff-interface.h"
38 * We have many arrays of size 3. Whenever we have such an array, the
39 * indices refer to one of the sides of the three-way merge. This is so
40 * pervasive that the constants 0, 1, and 2 are used in many places in the
41 * code (especially in arithmetic operations to find the other side's index
42 * or to compute a relevant mask), but sometimes these enum names are used
43 * to aid code clarity.
45 * See also 'filemask' and 'dirmask' in struct conflict_info; the "ith side"
46 * referred to there is one of these three sides.
56 * All variables that are arrays of size 3 correspond to data tracked
57 * for the sides in enum merge_side. Index 0 is almost always unused
58 * because we often only need to track information for MERGE_SIDE1 and
59 * MERGE_SIDE2 (MERGE_BASE can't have rename information since renames
60 * are determined relative to what changed since the MERGE_BASE).
64 * pairs: pairing of filenames from diffcore_rename()
66 struct diff_queue_struct pairs
[3];
69 * dirs_removed: directories removed on a given side of history.
71 struct strset dirs_removed
[3];
74 * dir_rename_count: tracking where parts of a directory were renamed to
76 * When files in a directory are renamed, they may not all go to the
77 * same location. Each strmap here tracks:
78 * old_dir => {new_dir => int}
79 * That is, dir_rename_count[side] is a strmap to a strintmap.
81 struct strmap dir_rename_count
[3];
84 * dir_renames: computed directory renames
86 * This is a map of old_dir => new_dir and is derived in part from
89 struct strmap dir_renames
[3];
92 * needed_limit: value needed for inexact rename detection to run
94 * If the current rename limit wasn't high enough for inexact
95 * rename detection to run, this records the limit needed. Otherwise,
96 * this value remains 0.
101 struct merge_options_internal
{
103 * paths: primary data structure in all of merge ort.
106 * * are full relative paths from the toplevel of the repository
107 * (e.g. "drivers/firmware/raspberrypi.c").
108 * * store all relevant paths in the repo, both directories and
109 * files (e.g. drivers, drivers/firmware would also be included)
110 * * these keys serve to intern all the path strings, which allows
111 * us to do pointer comparison on directory names instead of
112 * strcmp; we just have to be careful to use the interned strings.
113 * (Technically paths_to_free may track some strings that were
114 * removed from froms paths.)
116 * The values of paths:
117 * * either a pointer to a merged_info, or a conflict_info struct
118 * * merged_info contains all relevant information for a
119 * non-conflicted entry.
120 * * conflict_info contains a merged_info, plus any additional
121 * information about a conflict such as the higher orders stages
122 * involved and the names of the paths those came from (handy
123 * once renames get involved).
124 * * a path may start "conflicted" (i.e. point to a conflict_info)
125 * and then a later step (e.g. three-way content merge) determines
126 * it can be cleanly merged, at which point it'll be marked clean
127 * and the algorithm will ignore any data outside the contained
128 * merged_info for that entry
129 * * If an entry remains conflicted, the merged_info portion of a
130 * conflict_info will later be filled with whatever version of
131 * the file should be placed in the working directory (e.g. an
132 * as-merged-as-possible variation that contains conflict markers).
137 * conflicted: a subset of keys->values from "paths"
139 * conflicted is basically an optimization between process_entries()
140 * and record_conflicted_index_entries(); the latter could loop over
141 * ALL the entries in paths AGAIN and look for the ones that are
142 * still conflicted, but since process_entries() has to loop over
143 * all of them, it saves the ones it couldn't resolve in this strmap
144 * so that record_conflicted_index_entries() can iterate just the
147 struct strmap conflicted
;
150 * paths_to_free: additional list of strings to free
152 * If keys are removed from "paths", they are added to paths_to_free
153 * to ensure they are later freed. We avoid free'ing immediately since
154 * other places (e.g. conflict_info.pathnames[]) may still be
155 * referencing these paths.
157 struct string_list paths_to_free
;
160 * output: special messages and conflict notices for various paths
162 * This is a map of pathnames (a subset of the keys in "paths" above)
163 * to strbufs. It gathers various warning/conflict/notice messages
164 * for later processing.
166 struct strmap output
;
169 * renames: various data relating to rename detection
171 struct rename_info renames
;
174 * current_dir_name, toplevel_dir: temporary vars
176 * These are used in collect_merge_info_callback(), and will set the
177 * various merged_info.directory_name for the various paths we get;
178 * see documentation for that variable and the requirements placed on
181 const char *current_dir_name
;
182 const char *toplevel_dir
;
184 /* call_depth: recursion level counter for merging merge bases */
188 struct version_info
{
189 struct object_id oid
;
194 /* if is_null, ignore result. otherwise result has oid & mode */
195 struct version_info result
;
199 * clean: whether the path in question is cleanly merged.
201 * see conflict_info.merged for more details.
206 * basename_offset: offset of basename of path.
208 * perf optimization to avoid recomputing offset of final '/'
209 * character in pathname (0 if no '/' in pathname).
211 size_t basename_offset
;
214 * directory_name: containing directory name.
216 * Note that we assume directory_name is constructed such that
217 * strcmp(dir1_name, dir2_name) == 0 iff dir1_name == dir2_name,
218 * i.e. string equality is equivalent to pointer equality. For this
219 * to hold, we have to be careful setting directory_name.
221 const char *directory_name
;
224 struct conflict_info
{
226 * merged: the version of the path that will be written to working tree
228 * WARNING: It is critical to check merged.clean and ensure it is 0
229 * before reading any conflict_info fields outside of merged.
230 * Allocated merge_info structs will always have clean set to 1.
231 * Allocated conflict_info structs will have merged.clean set to 0
232 * initially. The merged.clean field is how we know if it is safe
233 * to access other parts of conflict_info besides merged; if a
234 * conflict_info's merged.clean is changed to 1, the rest of the
235 * algorithm is not allowed to look at anything outside of the
236 * merged member anymore.
238 struct merged_info merged
;
240 /* oids & modes from each of the three trees for this path */
241 struct version_info stages
[3];
243 /* pathnames for each stage; may differ due to rename detection */
244 const char *pathnames
[3];
246 /* Whether this path is/was involved in a directory/file conflict */
247 unsigned df_conflict
:1;
250 * Whether this path is/was involved in a non-content conflict other
251 * than a directory/file conflict (e.g. rename/rename, rename/delete,
252 * file location based on possible directory rename).
254 unsigned path_conflict
:1;
257 * For filemask and dirmask, the ith bit corresponds to whether the
258 * ith entry is a file (filemask) or a directory (dirmask). Thus,
259 * filemask & dirmask is always zero, and filemask | dirmask is at
260 * most 7 but can be less when a path does not appear as either a
261 * file or a directory on at least one side of history.
263 * Note that these masks are related to enum merge_side, as the ith
264 * entry corresponds to side i.
266 * These values come from a traverse_trees() call; more info may be
267 * found looking at tree-walk.h's struct traverse_info,
268 * particularly the documentation above the "fn" member (note that
269 * filemask = mask & ~dirmask from that documentation).
275 * Optimization to track which stages match, to avoid the need to
276 * recompute it in multiple steps. Either 0 or at least 2 bits are
277 * set; if at least 2 bits are set, their corresponding stages match.
279 unsigned match_mask
:3;
282 /*** Function Grouping: various utility functions ***/
285 * For the next three macros, see warning for conflict_info.merged.
287 * In each of the below, mi is a struct merged_info*, and ci was defined
288 * as a struct conflict_info* (but we need to verify ci isn't actually
289 * pointed at a struct merged_info*).
291 * INITIALIZE_CI: Assign ci to mi but only if it's safe; set to NULL otherwise.
292 * VERIFY_CI: Ensure that something we assigned to a conflict_info* is one.
293 * ASSIGN_AND_VERIFY_CI: Similar to VERIFY_CI but do assignment first.
295 #define INITIALIZE_CI(ci, mi) do { \
296 (ci) = (!(mi) || (mi)->clean) ? NULL : (struct conflict_info *)(mi); \
298 #define VERIFY_CI(ci) assert(ci && !ci->merged.clean);
299 #define ASSIGN_AND_VERIFY_CI(ci, mi) do { \
300 (ci) = (struct conflict_info *)(mi); \
301 assert((ci) && !(mi)->clean); \
304 static void free_strmap_strings(struct strmap
*map
)
306 struct hashmap_iter iter
;
307 struct strmap_entry
*entry
;
309 strmap_for_each_entry(map
, &iter
, entry
) {
310 free((char*)entry
->key
);
314 static void clear_or_reinit_internal_opts(struct merge_options_internal
*opti
,
317 struct rename_info
*renames
= &opti
->renames
;
319 void (*strmap_func
)(struct strmap
*, int) =
320 reinitialize
? strmap_partial_clear
: strmap_clear
;
321 void (*strset_func
)(struct strset
*) =
322 reinitialize
? strset_partial_clear
: strset_clear
;
325 * We marked opti->paths with strdup_strings = 0, so that we
326 * wouldn't have to make another copy of the fullpath created by
327 * make_traverse_path from setup_path_info(). But, now that we've
328 * used it and have no other references to these strings, it is time
329 * to deallocate them.
331 free_strmap_strings(&opti
->paths
);
332 strmap_func(&opti
->paths
, 1);
335 * All keys and values in opti->conflicted are a subset of those in
336 * opti->paths. We don't want to deallocate anything twice, so we
337 * don't free the keys and we pass 0 for free_values.
339 strmap_func(&opti
->conflicted
, 0);
342 * opti->paths_to_free is similar to opti->paths; we created it with
343 * strdup_strings = 0 to avoid making _another_ copy of the fullpath
344 * but now that we've used it and have no other references to these
345 * strings, it is time to deallocate them. We do so by temporarily
346 * setting strdup_strings to 1.
348 opti
->paths_to_free
.strdup_strings
= 1;
349 string_list_clear(&opti
->paths_to_free
, 0);
350 opti
->paths_to_free
.strdup_strings
= 0;
352 /* Free memory used by various renames maps */
353 for (i
= MERGE_SIDE1
; i
<= MERGE_SIDE2
; ++i
) {
354 struct hashmap_iter iter
;
355 struct strmap_entry
*entry
;
357 strset_func(&renames
->dirs_removed
[i
]);
359 strmap_for_each_entry(&renames
->dir_rename_count
[i
],
361 struct strintmap
*counts
= entry
->value
;
362 strintmap_clear(counts
);
364 strmap_func(&renames
->dir_rename_count
[i
], 1);
366 strmap_func(&renames
->dir_renames
[i
], 0);
370 struct hashmap_iter iter
;
371 struct strmap_entry
*e
;
373 /* Release and free each strbuf found in output */
374 strmap_for_each_entry(&opti
->output
, &iter
, e
) {
375 struct strbuf
*sb
= e
->value
;
378 * While strictly speaking we don't need to free(sb)
379 * here because we could pass free_values=1 when
380 * calling strmap_clear() on opti->output, that would
381 * require strmap_clear to do another
382 * strmap_for_each_entry() loop, so we just free it
383 * while we're iterating anyway.
387 strmap_clear(&opti
->output
, 0);
391 static int err(struct merge_options
*opt
, const char *err
, ...)
394 struct strbuf sb
= STRBUF_INIT
;
396 strbuf_addstr(&sb
, "error: ");
397 va_start(params
, err
);
398 strbuf_vaddf(&sb
, err
, params
);
407 static void format_commit(struct strbuf
*sb
,
409 struct commit
*commit
)
411 struct merge_remote_desc
*desc
;
412 struct pretty_print_context ctx
= {0};
413 ctx
.abbrev
= DEFAULT_ABBREV
;
415 strbuf_addchars(sb
, ' ', indent
);
416 desc
= merge_remote_util(commit
);
418 strbuf_addf(sb
, "virtual %s\n", desc
->name
);
422 format_commit_message(commit
, "%h %s", sb
, &ctx
);
423 strbuf_addch(sb
, '\n');
426 __attribute__((format (printf
, 4, 5)))
427 static void path_msg(struct merge_options
*opt
,
429 int omittable_hint
, /* skippable under --remerge-diff */
430 const char *fmt
, ...)
433 struct strbuf
*sb
= strmap_get(&opt
->priv
->output
, path
);
435 sb
= xmalloc(sizeof(*sb
));
437 strmap_put(&opt
->priv
->output
, path
, sb
);
441 strbuf_vaddf(sb
, fmt
, ap
);
444 strbuf_addch(sb
, '\n');
447 /* add a string to a strbuf, but converting "/" to "_" */
448 static void add_flattened_path(struct strbuf
*out
, const char *s
)
451 strbuf_addstr(out
, s
);
452 for (; i
< out
->len
; i
++)
453 if (out
->buf
[i
] == '/')
457 static char *unique_path(struct strmap
*existing_paths
,
461 struct strbuf newpath
= STRBUF_INIT
;
465 strbuf_addf(&newpath
, "%s~", path
);
466 add_flattened_path(&newpath
, branch
);
468 base_len
= newpath
.len
;
469 while (strmap_contains(existing_paths
, newpath
.buf
)) {
470 strbuf_setlen(&newpath
, base_len
);
471 strbuf_addf(&newpath
, "_%d", suffix
++);
474 return strbuf_detach(&newpath
, NULL
);
477 /*** Function Grouping: functions related to collect_merge_info() ***/
479 static void setup_path_info(struct merge_options
*opt
,
480 struct string_list_item
*result
,
481 const char *current_dir_name
,
482 int current_dir_name_len
,
483 char *fullpath
, /* we'll take over ownership */
484 struct name_entry
*names
,
485 struct name_entry
*merged_version
,
486 unsigned is_null
, /* boolean */
487 unsigned df_conflict
, /* boolean */
490 int resolved
/* boolean */)
492 /* result->util is void*, so mi is a convenience typed variable */
493 struct merged_info
*mi
;
495 assert(!is_null
|| resolved
);
496 assert(!df_conflict
|| !resolved
); /* df_conflict implies !resolved */
497 assert(resolved
== (merged_version
!= NULL
));
499 mi
= xcalloc(1, resolved
? sizeof(struct merged_info
) :
500 sizeof(struct conflict_info
));
501 mi
->directory_name
= current_dir_name
;
502 mi
->basename_offset
= current_dir_name_len
;
503 mi
->clean
= !!resolved
;
505 mi
->result
.mode
= merged_version
->mode
;
506 oidcpy(&mi
->result
.oid
, &merged_version
->oid
);
507 mi
->is_null
= !!is_null
;
510 struct conflict_info
*ci
;
512 ASSIGN_AND_VERIFY_CI(ci
, mi
);
513 for (i
= MERGE_BASE
; i
<= MERGE_SIDE2
; i
++) {
514 ci
->pathnames
[i
] = fullpath
;
515 ci
->stages
[i
].mode
= names
[i
].mode
;
516 oidcpy(&ci
->stages
[i
].oid
, &names
[i
].oid
);
518 ci
->filemask
= filemask
;
519 ci
->dirmask
= dirmask
;
520 ci
->df_conflict
= !!df_conflict
;
523 * Assume is_null for now, but if we have entries
524 * under the directory then when it is complete in
525 * write_completed_directory() it'll update this.
526 * Also, for D/F conflicts, we have to handle the
527 * directory first, then clear this bit and process
528 * the file to see how it is handled -- that occurs
529 * near the top of process_entry().
533 strmap_put(&opt
->priv
->paths
, fullpath
, mi
);
534 result
->string
= fullpath
;
538 static void collect_rename_info(struct merge_options
*opt
,
539 struct name_entry
*names
,
541 const char *fullname
,
546 struct rename_info
*renames
= &opt
->priv
->renames
;
548 /* Update dirs_removed, as needed */
549 if (dirmask
== 1 || dirmask
== 3 || dirmask
== 5) {
550 /* absent_mask = 0x07 - dirmask; sides = absent_mask/2 */
551 unsigned sides
= (0x07 - dirmask
)/2;
553 strset_add(&renames
->dirs_removed
[1], fullname
);
555 strset_add(&renames
->dirs_removed
[2], fullname
);
559 static int collect_merge_info_callback(int n
,
561 unsigned long dirmask
,
562 struct name_entry
*names
,
563 struct traverse_info
*info
)
567 * common ancestor (mbase) has mask 1, and stored in index 0 of names
568 * head of side 1 (side1) has mask 2, and stored in index 1 of names
569 * head of side 2 (side2) has mask 4, and stored in index 2 of names
571 struct merge_options
*opt
= info
->data
;
572 struct merge_options_internal
*opti
= opt
->priv
;
573 struct string_list_item pi
; /* Path Info */
574 struct conflict_info
*ci
; /* typed alias to pi.util (which is void*) */
575 struct name_entry
*p
;
578 const char *dirname
= opti
->current_dir_name
;
579 unsigned filemask
= mask
& ~dirmask
;
580 unsigned match_mask
= 0; /* will be updated below */
581 unsigned mbase_null
= !(mask
& 1);
582 unsigned side1_null
= !(mask
& 2);
583 unsigned side2_null
= !(mask
& 4);
584 unsigned side1_matches_mbase
= (!side1_null
&& !mbase_null
&&
585 names
[0].mode
== names
[1].mode
&&
586 oideq(&names
[0].oid
, &names
[1].oid
));
587 unsigned side2_matches_mbase
= (!side2_null
&& !mbase_null
&&
588 names
[0].mode
== names
[2].mode
&&
589 oideq(&names
[0].oid
, &names
[2].oid
));
590 unsigned sides_match
= (!side1_null
&& !side2_null
&&
591 names
[1].mode
== names
[2].mode
&&
592 oideq(&names
[1].oid
, &names
[2].oid
));
595 * Note: When a path is a file on one side of history and a directory
596 * in another, we have a directory/file conflict. In such cases, if
597 * the conflict doesn't resolve from renames and deletions, then we
598 * always leave directories where they are and move files out of the
599 * way. Thus, while struct conflict_info has a df_conflict field to
600 * track such conflicts, we ignore that field for any directories at
601 * a path and only pay attention to it for files at the given path.
602 * The fact that we leave directories were they are also means that
603 * we do not need to worry about getting additional df_conflict
604 * information propagated from parent directories down to children
605 * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
606 * sets a newinfo.df_conflicts field specifically to propagate it).
608 unsigned df_conflict
= (filemask
!= 0) && (dirmask
!= 0);
610 /* n = 3 is a fundamental assumption. */
612 BUG("Called collect_merge_info_callback wrong");
615 * A bunch of sanity checks verifying that traverse_trees() calls
616 * us the way I expect. Could just remove these at some point,
617 * though maybe they are helpful to future code readers.
619 assert(mbase_null
== is_null_oid(&names
[0].oid
));
620 assert(side1_null
== is_null_oid(&names
[1].oid
));
621 assert(side2_null
== is_null_oid(&names
[2].oid
));
622 assert(!mbase_null
|| !side1_null
|| !side2_null
);
623 assert(mask
> 0 && mask
< 8);
625 /* Determine match_mask */
626 if (side1_matches_mbase
)
627 match_mask
= (side2_matches_mbase
? 7 : 3);
628 else if (side2_matches_mbase
)
630 else if (sides_match
)
634 * Get the name of the relevant filepath, which we'll pass to
635 * setup_path_info() for tracking.
640 len
= traverse_path_len(info
, p
->pathlen
);
642 /* +1 in both of the following lines to include the NUL byte */
643 fullpath
= xmalloc(len
+ 1);
644 make_traverse_path(fullpath
, len
+ 1, info
, p
->path
, p
->pathlen
);
647 * If mbase, side1, and side2 all match, we can resolve early. Even
648 * if these are trees, there will be no renames or anything
651 if (side1_matches_mbase
&& side2_matches_mbase
) {
652 /* mbase, side1, & side2 all match; use mbase as resolution */
653 setup_path_info(opt
, &pi
, dirname
, info
->pathlen
, fullpath
,
654 names
, names
+0, mbase_null
, 0,
655 filemask
, dirmask
, 1);
660 * Gather additional information used in rename detection.
662 collect_rename_info(opt
, names
, dirname
, fullpath
,
663 filemask
, dirmask
, match_mask
);
666 * Record information about the path so we can resolve later in
669 setup_path_info(opt
, &pi
, dirname
, info
->pathlen
, fullpath
,
670 names
, NULL
, 0, df_conflict
, filemask
, dirmask
, 0);
674 ci
->match_mask
= match_mask
;
676 /* If dirmask, recurse into subdirectories */
678 struct traverse_info newinfo
;
679 struct tree_desc t
[3];
680 void *buf
[3] = {NULL
, NULL
, NULL
};
681 const char *original_dir_name
;
684 ci
->match_mask
&= filemask
;
687 newinfo
.name
= p
->path
;
688 newinfo
.namelen
= p
->pathlen
;
689 newinfo
.pathlen
= st_add3(newinfo
.pathlen
, p
->pathlen
, 1);
691 * If this directory we are about to recurse into cared about
692 * its parent directory (the current directory) having a D/F
693 * conflict, then we'd propagate the masks in this way:
694 * newinfo.df_conflicts |= (mask & ~dirmask);
695 * But we don't worry about propagating D/F conflicts. (See
696 * comment near setting of local df_conflict variable near
697 * the beginning of this function).
700 for (i
= MERGE_BASE
; i
<= MERGE_SIDE2
; i
++) {
701 if (i
== 1 && side1_matches_mbase
)
703 else if (i
== 2 && side2_matches_mbase
)
705 else if (i
== 2 && sides_match
)
708 const struct object_id
*oid
= NULL
;
711 buf
[i
] = fill_tree_descriptor(opt
->repo
,
717 original_dir_name
= opti
->current_dir_name
;
718 opti
->current_dir_name
= pi
.string
;
719 ret
= traverse_trees(NULL
, 3, t
, &newinfo
);
720 opti
->current_dir_name
= original_dir_name
;
722 for (i
= MERGE_BASE
; i
<= MERGE_SIDE2
; i
++)
732 static int collect_merge_info(struct merge_options
*opt
,
733 struct tree
*merge_base
,
738 struct tree_desc t
[3];
739 struct traverse_info info
;
741 opt
->priv
->toplevel_dir
= "";
742 opt
->priv
->current_dir_name
= opt
->priv
->toplevel_dir
;
743 setup_traverse_info(&info
, opt
->priv
->toplevel_dir
);
744 info
.fn
= collect_merge_info_callback
;
746 info
.show_all_errors
= 1;
748 parse_tree(merge_base
);
751 init_tree_desc(t
+ 0, merge_base
->buffer
, merge_base
->size
);
752 init_tree_desc(t
+ 1, side1
->buffer
, side1
->size
);
753 init_tree_desc(t
+ 2, side2
->buffer
, side2
->size
);
755 trace2_region_enter("merge", "traverse_trees", opt
->repo
);
756 ret
= traverse_trees(NULL
, 3, t
, &info
);
757 trace2_region_leave("merge", "traverse_trees", opt
->repo
);
762 /*** Function Grouping: functions related to threeway content merges ***/
764 static int find_first_merges(struct repository
*repo
,
768 struct object_array
*result
)
771 struct object_array merges
= OBJECT_ARRAY_INIT
;
772 struct commit
*commit
;
773 int contains_another
;
775 char merged_revision
[GIT_MAX_HEXSZ
+ 2];
776 const char *rev_args
[] = { "rev-list", "--merges", "--ancestry-path",
777 "--all", merged_revision
, NULL
};
778 struct rev_info revs
;
779 struct setup_revision_opt rev_opts
;
781 memset(result
, 0, sizeof(struct object_array
));
782 memset(&rev_opts
, 0, sizeof(rev_opts
));
784 /* get all revisions that merge commit a */
785 xsnprintf(merged_revision
, sizeof(merged_revision
), "^%s",
786 oid_to_hex(&a
->object
.oid
));
787 repo_init_revisions(repo
, &revs
, NULL
);
788 rev_opts
.submodule
= path
;
789 /* FIXME: can't handle linked worktrees in submodules yet */
790 revs
.single_worktree
= path
!= NULL
;
791 setup_revisions(ARRAY_SIZE(rev_args
)-1, rev_args
, &revs
, &rev_opts
);
793 /* save all revisions from the above list that contain b */
794 if (prepare_revision_walk(&revs
))
795 die("revision walk setup failed");
796 while ((commit
= get_revision(&revs
)) != NULL
) {
797 struct object
*o
= &(commit
->object
);
798 if (in_merge_bases(b
, commit
))
799 add_object_array(o
, NULL
, &merges
);
801 reset_revision_walk();
803 /* Now we've got all merges that contain a and b. Prune all
804 * merges that contain another found merge and save them in
807 for (i
= 0; i
< merges
.nr
; i
++) {
808 struct commit
*m1
= (struct commit
*) merges
.objects
[i
].item
;
810 contains_another
= 0;
811 for (j
= 0; j
< merges
.nr
; j
++) {
812 struct commit
*m2
= (struct commit
*) merges
.objects
[j
].item
;
813 if (i
!= j
&& in_merge_bases(m2
, m1
)) {
814 contains_another
= 1;
819 if (!contains_another
)
820 add_object_array(merges
.objects
[i
].item
, NULL
, result
);
823 object_array_clear(&merges
);
827 static int merge_submodule(struct merge_options
*opt
,
829 const struct object_id
*o
,
830 const struct object_id
*a
,
831 const struct object_id
*b
,
832 struct object_id
*result
)
834 struct commit
*commit_o
, *commit_a
, *commit_b
;
836 struct object_array merges
;
837 struct strbuf sb
= STRBUF_INIT
;
840 int search
= !opt
->priv
->call_depth
;
842 /* store fallback answer in result in case we fail */
843 oidcpy(result
, opt
->priv
->call_depth
? o
: a
);
845 /* we can not handle deletion conflicts */
853 if (add_submodule_odb(path
)) {
854 path_msg(opt
, path
, 0,
855 _("Failed to merge submodule %s (not checked out)"),
860 if (!(commit_o
= lookup_commit_reference(opt
->repo
, o
)) ||
861 !(commit_a
= lookup_commit_reference(opt
->repo
, a
)) ||
862 !(commit_b
= lookup_commit_reference(opt
->repo
, b
))) {
863 path_msg(opt
, path
, 0,
864 _("Failed to merge submodule %s (commits not present)"),
869 /* check whether both changes are forward */
870 if (!in_merge_bases(commit_o
, commit_a
) ||
871 !in_merge_bases(commit_o
, commit_b
)) {
872 path_msg(opt
, path
, 0,
873 _("Failed to merge submodule %s "
874 "(commits don't follow merge-base)"),
879 /* Case #1: a is contained in b or vice versa */
880 if (in_merge_bases(commit_a
, commit_b
)) {
882 path_msg(opt
, path
, 1,
883 _("Note: Fast-forwarding submodule %s to %s"),
884 path
, oid_to_hex(b
));
887 if (in_merge_bases(commit_b
, commit_a
)) {
889 path_msg(opt
, path
, 1,
890 _("Note: Fast-forwarding submodule %s to %s"),
891 path
, oid_to_hex(a
));
896 * Case #2: There are one or more merges that contain a and b in
897 * the submodule. If there is only one, then present it as a
898 * suggestion to the user, but leave it marked unmerged so the
899 * user needs to confirm the resolution.
902 /* Skip the search if makes no sense to the calling context. */
906 /* find commit which merges them */
907 parent_count
= find_first_merges(opt
->repo
, path
, commit_a
, commit_b
,
909 switch (parent_count
) {
911 path_msg(opt
, path
, 0, _("Failed to merge submodule %s"), path
);
915 format_commit(&sb
, 4,
916 (struct commit
*)merges
.objects
[0].item
);
917 path_msg(opt
, path
, 0,
918 _("Failed to merge submodule %s, but a possible merge "
919 "resolution exists:\n%s\n"),
921 path_msg(opt
, path
, 1,
922 _("If this is correct simply add it to the index "
925 " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
926 "which will accept this suggestion.\n"),
927 oid_to_hex(&merges
.objects
[0].item
->oid
), path
);
931 for (i
= 0; i
< merges
.nr
; i
++)
932 format_commit(&sb
, 4,
933 (struct commit
*)merges
.objects
[i
].item
);
934 path_msg(opt
, path
, 0,
935 _("Failed to merge submodule %s, but multiple "
936 "possible merges exist:\n%s"), path
, sb
.buf
);
940 object_array_clear(&merges
);
944 static int merge_3way(struct merge_options
*opt
,
946 const struct object_id
*o
,
947 const struct object_id
*a
,
948 const struct object_id
*b
,
949 const char *pathnames
[3],
950 const int extra_marker_size
,
951 mmbuffer_t
*result_buf
)
953 mmfile_t orig
, src1
, src2
;
954 struct ll_merge_options ll_opts
= {0};
955 char *base
, *name1
, *name2
;
958 ll_opts
.renormalize
= opt
->renormalize
;
959 ll_opts
.extra_marker_size
= extra_marker_size
;
960 ll_opts
.xdl_opts
= opt
->xdl_opts
;
962 if (opt
->priv
->call_depth
) {
963 ll_opts
.virtual_ancestor
= 1;
966 switch (opt
->recursive_variant
) {
967 case MERGE_VARIANT_OURS
:
968 ll_opts
.variant
= XDL_MERGE_FAVOR_OURS
;
970 case MERGE_VARIANT_THEIRS
:
971 ll_opts
.variant
= XDL_MERGE_FAVOR_THEIRS
;
979 assert(pathnames
[0] && pathnames
[1] && pathnames
[2] && opt
->ancestor
);
980 if (pathnames
[0] == pathnames
[1] && pathnames
[1] == pathnames
[2]) {
981 base
= mkpathdup("%s", opt
->ancestor
);
982 name1
= mkpathdup("%s", opt
->branch1
);
983 name2
= mkpathdup("%s", opt
->branch2
);
985 base
= mkpathdup("%s:%s", opt
->ancestor
, pathnames
[0]);
986 name1
= mkpathdup("%s:%s", opt
->branch1
, pathnames
[1]);
987 name2
= mkpathdup("%s:%s", opt
->branch2
, pathnames
[2]);
990 read_mmblob(&orig
, o
);
991 read_mmblob(&src1
, a
);
992 read_mmblob(&src2
, b
);
994 merge_status
= ll_merge(result_buf
, path
, &orig
, base
,
995 &src1
, name1
, &src2
, name2
,
996 opt
->repo
->index
, &ll_opts
);
1004 return merge_status
;
1007 static int handle_content_merge(struct merge_options
*opt
,
1009 const struct version_info
*o
,
1010 const struct version_info
*a
,
1011 const struct version_info
*b
,
1012 const char *pathnames
[3],
1013 const int extra_marker_size
,
1014 struct version_info
*result
)
1017 * path is the target location where we want to put the file, and
1018 * is used to determine any normalization rules in ll_merge.
1020 * The normal case is that path and all entries in pathnames are
1021 * identical, though renames can affect which path we got one of
1022 * the three blobs to merge on various sides of history.
1024 * extra_marker_size is the amount to extend conflict markers in
1025 * ll_merge; this is neeed if we have content merges of content
1026 * merges, which happens for example with rename/rename(2to1) and
1027 * rename/add conflicts.
1032 * handle_content_merge() needs both files to be of the same type, i.e.
1033 * both files OR both submodules OR both symlinks. Conflicting types
1034 * needs to be handled elsewhere.
1036 assert((S_IFMT
& a
->mode
) == (S_IFMT
& b
->mode
));
1039 if (a
->mode
== b
->mode
|| a
->mode
== o
->mode
)
1040 result
->mode
= b
->mode
;
1042 /* must be the 100644/100755 case */
1043 assert(S_ISREG(a
->mode
));
1044 result
->mode
= a
->mode
;
1045 clean
= (b
->mode
== o
->mode
);
1047 * FIXME: If opt->priv->call_depth && !clean, then we really
1048 * should not make result->mode match either a->mode or
1049 * b->mode; that causes t6036 "check conflicting mode for
1050 * regular file" to fail. It would be best to use some other
1051 * mode, but we'll confuse all kinds of stuff if we use one
1052 * where S_ISREG(result->mode) isn't true, and if we use
1053 * something like 0100666, then tree-walk.c's calls to
1054 * canon_mode() will just normalize that to 100644 for us and
1055 * thus not solve anything.
1057 * Figure out if there's some kind of way we can work around
1063 * Trivial oid merge.
1065 * Note: While one might assume that the next four lines would
1066 * be unnecessary due to the fact that match_mask is often
1067 * setup and already handled, renames don't always take care
1070 if (oideq(&a
->oid
, &b
->oid
) || oideq(&a
->oid
, &o
->oid
))
1071 oidcpy(&result
->oid
, &b
->oid
);
1072 else if (oideq(&b
->oid
, &o
->oid
))
1073 oidcpy(&result
->oid
, &a
->oid
);
1075 /* Remaining rules depend on file vs. submodule vs. symlink. */
1076 else if (S_ISREG(a
->mode
)) {
1077 mmbuffer_t result_buf
;
1078 int ret
= 0, merge_status
;
1082 * If 'o' is different type, treat it as null so we do a
1085 two_way
= ((S_IFMT
& o
->mode
) != (S_IFMT
& a
->mode
));
1087 merge_status
= merge_3way(opt
, path
,
1088 two_way
? &null_oid
: &o
->oid
,
1090 pathnames
, extra_marker_size
,
1093 if ((merge_status
< 0) || !result_buf
.ptr
)
1094 ret
= err(opt
, _("Failed to execute internal merge"));
1097 write_object_file(result_buf
.ptr
, result_buf
.size
,
1098 blob_type
, &result
->oid
))
1099 ret
= err(opt
, _("Unable to add %s to database"),
1102 free(result_buf
.ptr
);
1105 clean
&= (merge_status
== 0);
1106 path_msg(opt
, path
, 1, _("Auto-merging %s"), path
);
1107 } else if (S_ISGITLINK(a
->mode
)) {
1108 int two_way
= ((S_IFMT
& o
->mode
) != (S_IFMT
& a
->mode
));
1109 clean
= merge_submodule(opt
, pathnames
[0],
1110 two_way
? &null_oid
: &o
->oid
,
1111 &a
->oid
, &b
->oid
, &result
->oid
);
1112 if (opt
->priv
->call_depth
&& two_way
&& !clean
) {
1113 result
->mode
= o
->mode
;
1114 oidcpy(&result
->oid
, &o
->oid
);
1116 } else if (S_ISLNK(a
->mode
)) {
1117 if (opt
->priv
->call_depth
) {
1119 result
->mode
= o
->mode
;
1120 oidcpy(&result
->oid
, &o
->oid
);
1122 switch (opt
->recursive_variant
) {
1123 case MERGE_VARIANT_NORMAL
:
1125 oidcpy(&result
->oid
, &a
->oid
);
1127 case MERGE_VARIANT_OURS
:
1128 oidcpy(&result
->oid
, &a
->oid
);
1130 case MERGE_VARIANT_THEIRS
:
1131 oidcpy(&result
->oid
, &b
->oid
);
1136 BUG("unsupported object type in the tree: %06o for %s",
1142 /*** Function Grouping: functions related to detect_and_process_renames(), ***
1143 *** which are split into directory and regular rename detection sections. ***/
1145 /*** Function Grouping: functions related to directory rename detection ***/
1147 struct collision_info
{
1148 struct string_list source_files
;
1149 unsigned reported_already
:1;
1153 * Return a new string that replaces the beginning portion (which matches
1154 * rename_info->key), with rename_info->util.new_dir. In perl-speak:
1155 * new_path_name = (old_path =~ s/rename_info->key/rename_info->value/);
1157 * Caller must ensure that old_path starts with rename_info->key + '/'.
1159 static char *apply_dir_rename(struct strmap_entry
*rename_info
,
1160 const char *old_path
)
1162 struct strbuf new_path
= STRBUF_INIT
;
1163 const char *old_dir
= rename_info
->key
;
1164 const char *new_dir
= rename_info
->value
;
1165 int oldlen
, newlen
, new_dir_len
;
1167 oldlen
= strlen(old_dir
);
1168 if (*new_dir
== '\0')
1170 * If someone renamed/merged a subdirectory into the root
1171 * directory (e.g. 'some/subdir' -> ''), then we want to
1174 * as the rename; we need to make old_path + oldlen advance
1175 * past the '/' character.
1178 new_dir_len
= strlen(new_dir
);
1179 newlen
= new_dir_len
+ (strlen(old_path
) - oldlen
) + 1;
1180 strbuf_grow(&new_path
, newlen
);
1181 strbuf_add(&new_path
, new_dir
, new_dir_len
);
1182 strbuf_addstr(&new_path
, &old_path
[oldlen
]);
1184 return strbuf_detach(&new_path
, NULL
);
1187 static int path_in_way(struct strmap
*paths
, const char *path
, unsigned side_mask
)
1189 struct merged_info
*mi
= strmap_get(paths
, path
);
1190 struct conflict_info
*ci
;
1193 INITIALIZE_CI(ci
, mi
);
1194 return mi
->clean
|| (side_mask
& (ci
->filemask
| ci
->dirmask
));
1198 * See if there is a directory rename for path, and if there are any file
1199 * level conflicts on the given side for the renamed location. If there is
1200 * a rename and there are no conflicts, return the new name. Otherwise,
1203 static char *handle_path_level_conflicts(struct merge_options
*opt
,
1205 unsigned side_index
,
1206 struct strmap_entry
*rename_info
,
1207 struct strmap
*collisions
)
1209 char *new_path
= NULL
;
1210 struct collision_info
*c_info
;
1212 struct strbuf collision_paths
= STRBUF_INIT
;
1215 * entry has the mapping of old directory name to new directory name
1216 * that we want to apply to path.
1218 new_path
= apply_dir_rename(rename_info
, path
);
1220 BUG("Failed to apply directory rename!");
1223 * The caller needs to have ensured that it has pre-populated
1224 * collisions with all paths that map to new_path. Do a quick check
1225 * to ensure that's the case.
1227 c_info
= strmap_get(collisions
, new_path
);
1229 BUG("c_info is NULL");
1232 * Check for one-sided add/add/.../add conflicts, i.e.
1233 * where implicit renames from the other side doing
1234 * directory rename(s) can affect this side of history
1235 * to put multiple paths into the same location. Warn
1236 * and bail on directory renames for such paths.
1238 if (c_info
->reported_already
) {
1240 } else if (path_in_way(&opt
->priv
->paths
, new_path
, 1 << side_index
)) {
1241 c_info
->reported_already
= 1;
1242 strbuf_add_separated_string_list(&collision_paths
, ", ",
1243 &c_info
->source_files
);
1244 path_msg(opt
, new_path
, 0,
1245 _("CONFLICT (implicit dir rename): Existing file/dir "
1246 "at %s in the way of implicit directory rename(s) "
1247 "putting the following path(s) there: %s."),
1248 new_path
, collision_paths
.buf
);
1250 } else if (c_info
->source_files
.nr
> 1) {
1251 c_info
->reported_already
= 1;
1252 strbuf_add_separated_string_list(&collision_paths
, ", ",
1253 &c_info
->source_files
);
1254 path_msg(opt
, new_path
, 0,
1255 _("CONFLICT (implicit dir rename): Cannot map more "
1256 "than one path to %s; implicit directory renames "
1257 "tried to put these paths there: %s"),
1258 new_path
, collision_paths
.buf
);
1262 /* Free memory we no longer need */
1263 strbuf_release(&collision_paths
);
1264 if (!clean
&& new_path
) {
1272 static void dirname_munge(char *filename
)
1274 char *slash
= strrchr(filename
, '/');
1280 static void increment_count(struct strmap
*dir_rename_count
,
1284 struct strintmap
*counts
;
1285 struct strmap_entry
*e
;
1287 /* Get the {new_dirs -> counts} mapping using old_dir */
1288 e
= strmap_get_entry(dir_rename_count
, old_dir
);
1292 counts
= xmalloc(sizeof(*counts
));
1293 strintmap_init_with_options(counts
, 0, NULL
, 1);
1294 strmap_put(dir_rename_count
, old_dir
, counts
);
1297 /* Increment the count for new_dir */
1298 strintmap_incr(counts
, new_dir
, 1);
1301 static void update_dir_rename_counts(struct strmap
*dir_rename_count
,
1302 struct strset
*dirs_removed
,
1303 const char *oldname
,
1304 const char *newname
)
1306 char *old_dir
= xstrdup(oldname
);
1307 char *new_dir
= xstrdup(newname
);
1308 char new_dir_first_char
= new_dir
[0];
1309 int first_time_in_loop
= 1;
1312 dirname_munge(old_dir
);
1313 dirname_munge(new_dir
);
1317 * "a/b/c/d/e/foo.c" -> "a/b/some/thing/else/e/foo.c"
1318 * then this suggests that both
1319 * a/b/c/d/e/ => a/b/some/thing/else/e/
1320 * a/b/c/d/ => a/b/some/thing/else/
1321 * so we want to increment counters for both. We do NOT,
1322 * however, also want to suggest that there was the following
1324 * a/b/c/ => a/b/some/thing/
1325 * so we need to quit at that point.
1327 * Note the when first_time_in_loop, we only strip off the
1328 * basename, and we don't care if that's different.
1330 if (!first_time_in_loop
) {
1331 char *old_sub_dir
= strchr(old_dir
, '\0')+1;
1332 char *new_sub_dir
= strchr(new_dir
, '\0')+1;
1335 * Special case when renaming to root directory,
1336 * i.e. when new_dir == "". In this case, we had
1338 * a/b/subdir => subdir
1339 * and so dirname_munge() sets things up so that
1340 * old_dir = "a/b\0subdir\0"
1341 * new_dir = "\0ubdir\0"
1342 * We didn't have a '/' to overwrite a '\0' onto
1343 * in new_dir, so we have to compare differently.
1345 if (new_dir_first_char
!= old_sub_dir
[0] ||
1346 strcmp(old_sub_dir
+1, new_sub_dir
))
1349 if (strcmp(old_sub_dir
, new_sub_dir
))
1354 if (strset_contains(dirs_removed
, old_dir
))
1355 increment_count(dir_rename_count
, old_dir
, new_dir
);
1359 /* If we hit toplevel directory ("") for old or new dir, quit */
1360 if (!*old_dir
|| !*new_dir
)
1363 first_time_in_loop
= 0;
1366 /* Free resources we don't need anymore */
1371 static void compute_rename_counts(struct diff_queue_struct
*pairs
,
1372 struct strmap
*dir_rename_count
,
1373 struct strset
*dirs_removed
)
1377 for (i
= 0; i
< pairs
->nr
; ++i
) {
1378 struct diff_filepair
*pair
= pairs
->queue
[i
];
1380 /* File not part of directory rename if it wasn't renamed */
1381 if (pair
->status
!= 'R')
1385 * Make dir_rename_count contain a map of a map:
1386 * old_directory -> {new_directory -> count}
1387 * In other words, for every pair look at the directories for
1388 * the old filename and the new filename and count how many
1389 * times that pairing occurs.
1391 update_dir_rename_counts(dir_rename_count
, dirs_removed
,
1397 static void get_provisional_directory_renames(struct merge_options
*opt
,
1401 struct hashmap_iter iter
;
1402 struct strmap_entry
*entry
;
1403 struct rename_info
*renames
= &opt
->priv
->renames
;
1405 compute_rename_counts(&renames
->pairs
[side
],
1406 &renames
->dir_rename_count
[side
],
1407 &renames
->dirs_removed
[side
]);
1410 * dir_rename_count: old_directory -> {new_directory -> count}
1412 * dir_renames: old_directory -> best_new_directory
1413 * where best_new_directory is the one with the unique highest count.
1415 strmap_for_each_entry(&renames
->dir_rename_count
[side
], &iter
, entry
) {
1416 const char *source_dir
= entry
->key
;
1417 struct strintmap
*counts
= entry
->value
;
1418 struct hashmap_iter count_iter
;
1419 struct strmap_entry
*count_entry
;
1422 const char *best
= NULL
;
1424 strintmap_for_each_entry(counts
, &count_iter
, count_entry
) {
1425 const char *target_dir
= count_entry
->key
;
1426 intptr_t count
= (intptr_t)count_entry
->value
;
1430 else if (count
> max
) {
1436 if (bad_max
== max
) {
1437 path_msg(opt
, source_dir
, 0,
1438 _("CONFLICT (directory rename split): "
1439 "Unclear where to rename %s to; it was "
1440 "renamed to multiple other directories, with "
1441 "no destination getting a majority of the "
1445 * We should mark this as unclean IF something attempts
1446 * to use this rename. We do not yet have the logic
1447 * in place to detect if this directory rename is being
1448 * used, and optimizations that reduce the number of
1449 * renames cause this to falsely trigger. For now,
1450 * just disable it, causing t6423 testcase 2a to break.
1451 * We'll later fix the detection, and when we do we
1452 * will re-enable setting *clean to 0 (and thereby fix
1453 * t6423 testcase 2a).
1457 strmap_put(&renames
->dir_renames
[side
],
1458 source_dir
, (void*)best
);
1463 static void handle_directory_level_conflicts(struct merge_options
*opt
)
1465 struct hashmap_iter iter
;
1466 struct strmap_entry
*entry
;
1467 struct string_list duplicated
= STRING_LIST_INIT_NODUP
;
1468 struct rename_info
*renames
= &opt
->priv
->renames
;
1469 struct strmap
*side1_dir_renames
= &renames
->dir_renames
[MERGE_SIDE1
];
1470 struct strmap
*side2_dir_renames
= &renames
->dir_renames
[MERGE_SIDE2
];
1473 strmap_for_each_entry(side1_dir_renames
, &iter
, entry
) {
1474 if (strmap_contains(side2_dir_renames
, entry
->key
))
1475 string_list_append(&duplicated
, entry
->key
);
1478 for (i
= 0; i
< duplicated
.nr
; i
++) {
1479 strmap_remove(side1_dir_renames
, duplicated
.items
[i
].string
, 0);
1480 strmap_remove(side2_dir_renames
, duplicated
.items
[i
].string
, 0);
1482 string_list_clear(&duplicated
, 0);
1485 static struct strmap_entry
*check_dir_renamed(const char *path
,
1486 struct strmap
*dir_renames
)
1488 char *temp
= xstrdup(path
);
1490 struct strmap_entry
*e
= NULL
;
1492 while ((end
= strrchr(temp
, '/'))) {
1494 e
= strmap_get_entry(dir_renames
, temp
);
1502 static void compute_collisions(struct strmap
*collisions
,
1503 struct strmap
*dir_renames
,
1504 struct diff_queue_struct
*pairs
)
1508 strmap_init_with_options(collisions
, NULL
, 0);
1509 if (strmap_empty(dir_renames
))
1513 * Multiple files can be mapped to the same path due to directory
1514 * renames done by the other side of history. Since that other
1515 * side of history could have merged multiple directories into one,
1516 * if our side of history added the same file basename to each of
1517 * those directories, then all N of them would get implicitly
1518 * renamed by the directory rename detection into the same path,
1519 * and we'd get an add/add/.../add conflict, and all those adds
1520 * from *this* side of history. This is not representable in the
1521 * index, and users aren't going to easily be able to make sense of
1522 * it. So we need to provide a good warning about what's
1523 * happening, and fall back to no-directory-rename detection
1524 * behavior for those paths.
1526 * See testcases 9e and all of section 5 from t6043 for examples.
1528 for (i
= 0; i
< pairs
->nr
; ++i
) {
1529 struct strmap_entry
*rename_info
;
1530 struct collision_info
*collision_info
;
1532 struct diff_filepair
*pair
= pairs
->queue
[i
];
1534 if (pair
->status
!= 'A' && pair
->status
!= 'R')
1536 rename_info
= check_dir_renamed(pair
->two
->path
, dir_renames
);
1540 new_path
= apply_dir_rename(rename_info
, pair
->two
->path
);
1542 collision_info
= strmap_get(collisions
, new_path
);
1543 if (collision_info
) {
1546 collision_info
= xcalloc(1,
1547 sizeof(struct collision_info
));
1548 string_list_init(&collision_info
->source_files
, 0);
1549 strmap_put(collisions
, new_path
, collision_info
);
1551 string_list_insert(&collision_info
->source_files
,
1556 static char *check_for_directory_rename(struct merge_options
*opt
,
1558 unsigned side_index
,
1559 struct strmap
*dir_renames
,
1560 struct strmap
*dir_rename_exclusions
,
1561 struct strmap
*collisions
,
1564 char *new_path
= NULL
;
1565 struct strmap_entry
*rename_info
;
1566 struct strmap_entry
*otherinfo
= NULL
;
1567 const char *new_dir
;
1569 if (strmap_empty(dir_renames
))
1571 rename_info
= check_dir_renamed(path
, dir_renames
);
1574 /* old_dir = rename_info->key; */
1575 new_dir
= rename_info
->value
;
1578 * This next part is a little weird. We do not want to do an
1579 * implicit rename into a directory we renamed on our side, because
1580 * that will result in a spurious rename/rename(1to2) conflict. An
1582 * Base commit: dumbdir/afile, otherdir/bfile
1583 * Side 1: smrtdir/afile, otherdir/bfile
1584 * Side 2: dumbdir/afile, dumbdir/bfile
1585 * Here, while working on Side 1, we could notice that otherdir was
1586 * renamed/merged to dumbdir, and change the diff_filepair for
1587 * otherdir/bfile into a rename into dumbdir/bfile. However, Side
1588 * 2 will notice the rename from dumbdir to smrtdir, and do the
1589 * transitive rename to move it from dumbdir/bfile to
1590 * smrtdir/bfile. That gives us bfile in dumbdir vs being in
1591 * smrtdir, a rename/rename(1to2) conflict. We really just want
1592 * the file to end up in smrtdir. And the way to achieve that is
1593 * to not let Side1 do the rename to dumbdir, since we know that is
1594 * the source of one of our directory renames.
1596 * That's why otherinfo and dir_rename_exclusions is here.
1598 * As it turns out, this also prevents N-way transient rename
1599 * confusion; See testcases 9c and 9d of t6043.
1601 otherinfo
= strmap_get_entry(dir_rename_exclusions
, new_dir
);
1603 path_msg(opt
, rename_info
->key
, 1,
1604 _("WARNING: Avoiding applying %s -> %s rename "
1605 "to %s, because %s itself was renamed."),
1606 rename_info
->key
, new_dir
, path
, new_dir
);
1610 new_path
= handle_path_level_conflicts(opt
, path
, side_index
,
1611 rename_info
, collisions
);
1612 *clean_merge
&= (new_path
!= NULL
);
1617 static void apply_directory_rename_modifications(struct merge_options
*opt
,
1618 struct diff_filepair
*pair
,
1622 * The basic idea is to get the conflict_info from opt->priv->paths
1623 * at old path, and insert it into new_path; basically just this:
1624 * ci = strmap_get(&opt->priv->paths, old_path);
1625 * strmap_remove(&opt->priv->paths, old_path, 0);
1626 * strmap_put(&opt->priv->paths, new_path, ci);
1627 * However, there are some factors complicating this:
1628 * - opt->priv->paths may already have an entry at new_path
1629 * - Each ci tracks its containing directory, so we need to
1631 * - If another ci has the same containing directory, then
1632 * the two char*'s MUST point to the same location. See the
1633 * comment in struct merged_info. strcmp equality is not
1634 * enough; we need pointer equality.
1635 * - opt->priv->paths must hold the parent directories of any
1636 * entries that are added. So, if this directory rename
1637 * causes entirely new directories, we must recursively add
1638 * parent directories.
1639 * - For each parent directory added to opt->priv->paths, we
1640 * also need to get its parent directory stored in its
1641 * conflict_info->merged.directory_name with all the same
1642 * requirements about pointer equality.
1644 struct string_list dirs_to_insert
= STRING_LIST_INIT_NODUP
;
1645 struct conflict_info
*ci
, *new_ci
;
1646 struct strmap_entry
*entry
;
1647 const char *branch_with_new_path
, *branch_with_dir_rename
;
1648 const char *old_path
= pair
->two
->path
;
1649 const char *parent_name
;
1650 const char *cur_path
;
1653 entry
= strmap_get_entry(&opt
->priv
->paths
, old_path
);
1654 old_path
= entry
->key
;
1658 /* Find parent directories missing from opt->priv->paths */
1659 cur_path
= new_path
;
1661 /* Find the parent directory of cur_path */
1662 char *last_slash
= strrchr(cur_path
, '/');
1664 parent_name
= xstrndup(cur_path
, last_slash
- cur_path
);
1666 parent_name
= opt
->priv
->toplevel_dir
;
1670 /* Look it up in opt->priv->paths */
1671 entry
= strmap_get_entry(&opt
->priv
->paths
, parent_name
);
1673 free((char*)parent_name
);
1674 parent_name
= entry
->key
; /* reuse known pointer */
1678 /* Record this is one of the directories we need to insert */
1679 string_list_append(&dirs_to_insert
, parent_name
);
1680 cur_path
= parent_name
;
1683 /* Traverse dirs_to_insert and insert them into opt->priv->paths */
1684 for (i
= dirs_to_insert
.nr
-1; i
>= 0; --i
) {
1685 struct conflict_info
*dir_ci
;
1686 char *cur_dir
= dirs_to_insert
.items
[i
].string
;
1688 dir_ci
= xcalloc(1, sizeof(*dir_ci
));
1690 dir_ci
->merged
.directory_name
= parent_name
;
1691 len
= strlen(parent_name
);
1692 /* len+1 because of trailing '/' character */
1693 dir_ci
->merged
.basename_offset
= (len
> 0 ? len
+1 : len
);
1694 dir_ci
->dirmask
= ci
->filemask
;
1695 strmap_put(&opt
->priv
->paths
, cur_dir
, dir_ci
);
1697 parent_name
= cur_dir
;
1701 * We are removing old_path from opt->priv->paths. old_path also will
1702 * eventually need to be freed, but it may still be used by e.g.
1703 * ci->pathnames. So, store it in another string-list for now.
1705 string_list_append(&opt
->priv
->paths_to_free
, old_path
);
1707 assert(ci
->filemask
== 2 || ci
->filemask
== 4);
1708 assert(ci
->dirmask
== 0);
1709 strmap_remove(&opt
->priv
->paths
, old_path
, 0);
1711 branch_with_new_path
= (ci
->filemask
== 2) ? opt
->branch1
: opt
->branch2
;
1712 branch_with_dir_rename
= (ci
->filemask
== 2) ? opt
->branch2
: opt
->branch1
;
1714 /* Now, finally update ci and stick it into opt->priv->paths */
1715 ci
->merged
.directory_name
= parent_name
;
1716 len
= strlen(parent_name
);
1717 ci
->merged
.basename_offset
= (len
> 0 ? len
+1 : len
);
1718 new_ci
= strmap_get(&opt
->priv
->paths
, new_path
);
1720 /* Place ci back into opt->priv->paths, but at new_path */
1721 strmap_put(&opt
->priv
->paths
, new_path
, ci
);
1725 /* A few sanity checks */
1727 assert(ci
->filemask
== 2 || ci
->filemask
== 4);
1728 assert((new_ci
->filemask
& ci
->filemask
) == 0);
1729 assert(!new_ci
->merged
.clean
);
1731 /* Copy stuff from ci into new_ci */
1732 new_ci
->filemask
|= ci
->filemask
;
1733 if (new_ci
->dirmask
)
1734 new_ci
->df_conflict
= 1;
1735 index
= (ci
->filemask
>> 1);
1736 new_ci
->pathnames
[index
] = ci
->pathnames
[index
];
1737 new_ci
->stages
[index
].mode
= ci
->stages
[index
].mode
;
1738 oidcpy(&new_ci
->stages
[index
].oid
, &ci
->stages
[index
].oid
);
1744 if (opt
->detect_directory_renames
== MERGE_DIRECTORY_RENAMES_TRUE
) {
1745 /* Notify user of updated path */
1746 if (pair
->status
== 'A')
1747 path_msg(opt
, new_path
, 1,
1748 _("Path updated: %s added in %s inside a "
1749 "directory that was renamed in %s; moving "
1751 old_path
, branch_with_new_path
,
1752 branch_with_dir_rename
, new_path
);
1754 path_msg(opt
, new_path
, 1,
1755 _("Path updated: %s renamed to %s in %s, "
1756 "inside a directory that was renamed in %s; "
1757 "moving it to %s."),
1758 pair
->one
->path
, old_path
, branch_with_new_path
,
1759 branch_with_dir_rename
, new_path
);
1762 * opt->detect_directory_renames has the value
1763 * MERGE_DIRECTORY_RENAMES_CONFLICT, so mark these as conflicts.
1765 ci
->path_conflict
= 1;
1766 if (pair
->status
== 'A')
1767 path_msg(opt
, new_path
, 0,
1768 _("CONFLICT (file location): %s added in %s "
1769 "inside a directory that was renamed in %s, "
1770 "suggesting it should perhaps be moved to "
1772 old_path
, branch_with_new_path
,
1773 branch_with_dir_rename
, new_path
);
1775 path_msg(opt
, new_path
, 0,
1776 _("CONFLICT (file location): %s renamed to %s "
1777 "in %s, inside a directory that was renamed "
1778 "in %s, suggesting it should perhaps be "
1780 pair
->one
->path
, old_path
, branch_with_new_path
,
1781 branch_with_dir_rename
, new_path
);
1785 * Finally, record the new location.
1787 pair
->two
->path
= new_path
;
1790 /*** Function Grouping: functions related to regular rename detection ***/
1792 static int process_renames(struct merge_options
*opt
,
1793 struct diff_queue_struct
*renames
)
1795 int clean_merge
= 1, i
;
1797 for (i
= 0; i
< renames
->nr
; ++i
) {
1798 const char *oldpath
= NULL
, *newpath
;
1799 struct diff_filepair
*pair
= renames
->queue
[i
];
1800 struct conflict_info
*oldinfo
= NULL
, *newinfo
= NULL
;
1801 struct strmap_entry
*old_ent
, *new_ent
;
1802 unsigned int old_sidemask
;
1803 int target_index
, other_source_index
;
1804 int source_deleted
, collision
, type_changed
;
1805 const char *rename_branch
= NULL
, *delete_branch
= NULL
;
1807 old_ent
= strmap_get_entry(&opt
->priv
->paths
, pair
->one
->path
);
1808 new_ent
= strmap_get_entry(&opt
->priv
->paths
, pair
->two
->path
);
1810 oldpath
= old_ent
->key
;
1811 oldinfo
= old_ent
->value
;
1813 newpath
= pair
->two
->path
;
1815 newpath
= new_ent
->key
;
1816 newinfo
= new_ent
->value
;
1820 * If pair->one->path isn't in opt->priv->paths, that means
1821 * that either directory rename detection removed that
1822 * path, or a parent directory of oldpath was resolved and
1823 * we don't even need the rename; in either case, we can
1824 * skip it. If oldinfo->merged.clean, then the other side
1825 * of history had no changes to oldpath and we don't need
1826 * the rename and can skip it.
1828 if (!oldinfo
|| oldinfo
->merged
.clean
)
1832 * diff_filepairs have copies of pathnames, thus we have to
1833 * use standard 'strcmp()' (negated) instead of '=='.
1835 if (i
+ 1 < renames
->nr
&&
1836 !strcmp(oldpath
, renames
->queue
[i
+1]->one
->path
)) {
1837 /* Handle rename/rename(1to2) or rename/rename(1to1) */
1838 const char *pathnames
[3];
1839 struct version_info merged
;
1840 struct conflict_info
*base
, *side1
, *side2
;
1841 unsigned was_binary_blob
= 0;
1843 pathnames
[0] = oldpath
;
1844 pathnames
[1] = newpath
;
1845 pathnames
[2] = renames
->queue
[i
+1]->two
->path
;
1847 base
= strmap_get(&opt
->priv
->paths
, pathnames
[0]);
1848 side1
= strmap_get(&opt
->priv
->paths
, pathnames
[1]);
1849 side2
= strmap_get(&opt
->priv
->paths
, pathnames
[2]);
1855 if (!strcmp(pathnames
[1], pathnames
[2])) {
1856 /* Both sides renamed the same way */
1857 assert(side1
== side2
);
1858 memcpy(&side1
->stages
[0], &base
->stages
[0],
1860 side1
->filemask
|= (1 << MERGE_BASE
);
1861 /* Mark base as resolved by removal */
1862 base
->merged
.is_null
= 1;
1863 base
->merged
.clean
= 1;
1865 /* We handled both renames, i.e. i+1 handled */
1867 /* Move to next rename */
1871 /* This is a rename/rename(1to2) */
1872 clean_merge
= handle_content_merge(opt
,
1878 1 + 2 * opt
->priv
->call_depth
,
1881 merged
.mode
== side1
->stages
[1].mode
&&
1882 oideq(&merged
.oid
, &side1
->stages
[1].oid
))
1883 was_binary_blob
= 1;
1884 memcpy(&side1
->stages
[1], &merged
, sizeof(merged
));
1885 if (was_binary_blob
) {
1887 * Getting here means we were attempting to
1888 * merge a binary blob.
1890 * Since we can't merge binaries,
1891 * handle_content_merge() just takes one
1892 * side. But we don't want to copy the
1893 * contents of one side to both paths. We
1894 * used the contents of side1 above for
1895 * side1->stages, let's use the contents of
1896 * side2 for side2->stages below.
1898 oidcpy(&merged
.oid
, &side2
->stages
[2].oid
);
1899 merged
.mode
= side2
->stages
[2].mode
;
1901 memcpy(&side2
->stages
[2], &merged
, sizeof(merged
));
1903 side1
->path_conflict
= 1;
1904 side2
->path_conflict
= 1;
1906 * TODO: For renames we normally remove the path at the
1907 * old name. It would thus seem consistent to do the
1908 * same for rename/rename(1to2) cases, but we haven't
1909 * done so traditionally and a number of the regression
1910 * tests now encode an expectation that the file is
1911 * left there at stage 1. If we ever decide to change
1912 * this, add the following two lines here:
1913 * base->merged.is_null = 1;
1914 * base->merged.clean = 1;
1915 * and remove the setting of base->path_conflict to 1.
1917 base
->path_conflict
= 1;
1918 path_msg(opt
, oldpath
, 0,
1919 _("CONFLICT (rename/rename): %s renamed to "
1920 "%s in %s and to %s in %s."),
1922 pathnames
[1], opt
->branch1
,
1923 pathnames
[2], opt
->branch2
);
1925 i
++; /* We handled both renames, i.e. i+1 handled */
1931 target_index
= pair
->score
; /* from collect_renames() */
1932 assert(target_index
== 1 || target_index
== 2);
1933 other_source_index
= 3 - target_index
;
1934 old_sidemask
= (1 << other_source_index
); /* 2 or 4 */
1935 source_deleted
= (oldinfo
->filemask
== 1);
1936 collision
= ((newinfo
->filemask
& old_sidemask
) != 0);
1937 type_changed
= !source_deleted
&&
1938 (S_ISREG(oldinfo
->stages
[other_source_index
].mode
) !=
1939 S_ISREG(newinfo
->stages
[target_index
].mode
));
1940 if (type_changed
&& collision
) {
1942 * special handling so later blocks can handle this...
1944 * if type_changed && collision are both true, then this
1945 * was really a double rename, but one side wasn't
1946 * detected due to lack of break detection. I.e.
1948 * orig: has normal file 'foo'
1949 * side1: renames 'foo' to 'bar', adds 'foo' symlink
1950 * side2: renames 'foo' to 'bar'
1951 * In this case, the foo->bar rename on side1 won't be
1952 * detected because the new symlink named 'foo' is
1953 * there and we don't do break detection. But we detect
1954 * this here because we don't want to merge the content
1955 * of the foo symlink with the foo->bar file, so we
1956 * have some logic to handle this special case. The
1957 * easiest way to do that is make 'bar' on side1 not
1958 * be considered a colliding file but the other part
1959 * of a normal rename. If the file is very different,
1960 * well we're going to get content merge conflicts
1961 * anyway so it doesn't hurt. And if the colliding
1962 * file also has a different type, that'll be handled
1963 * by the content merge logic in process_entry() too.
1965 * See also t6430, 'rename vs. rename/symlink'
1969 if (source_deleted
) {
1970 if (target_index
== 1) {
1971 rename_branch
= opt
->branch1
;
1972 delete_branch
= opt
->branch2
;
1974 rename_branch
= opt
->branch2
;
1975 delete_branch
= opt
->branch1
;
1979 assert(source_deleted
|| oldinfo
->filemask
& old_sidemask
);
1981 /* Need to check for special types of rename conflicts... */
1982 if (collision
&& !source_deleted
) {
1983 /* collision: rename/add or rename/rename(2to1) */
1984 const char *pathnames
[3];
1985 struct version_info merged
;
1987 struct conflict_info
*base
, *side1
, *side2
;
1990 pathnames
[0] = oldpath
;
1991 pathnames
[other_source_index
] = oldpath
;
1992 pathnames
[target_index
] = newpath
;
1994 base
= strmap_get(&opt
->priv
->paths
, pathnames
[0]);
1995 side1
= strmap_get(&opt
->priv
->paths
, pathnames
[1]);
1996 side2
= strmap_get(&opt
->priv
->paths
, pathnames
[2]);
2002 clean
= handle_content_merge(opt
, pair
->one
->path
,
2007 1 + 2 * opt
->priv
->call_depth
,
2010 memcpy(&newinfo
->stages
[target_index
], &merged
,
2013 path_msg(opt
, newpath
, 0,
2014 _("CONFLICT (rename involved in "
2015 "collision): rename of %s -> %s has "
2016 "content conflicts AND collides "
2017 "with another path; this may result "
2018 "in nested conflict markers."),
2021 } else if (collision
&& source_deleted
) {
2023 * rename/add/delete or rename/rename(2to1)/delete:
2024 * since oldpath was deleted on the side that didn't
2025 * do the rename, there's not much of a content merge
2026 * we can do for the rename. oldinfo->merged.is_null
2027 * was already set, so we just leave things as-is so
2028 * they look like an add/add conflict.
2031 newinfo
->path_conflict
= 1;
2032 path_msg(opt
, newpath
, 0,
2033 _("CONFLICT (rename/delete): %s renamed "
2034 "to %s in %s, but deleted in %s."),
2035 oldpath
, newpath
, rename_branch
, delete_branch
);
2038 * a few different cases...start by copying the
2039 * existing stage(s) from oldinfo over the newinfo
2040 * and update the pathname(s).
2042 memcpy(&newinfo
->stages
[0], &oldinfo
->stages
[0],
2043 sizeof(newinfo
->stages
[0]));
2044 newinfo
->filemask
|= (1 << MERGE_BASE
);
2045 newinfo
->pathnames
[0] = oldpath
;
2047 /* rename vs. typechange */
2048 /* Mark the original as resolved by removal */
2049 memcpy(&oldinfo
->stages
[0].oid
, &null_oid
,
2050 sizeof(oldinfo
->stages
[0].oid
));
2051 oldinfo
->stages
[0].mode
= 0;
2052 oldinfo
->filemask
&= 0x06;
2053 } else if (source_deleted
) {
2055 newinfo
->path_conflict
= 1;
2056 path_msg(opt
, newpath
, 0,
2057 _("CONFLICT (rename/delete): %s renamed"
2058 " to %s in %s, but deleted in %s."),
2060 rename_branch
, delete_branch
);
2063 memcpy(&newinfo
->stages
[other_source_index
],
2064 &oldinfo
->stages
[other_source_index
],
2065 sizeof(newinfo
->stages
[0]));
2066 newinfo
->filemask
|= (1 << other_source_index
);
2067 newinfo
->pathnames
[other_source_index
] = oldpath
;
2071 if (!type_changed
) {
2072 /* Mark the original as resolved by removal */
2073 oldinfo
->merged
.is_null
= 1;
2074 oldinfo
->merged
.clean
= 1;
2082 static int compare_pairs(const void *a_
, const void *b_
)
2084 const struct diff_filepair
*a
= *((const struct diff_filepair
**)a_
);
2085 const struct diff_filepair
*b
= *((const struct diff_filepair
**)b_
);
2087 return strcmp(a
->one
->path
, b
->one
->path
);
2090 /* Call diffcore_rename() to compute which files have changed on given side */
2091 static void detect_regular_renames(struct merge_options
*opt
,
2092 struct tree
*merge_base
,
2094 unsigned side_index
)
2096 struct diff_options diff_opts
;
2097 struct rename_info
*renames
= &opt
->priv
->renames
;
2099 repo_diff_setup(opt
->repo
, &diff_opts
);
2100 diff_opts
.flags
.recursive
= 1;
2101 diff_opts
.flags
.rename_empty
= 0;
2102 diff_opts
.detect_rename
= DIFF_DETECT_RENAME
;
2103 diff_opts
.rename_limit
= opt
->rename_limit
;
2104 if (opt
->rename_limit
<= 0)
2105 diff_opts
.rename_limit
= 1000;
2106 diff_opts
.rename_score
= opt
->rename_score
;
2107 diff_opts
.show_rename_progress
= opt
->show_rename_progress
;
2108 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
2109 diff_setup_done(&diff_opts
);
2111 trace2_region_enter("diff", "diffcore_rename", opt
->repo
);
2112 diff_tree_oid(&merge_base
->object
.oid
, &side
->object
.oid
, "",
2114 diffcore_std(&diff_opts
);
2115 trace2_region_leave("diff", "diffcore_rename", opt
->repo
);
2117 if (diff_opts
.needed_rename_limit
> renames
->needed_limit
)
2118 renames
->needed_limit
= diff_opts
.needed_rename_limit
;
2120 renames
->pairs
[side_index
] = diff_queued_diff
;
2122 diff_opts
.output_format
= DIFF_FORMAT_NO_OUTPUT
;
2123 diff_queued_diff
.nr
= 0;
2124 diff_queued_diff
.queue
= NULL
;
2125 diff_flush(&diff_opts
);
2129 * Get information of all renames which occurred in 'side_pairs', discarding
2132 static int collect_renames(struct merge_options
*opt
,
2133 struct diff_queue_struct
*result
,
2134 unsigned side_index
,
2135 struct strmap
*dir_renames_for_side
,
2136 struct strmap
*rename_exclusions
)
2139 struct strmap collisions
;
2140 struct diff_queue_struct
*side_pairs
;
2141 struct hashmap_iter iter
;
2142 struct strmap_entry
*entry
;
2143 struct rename_info
*renames
= &opt
->priv
->renames
;
2145 side_pairs
= &renames
->pairs
[side_index
];
2146 compute_collisions(&collisions
, dir_renames_for_side
, side_pairs
);
2148 for (i
= 0; i
< side_pairs
->nr
; ++i
) {
2149 struct diff_filepair
*p
= side_pairs
->queue
[i
];
2150 char *new_path
; /* non-NULL only with directory renames */
2152 if (p
->status
!= 'A' && p
->status
!= 'R') {
2153 diff_free_filepair(p
);
2157 new_path
= check_for_directory_rename(opt
, p
->two
->path
,
2159 dir_renames_for_side
,
2164 if (p
->status
!= 'R' && !new_path
) {
2165 diff_free_filepair(p
);
2170 apply_directory_rename_modifications(opt
, p
, new_path
);
2173 * p->score comes back from diffcore_rename_extended() with
2174 * the similarity of the renamed file. The similarity is
2175 * was used to determine that the two files were related
2176 * and are a rename, which we have already used, but beyond
2177 * that we have no use for the similarity. So p->score is
2178 * now irrelevant. However, process_renames() will need to
2179 * know which side of the merge this rename was associated
2180 * with, so overwrite p->score with that value.
2182 p
->score
= side_index
;
2183 result
->queue
[result
->nr
++] = p
;
2186 /* Free each value in the collisions map */
2187 strmap_for_each_entry(&collisions
, &iter
, entry
) {
2188 struct collision_info
*info
= entry
->value
;
2189 string_list_clear(&info
->source_files
, 0);
2192 * In compute_collisions(), we set collisions.strdup_strings to 0
2193 * so that we wouldn't have to make another copy of the new_path
2194 * allocated by apply_dir_rename(). But now that we've used them
2195 * and have no other references to these strings, it is time to
2198 free_strmap_strings(&collisions
);
2199 strmap_clear(&collisions
, 1);
2203 static int detect_and_process_renames(struct merge_options
*opt
,
2204 struct tree
*merge_base
,
2208 struct diff_queue_struct combined
;
2209 struct rename_info
*renames
= &opt
->priv
->renames
;
2210 int need_dir_renames
, s
, clean
= 1;
2212 memset(&combined
, 0, sizeof(combined
));
2214 trace2_region_enter("merge", "regular renames", opt
->repo
);
2215 detect_regular_renames(opt
, merge_base
, side1
, MERGE_SIDE1
);
2216 detect_regular_renames(opt
, merge_base
, side2
, MERGE_SIDE2
);
2217 trace2_region_leave("merge", "regular renames", opt
->repo
);
2219 trace2_region_enter("merge", "directory renames", opt
->repo
);
2221 !opt
->priv
->call_depth
&&
2222 (opt
->detect_directory_renames
== MERGE_DIRECTORY_RENAMES_TRUE
||
2223 opt
->detect_directory_renames
== MERGE_DIRECTORY_RENAMES_CONFLICT
);
2225 if (need_dir_renames
) {
2226 get_provisional_directory_renames(opt
, MERGE_SIDE1
, &clean
);
2227 get_provisional_directory_renames(opt
, MERGE_SIDE2
, &clean
);
2228 handle_directory_level_conflicts(opt
);
2231 ALLOC_GROW(combined
.queue
,
2232 renames
->pairs
[1].nr
+ renames
->pairs
[2].nr
,
2234 clean
&= collect_renames(opt
, &combined
, MERGE_SIDE1
,
2235 &renames
->dir_renames
[2],
2236 &renames
->dir_renames
[1]);
2237 clean
&= collect_renames(opt
, &combined
, MERGE_SIDE2
,
2238 &renames
->dir_renames
[1],
2239 &renames
->dir_renames
[2]);
2240 QSORT(combined
.queue
, combined
.nr
, compare_pairs
);
2241 trace2_region_leave("merge", "directory renames", opt
->repo
);
2243 trace2_region_enter("merge", "process renames", opt
->repo
);
2244 clean
&= process_renames(opt
, &combined
);
2245 trace2_region_leave("merge", "process renames", opt
->repo
);
2247 /* Free memory for renames->pairs[] and combined */
2248 for (s
= MERGE_SIDE1
; s
<= MERGE_SIDE2
; s
++) {
2249 free(renames
->pairs
[s
].queue
);
2250 DIFF_QUEUE_CLEAR(&renames
->pairs
[s
]);
2254 for (i
= 0; i
< combined
.nr
; i
++)
2255 diff_free_filepair(combined
.queue
[i
]);
2256 free(combined
.queue
);
2262 /*** Function Grouping: functions related to process_entries() ***/
2264 static int string_list_df_name_compare(const char *one
, const char *two
)
2266 int onelen
= strlen(one
);
2267 int twolen
= strlen(two
);
2269 * Here we only care that entries for D/F conflicts are
2270 * adjacent, in particular with the file of the D/F conflict
2271 * appearing before files below the corresponding directory.
2272 * The order of the rest of the list is irrelevant for us.
2274 * To achieve this, we sort with df_name_compare and provide
2275 * the mode S_IFDIR so that D/F conflicts will sort correctly.
2276 * We use the mode S_IFDIR for everything else for simplicity,
2277 * since in other cases any changes in their order due to
2278 * sorting cause no problems for us.
2280 int cmp
= df_name_compare(one
, onelen
, S_IFDIR
,
2281 two
, twolen
, S_IFDIR
);
2283 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
2284 * that 'foo' comes before 'foo/bar'.
2288 return onelen
- twolen
;
2291 struct directory_versions
{
2293 * versions: list of (basename -> version_info)
2295 * The basenames are in reverse lexicographic order of full pathnames,
2296 * as processed in process_entries(). This puts all entries within
2297 * a directory together, and covers the directory itself after
2298 * everything within it, allowing us to write subtrees before needing
2299 * to record information for the tree itself.
2301 struct string_list versions
;
2304 * offsets: list of (full relative path directories -> integer offsets)
2306 * Since versions contains basenames from files in multiple different
2307 * directories, we need to know which entries in versions correspond
2308 * to which directories. Values of e.g.
2312 * Would mean that entries 0-1 of versions are files in the toplevel
2313 * directory, entries 2-4 are files under src/, and the remaining
2314 * entries starting at index 5 are files under src/moduleA/.
2316 struct string_list offsets
;
2319 * last_directory: directory that previously processed file found in
2321 * last_directory starts NULL, but records the directory in which the
2322 * previous file was found within. As soon as
2323 * directory(current_file) != last_directory
2324 * then we need to start updating accounting in versions & offsets.
2325 * Note that last_directory is always the last path in "offsets" (or
2326 * NULL if "offsets" is empty) so this exists just for quick access.
2328 const char *last_directory
;
2330 /* last_directory_len: cached computation of strlen(last_directory) */
2331 unsigned last_directory_len
;
2334 static int tree_entry_order(const void *a_
, const void *b_
)
2336 const struct string_list_item
*a
= a_
;
2337 const struct string_list_item
*b
= b_
;
2339 const struct merged_info
*ami
= a
->util
;
2340 const struct merged_info
*bmi
= b
->util
;
2341 return base_name_compare(a
->string
, strlen(a
->string
), ami
->result
.mode
,
2342 b
->string
, strlen(b
->string
), bmi
->result
.mode
);
2345 static void write_tree(struct object_id
*result_oid
,
2346 struct string_list
*versions
,
2347 unsigned int offset
,
2350 size_t maxlen
= 0, extra
;
2351 unsigned int nr
= versions
->nr
- offset
;
2352 struct strbuf buf
= STRBUF_INIT
;
2353 struct string_list relevant_entries
= STRING_LIST_INIT_NODUP
;
2357 * We want to sort the last (versions->nr-offset) entries in versions.
2358 * Do so by abusing the string_list API a bit: make another string_list
2359 * that contains just those entries and then sort them.
2361 * We won't use relevant_entries again and will let it just pop off the
2362 * stack, so there won't be allocation worries or anything.
2364 relevant_entries
.items
= versions
->items
+ offset
;
2365 relevant_entries
.nr
= versions
->nr
- offset
;
2366 QSORT(relevant_entries
.items
, relevant_entries
.nr
, tree_entry_order
);
2368 /* Pre-allocate some space in buf */
2369 extra
= hash_size
+ 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
2370 for (i
= 0; i
< nr
; i
++) {
2371 maxlen
+= strlen(versions
->items
[offset
+i
].string
) + extra
;
2373 strbuf_grow(&buf
, maxlen
);
2375 /* Write each entry out to buf */
2376 for (i
= 0; i
< nr
; i
++) {
2377 struct merged_info
*mi
= versions
->items
[offset
+i
].util
;
2378 struct version_info
*ri
= &mi
->result
;
2379 strbuf_addf(&buf
, "%o %s%c",
2381 versions
->items
[offset
+i
].string
, '\0');
2382 strbuf_add(&buf
, ri
->oid
.hash
, hash_size
);
2385 /* Write this object file out, and record in result_oid */
2386 write_object_file(buf
.buf
, buf
.len
, tree_type
, result_oid
);
2387 strbuf_release(&buf
);
2390 static void record_entry_for_tree(struct directory_versions
*dir_metadata
,
2392 struct merged_info
*mi
)
2394 const char *basename
;
2397 /* nothing to record */
2400 basename
= path
+ mi
->basename_offset
;
2401 assert(strchr(basename
, '/') == NULL
);
2402 string_list_append(&dir_metadata
->versions
,
2403 basename
)->util
= &mi
->result
;
2406 static void write_completed_directory(struct merge_options
*opt
,
2407 const char *new_directory_name
,
2408 struct directory_versions
*info
)
2410 const char *prev_dir
;
2411 struct merged_info
*dir_info
= NULL
;
2412 unsigned int offset
;
2415 * Some explanation of info->versions and info->offsets...
2417 * process_entries() iterates over all relevant files AND
2418 * directories in reverse lexicographic order, and calls this
2419 * function. Thus, an example of the paths that process_entries()
2420 * could operate on (along with the directories for those paths
2425 * src/moduleB/umm.c src/moduleB
2426 * src/moduleB/stuff.h src/moduleB
2427 * src/moduleB/baz.c src/moduleB
2429 * src/moduleA/foo.c src/moduleA
2430 * src/moduleA/bar.c src/moduleA
2437 * always contains the unprocessed entries and their
2438 * version_info information. For example, after the first five
2439 * entries above, info->versions would be:
2441 * xtract.c <xtract.c's version_info>
2442 * token.txt <token.txt's version_info>
2443 * umm.c <src/moduleB/umm.c's version_info>
2444 * stuff.h <src/moduleB/stuff.h's version_info>
2445 * baz.c <src/moduleB/baz.c's version_info>
2447 * Once a subdirectory is completed we remove the entries in
2448 * that subdirectory from info->versions, writing it as a tree
2449 * (write_tree()). Thus, as soon as we get to src/moduleB,
2450 * info->versions would be updated to
2452 * xtract.c <xtract.c's version_info>
2453 * token.txt <token.txt's version_info>
2454 * moduleB <src/moduleB's version_info>
2458 * helps us track which entries in info->versions correspond to
2459 * which directories. When we are N directories deep (e.g. 4
2460 * for src/modA/submod/subdir/), we have up to N+1 unprocessed
2461 * directories (+1 because of toplevel dir). Corresponding to
2462 * the info->versions example above, after processing five entries
2463 * info->offsets will be:
2468 * which is used to know that xtract.c & token.txt are from the
2469 * toplevel dirctory, while umm.c & stuff.h & baz.c are from the
2470 * src/moduleB directory. Again, following the example above,
2471 * once we need to process src/moduleB, then info->offsets is
2477 * which says that moduleB (and only moduleB so far) is in the
2480 * One unique thing to note about info->offsets here is that
2481 * "src" was not added to info->offsets until there was a path
2482 * (a file OR directory) immediately below src/ that got
2485 * Since process_entry() just appends new entries to info->versions,
2486 * write_completed_directory() only needs to do work if the next path
2487 * is in a directory that is different than the last directory found
2492 * If we are working with the same directory as the last entry, there
2493 * is no work to do. (See comments above the directory_name member of
2494 * struct merged_info for why we can use pointer comparison instead of
2497 if (new_directory_name
== info
->last_directory
)
2501 * If we are just starting (last_directory is NULL), or last_directory
2502 * is a prefix of the current directory, then we can just update
2503 * info->offsets to record the offset where we started this directory
2504 * and update last_directory to have quick access to it.
2506 if (info
->last_directory
== NULL
||
2507 !strncmp(new_directory_name
, info
->last_directory
,
2508 info
->last_directory_len
)) {
2509 uintptr_t offset
= info
->versions
.nr
;
2511 info
->last_directory
= new_directory_name
;
2512 info
->last_directory_len
= strlen(info
->last_directory
);
2514 * Record the offset into info->versions where we will
2515 * start recording basenames of paths found within
2516 * new_directory_name.
2518 string_list_append(&info
->offsets
,
2519 info
->last_directory
)->util
= (void*)offset
;
2524 * The next entry that will be processed will be within
2525 * new_directory_name. Since at this point we know that
2526 * new_directory_name is within a different directory than
2527 * info->last_directory, we have all entries for info->last_directory
2528 * in info->versions and we need to create a tree object for them.
2530 dir_info
= strmap_get(&opt
->priv
->paths
, info
->last_directory
);
2532 offset
= (uintptr_t)info
->offsets
.items
[info
->offsets
.nr
-1].util
;
2533 if (offset
== info
->versions
.nr
) {
2535 * Actually, we don't need to create a tree object in this
2536 * case. Whenever all files within a directory disappear
2537 * during the merge (e.g. unmodified on one side and
2538 * deleted on the other, or files were renamed elsewhere),
2539 * then we get here and the directory itself needs to be
2540 * omitted from its parent tree as well.
2542 dir_info
->is_null
= 1;
2545 * Write out the tree to the git object directory, and also
2546 * record the mode and oid in dir_info->result.
2548 dir_info
->is_null
= 0;
2549 dir_info
->result
.mode
= S_IFDIR
;
2550 write_tree(&dir_info
->result
.oid
, &info
->versions
, offset
,
2551 opt
->repo
->hash_algo
->rawsz
);
2555 * We've now used several entries from info->versions and one entry
2556 * from info->offsets, so we get rid of those values.
2559 info
->versions
.nr
= offset
;
2562 * Now we've taken care of the completed directory, but we need to
2563 * prepare things since future entries will be in
2564 * new_directory_name. (In particular, process_entry() will be
2565 * appending new entries to info->versions.) So, we need to make
2566 * sure new_directory_name is the last entry in info->offsets.
2568 prev_dir
= info
->offsets
.nr
== 0 ? NULL
:
2569 info
->offsets
.items
[info
->offsets
.nr
-1].string
;
2570 if (new_directory_name
!= prev_dir
) {
2571 uintptr_t c
= info
->versions
.nr
;
2572 string_list_append(&info
->offsets
,
2573 new_directory_name
)->util
= (void*)c
;
2576 /* And, of course, we need to update last_directory to match. */
2577 info
->last_directory
= new_directory_name
;
2578 info
->last_directory_len
= strlen(info
->last_directory
);
2581 /* Per entry merge function */
2582 static void process_entry(struct merge_options
*opt
,
2584 struct conflict_info
*ci
,
2585 struct directory_versions
*dir_metadata
)
2587 int df_file_index
= 0;
2590 assert(ci
->filemask
>= 0 && ci
->filemask
<= 7);
2591 /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
2592 assert(ci
->match_mask
== 0 || ci
->match_mask
== 3 ||
2593 ci
->match_mask
== 5 || ci
->match_mask
== 6);
2596 record_entry_for_tree(dir_metadata
, path
, &ci
->merged
);
2597 if (ci
->filemask
== 0)
2598 /* nothing else to handle */
2600 assert(ci
->df_conflict
);
2603 if (ci
->df_conflict
&& ci
->merged
.result
.mode
== 0) {
2607 * directory no longer in the way, but we do have a file we
2608 * need to place here so we need to clean away the "directory
2609 * merges to nothing" result.
2611 ci
->df_conflict
= 0;
2612 assert(ci
->filemask
!= 0);
2613 ci
->merged
.clean
= 0;
2614 ci
->merged
.is_null
= 0;
2615 /* and we want to zero out any directory-related entries */
2616 ci
->match_mask
= (ci
->match_mask
& ~ci
->dirmask
);
2618 for (i
= MERGE_BASE
; i
<= MERGE_SIDE2
; i
++) {
2619 if (ci
->filemask
& (1 << i
))
2621 ci
->stages
[i
].mode
= 0;
2622 oidcpy(&ci
->stages
[i
].oid
, &null_oid
);
2624 } else if (ci
->df_conflict
&& ci
->merged
.result
.mode
!= 0) {
2626 * This started out as a D/F conflict, and the entries in
2627 * the competing directory were not removed by the merge as
2628 * evidenced by write_completed_directory() writing a value
2629 * to ci->merged.result.mode.
2631 struct conflict_info
*new_ci
;
2633 const char *old_path
= path
;
2636 assert(ci
->merged
.result
.mode
== S_IFDIR
);
2639 * If filemask is 1, we can just ignore the file as having
2640 * been deleted on both sides. We do not want to overwrite
2641 * ci->merged.result, since it stores the tree for all the
2644 if (ci
->filemask
== 1) {
2650 * This file still exists on at least one side, and we want
2651 * the directory to remain here, so we need to move this
2652 * path to some new location.
2654 new_ci
= xcalloc(1, sizeof(*new_ci
));
2655 /* We don't really want new_ci->merged.result copied, but it'll
2656 * be overwritten below so it doesn't matter. We also don't
2657 * want any directory mode/oid values copied, but we'll zero
2658 * those out immediately. We do want the rest of ci copied.
2660 memcpy(new_ci
, ci
, sizeof(*ci
));
2661 new_ci
->match_mask
= (new_ci
->match_mask
& ~new_ci
->dirmask
);
2662 new_ci
->dirmask
= 0;
2663 for (i
= MERGE_BASE
; i
<= MERGE_SIDE2
; i
++) {
2664 if (new_ci
->filemask
& (1 << i
))
2666 /* zero out any entries related to directories */
2667 new_ci
->stages
[i
].mode
= 0;
2668 oidcpy(&new_ci
->stages
[i
].oid
, &null_oid
);
2672 * Find out which side this file came from; note that we
2673 * cannot just use ci->filemask, because renames could cause
2674 * the filemask to go back to 7. So we use dirmask, then
2675 * pick the opposite side's index.
2677 df_file_index
= (ci
->dirmask
& (1 << 1)) ? 2 : 1;
2678 branch
= (df_file_index
== 1) ? opt
->branch1
: opt
->branch2
;
2679 path
= unique_path(&opt
->priv
->paths
, path
, branch
);
2680 strmap_put(&opt
->priv
->paths
, path
, new_ci
);
2682 path_msg(opt
, path
, 0,
2683 _("CONFLICT (file/directory): directory in the way "
2684 "of %s from %s; moving it to %s instead."),
2685 old_path
, branch
, path
);
2688 * Zero out the filemask for the old ci. At this point, ci
2689 * was just an entry for a directory, so we don't need to
2690 * do anything more with it.
2695 * Now note that we're working on the new entry (path was
2702 * NOTE: Below there is a long switch-like if-elseif-elseif... block
2703 * which the code goes through even for the df_conflict cases
2706 if (ci
->match_mask
) {
2707 ci
->merged
.clean
= 1;
2708 if (ci
->match_mask
== 6) {
2709 /* stages[1] == stages[2] */
2710 ci
->merged
.result
.mode
= ci
->stages
[1].mode
;
2711 oidcpy(&ci
->merged
.result
.oid
, &ci
->stages
[1].oid
);
2713 /* determine the mask of the side that didn't match */
2714 unsigned int othermask
= 7 & ~ci
->match_mask
;
2715 int side
= (othermask
== 4) ? 2 : 1;
2717 ci
->merged
.result
.mode
= ci
->stages
[side
].mode
;
2718 ci
->merged
.is_null
= !ci
->merged
.result
.mode
;
2719 oidcpy(&ci
->merged
.result
.oid
, &ci
->stages
[side
].oid
);
2721 assert(othermask
== 2 || othermask
== 4);
2722 assert(ci
->merged
.is_null
==
2723 (ci
->filemask
== ci
->match_mask
));
2725 } else if (ci
->filemask
>= 6 &&
2726 (S_IFMT
& ci
->stages
[1].mode
) !=
2727 (S_IFMT
& ci
->stages
[2].mode
)) {
2728 /* Two different items from (file/submodule/symlink) */
2729 if (opt
->priv
->call_depth
) {
2730 /* Just use the version from the merge base */
2731 ci
->merged
.clean
= 0;
2732 oidcpy(&ci
->merged
.result
.oid
, &ci
->stages
[0].oid
);
2733 ci
->merged
.result
.mode
= ci
->stages
[0].mode
;
2734 ci
->merged
.is_null
= (ci
->merged
.result
.mode
== 0);
2736 /* Handle by renaming one or both to separate paths. */
2737 unsigned o_mode
= ci
->stages
[0].mode
;
2738 unsigned a_mode
= ci
->stages
[1].mode
;
2739 unsigned b_mode
= ci
->stages
[2].mode
;
2740 struct conflict_info
*new_ci
;
2741 const char *a_path
= NULL
, *b_path
= NULL
;
2742 int rename_a
= 0, rename_b
= 0;
2744 new_ci
= xmalloc(sizeof(*new_ci
));
2746 if (S_ISREG(a_mode
))
2748 else if (S_ISREG(b_mode
))
2755 path_msg(opt
, path
, 0,
2756 _("CONFLICT (distinct types): %s had different "
2757 "types on each side; renamed %s of them so "
2758 "each can be recorded somewhere."),
2760 (rename_a
&& rename_b
) ? _("both") : _("one"));
2762 ci
->merged
.clean
= 0;
2763 memcpy(new_ci
, ci
, sizeof(*new_ci
));
2765 /* Put b into new_ci, removing a from stages */
2766 new_ci
->merged
.result
.mode
= ci
->stages
[2].mode
;
2767 oidcpy(&new_ci
->merged
.result
.oid
, &ci
->stages
[2].oid
);
2768 new_ci
->stages
[1].mode
= 0;
2769 oidcpy(&new_ci
->stages
[1].oid
, &null_oid
);
2770 new_ci
->filemask
= 5;
2771 if ((S_IFMT
& b_mode
) != (S_IFMT
& o_mode
)) {
2772 new_ci
->stages
[0].mode
= 0;
2773 oidcpy(&new_ci
->stages
[0].oid
, &null_oid
);
2774 new_ci
->filemask
= 4;
2777 /* Leave only a in ci, fixing stages. */
2778 ci
->merged
.result
.mode
= ci
->stages
[1].mode
;
2779 oidcpy(&ci
->merged
.result
.oid
, &ci
->stages
[1].oid
);
2780 ci
->stages
[2].mode
= 0;
2781 oidcpy(&ci
->stages
[2].oid
, &null_oid
);
2783 if ((S_IFMT
& a_mode
) != (S_IFMT
& o_mode
)) {
2784 ci
->stages
[0].mode
= 0;
2785 oidcpy(&ci
->stages
[0].oid
, &null_oid
);
2789 /* Insert entries into opt->priv_paths */
2790 assert(rename_a
|| rename_b
);
2792 a_path
= unique_path(&opt
->priv
->paths
,
2793 path
, opt
->branch1
);
2794 strmap_put(&opt
->priv
->paths
, a_path
, ci
);
2798 b_path
= unique_path(&opt
->priv
->paths
,
2799 path
, opt
->branch2
);
2802 strmap_put(&opt
->priv
->paths
, b_path
, new_ci
);
2804 if (rename_a
&& rename_b
) {
2805 strmap_remove(&opt
->priv
->paths
, path
, 0);
2807 * We removed path from opt->priv->paths. path
2808 * will also eventually need to be freed, but
2809 * it may still be used by e.g. ci->pathnames.
2810 * So, store it in another string-list for now.
2812 string_list_append(&opt
->priv
->paths_to_free
,
2817 * Do special handling for b_path since process_entry()
2818 * won't be called on it specially.
2820 strmap_put(&opt
->priv
->conflicted
, b_path
, new_ci
);
2821 record_entry_for_tree(dir_metadata
, b_path
,
2825 * Remaining code for processing this entry should
2826 * think in terms of processing a_path.
2831 } else if (ci
->filemask
>= 6) {
2832 /* Need a two-way or three-way content merge */
2833 struct version_info merged_file
;
2834 unsigned clean_merge
;
2835 struct version_info
*o
= &ci
->stages
[0];
2836 struct version_info
*a
= &ci
->stages
[1];
2837 struct version_info
*b
= &ci
->stages
[2];
2839 clean_merge
= handle_content_merge(opt
, path
, o
, a
, b
,
2841 opt
->priv
->call_depth
* 2,
2843 ci
->merged
.clean
= clean_merge
&&
2844 !ci
->df_conflict
&& !ci
->path_conflict
;
2845 ci
->merged
.result
.mode
= merged_file
.mode
;
2846 ci
->merged
.is_null
= (merged_file
.mode
== 0);
2847 oidcpy(&ci
->merged
.result
.oid
, &merged_file
.oid
);
2848 if (clean_merge
&& ci
->df_conflict
) {
2849 assert(df_file_index
== 1 || df_file_index
== 2);
2850 ci
->filemask
= 1 << df_file_index
;
2851 ci
->stages
[df_file_index
].mode
= merged_file
.mode
;
2852 oidcpy(&ci
->stages
[df_file_index
].oid
, &merged_file
.oid
);
2855 const char *reason
= _("content");
2856 if (ci
->filemask
== 6)
2857 reason
= _("add/add");
2858 if (S_ISGITLINK(merged_file
.mode
))
2859 reason
= _("submodule");
2860 path_msg(opt
, path
, 0,
2861 _("CONFLICT (%s): Merge conflict in %s"),
2864 } else if (ci
->filemask
== 3 || ci
->filemask
== 5) {
2866 const char *modify_branch
, *delete_branch
;
2867 int side
= (ci
->filemask
== 5) ? 2 : 1;
2868 int index
= opt
->priv
->call_depth
? 0 : side
;
2870 ci
->merged
.result
.mode
= ci
->stages
[index
].mode
;
2871 oidcpy(&ci
->merged
.result
.oid
, &ci
->stages
[index
].oid
);
2872 ci
->merged
.clean
= 0;
2874 modify_branch
= (side
== 1) ? opt
->branch1
: opt
->branch2
;
2875 delete_branch
= (side
== 1) ? opt
->branch2
: opt
->branch1
;
2877 if (ci
->path_conflict
&&
2878 oideq(&ci
->stages
[0].oid
, &ci
->stages
[side
].oid
)) {
2880 * This came from a rename/delete; no action to take,
2881 * but avoid printing "modify/delete" conflict notice
2882 * since the contents were not modified.
2885 path_msg(opt
, path
, 0,
2886 _("CONFLICT (modify/delete): %s deleted in %s "
2887 "and modified in %s. Version %s of %s left "
2889 path
, delete_branch
, modify_branch
,
2890 modify_branch
, path
);
2892 } else if (ci
->filemask
== 2 || ci
->filemask
== 4) {
2893 /* Added on one side */
2894 int side
= (ci
->filemask
== 4) ? 2 : 1;
2895 ci
->merged
.result
.mode
= ci
->stages
[side
].mode
;
2896 oidcpy(&ci
->merged
.result
.oid
, &ci
->stages
[side
].oid
);
2897 ci
->merged
.clean
= !ci
->df_conflict
&& !ci
->path_conflict
;
2898 } else if (ci
->filemask
== 1) {
2899 /* Deleted on both sides */
2900 ci
->merged
.is_null
= 1;
2901 ci
->merged
.result
.mode
= 0;
2902 oidcpy(&ci
->merged
.result
.oid
, &null_oid
);
2903 ci
->merged
.clean
= !ci
->path_conflict
;
2907 * If still conflicted, record it separately. This allows us to later
2908 * iterate over just conflicted entries when updating the index instead
2909 * of iterating over all entries.
2911 if (!ci
->merged
.clean
)
2912 strmap_put(&opt
->priv
->conflicted
, path
, ci
);
2913 record_entry_for_tree(dir_metadata
, path
, &ci
->merged
);
2916 static void process_entries(struct merge_options
*opt
,
2917 struct object_id
*result_oid
)
2919 struct hashmap_iter iter
;
2920 struct strmap_entry
*e
;
2921 struct string_list plist
= STRING_LIST_INIT_NODUP
;
2922 struct string_list_item
*entry
;
2923 struct directory_versions dir_metadata
= { STRING_LIST_INIT_NODUP
,
2924 STRING_LIST_INIT_NODUP
,
2927 trace2_region_enter("merge", "process_entries setup", opt
->repo
);
2928 if (strmap_empty(&opt
->priv
->paths
)) {
2929 oidcpy(result_oid
, opt
->repo
->hash_algo
->empty_tree
);
2933 /* Hack to pre-allocate plist to the desired size */
2934 trace2_region_enter("merge", "plist grow", opt
->repo
);
2935 ALLOC_GROW(plist
.items
, strmap_get_size(&opt
->priv
->paths
), plist
.alloc
);
2936 trace2_region_leave("merge", "plist grow", opt
->repo
);
2938 /* Put every entry from paths into plist, then sort */
2939 trace2_region_enter("merge", "plist copy", opt
->repo
);
2940 strmap_for_each_entry(&opt
->priv
->paths
, &iter
, e
) {
2941 string_list_append(&plist
, e
->key
)->util
= e
->value
;
2943 trace2_region_leave("merge", "plist copy", opt
->repo
);
2945 trace2_region_enter("merge", "plist special sort", opt
->repo
);
2946 plist
.cmp
= string_list_df_name_compare
;
2947 string_list_sort(&plist
);
2948 trace2_region_leave("merge", "plist special sort", opt
->repo
);
2950 trace2_region_leave("merge", "process_entries setup", opt
->repo
);
2953 * Iterate over the items in reverse order, so we can handle paths
2954 * below a directory before needing to handle the directory itself.
2956 * This allows us to write subtrees before we need to write trees,
2957 * and it also enables sane handling of directory/file conflicts
2958 * (because it allows us to know whether the directory is still in
2959 * the way when it is time to process the file at the same path).
2961 trace2_region_enter("merge", "processing", opt
->repo
);
2962 for (entry
= &plist
.items
[plist
.nr
-1]; entry
>= plist
.items
; --entry
) {
2963 char *path
= entry
->string
;
2965 * NOTE: mi may actually be a pointer to a conflict_info, but
2966 * we have to check mi->clean first to see if it's safe to
2967 * reassign to such a pointer type.
2969 struct merged_info
*mi
= entry
->util
;
2971 write_completed_directory(opt
, mi
->directory_name
,
2974 record_entry_for_tree(&dir_metadata
, path
, mi
);
2976 struct conflict_info
*ci
= (struct conflict_info
*)mi
;
2977 process_entry(opt
, path
, ci
, &dir_metadata
);
2980 trace2_region_leave("merge", "processing", opt
->repo
);
2982 trace2_region_enter("merge", "process_entries cleanup", opt
->repo
);
2983 if (dir_metadata
.offsets
.nr
!= 1 ||
2984 (uintptr_t)dir_metadata
.offsets
.items
[0].util
!= 0) {
2985 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
2986 dir_metadata
.offsets
.nr
);
2987 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
2988 (unsigned)(uintptr_t)dir_metadata
.offsets
.items
[0].util
);
2990 BUG("dir_metadata accounting completely off; shouldn't happen");
2992 write_tree(result_oid
, &dir_metadata
.versions
, 0,
2993 opt
->repo
->hash_algo
->rawsz
);
2994 string_list_clear(&plist
, 0);
2995 string_list_clear(&dir_metadata
.versions
, 0);
2996 string_list_clear(&dir_metadata
.offsets
, 0);
2997 trace2_region_leave("merge", "process_entries cleanup", opt
->repo
);
3000 /*** Function Grouping: functions related to merge_switch_to_result() ***/
3002 static int checkout(struct merge_options
*opt
,
3006 /* Switch the index/working copy from old to new */
3008 struct tree_desc trees
[2];
3009 struct unpack_trees_options unpack_opts
;
3011 memset(&unpack_opts
, 0, sizeof(unpack_opts
));
3012 unpack_opts
.head_idx
= -1;
3013 unpack_opts
.src_index
= opt
->repo
->index
;
3014 unpack_opts
.dst_index
= opt
->repo
->index
;
3016 setup_unpack_trees_porcelain(&unpack_opts
, "merge");
3019 * NOTE: if this were just "git checkout" code, we would probably
3020 * read or refresh the cache and check for a conflicted index, but
3021 * builtin/merge.c or sequencer.c really needs to read the index
3022 * and check for conflicted entries before starting merging for a
3023 * good user experience (no sense waiting for merges/rebases before
3024 * erroring out), so there's no reason to duplicate that work here.
3027 /* 2-way merge to the new branch */
3028 unpack_opts
.update
= 1;
3029 unpack_opts
.merge
= 1;
3030 unpack_opts
.quiet
= 0; /* FIXME: sequencer might want quiet? */
3031 unpack_opts
.verbose_update
= (opt
->verbosity
> 2);
3032 unpack_opts
.fn
= twoway_merge
;
3033 if (1/* FIXME: opts->overwrite_ignore*/) {
3034 unpack_opts
.dir
= xcalloc(1, sizeof(*unpack_opts
.dir
));
3035 unpack_opts
.dir
->flags
|= DIR_SHOW_IGNORED
;
3036 setup_standard_excludes(unpack_opts
.dir
);
3039 init_tree_desc(&trees
[0], prev
->buffer
, prev
->size
);
3041 init_tree_desc(&trees
[1], next
->buffer
, next
->size
);
3043 ret
= unpack_trees(2, trees
, &unpack_opts
);
3044 clear_unpack_trees_porcelain(&unpack_opts
);
3045 dir_clear(unpack_opts
.dir
);
3046 FREE_AND_NULL(unpack_opts
.dir
);
3050 static int record_conflicted_index_entries(struct merge_options
*opt
,
3051 struct index_state
*index
,
3052 struct strmap
*paths
,
3053 struct strmap
*conflicted
)
3055 struct hashmap_iter iter
;
3056 struct strmap_entry
*e
;
3058 int original_cache_nr
;
3060 if (strmap_empty(conflicted
))
3063 original_cache_nr
= index
->cache_nr
;
3065 /* Put every entry from paths into plist, then sort */
3066 strmap_for_each_entry(conflicted
, &iter
, e
) {
3067 const char *path
= e
->key
;
3068 struct conflict_info
*ci
= e
->value
;
3070 struct cache_entry
*ce
;
3076 * The index will already have a stage=0 entry for this path,
3077 * because we created an as-merged-as-possible version of the
3078 * file and checkout() moved the working copy and index over
3081 * However, previous iterations through this loop will have
3082 * added unstaged entries to the end of the cache which
3083 * ignore the standard alphabetical ordering of cache
3084 * entries and break invariants needed for index_name_pos()
3085 * to work. However, we know the entry we want is before
3086 * those appended cache entries, so do a temporary swap on
3087 * cache_nr to only look through entries of interest.
3089 SWAP(index
->cache_nr
, original_cache_nr
);
3090 pos
= index_name_pos(index
, path
, strlen(path
));
3091 SWAP(index
->cache_nr
, original_cache_nr
);
3093 if (ci
->filemask
!= 1)
3094 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path
);
3095 cache_tree_invalidate_path(index
, path
);
3097 ce
= index
->cache
[pos
];
3100 * Clean paths with CE_SKIP_WORKTREE set will not be
3101 * written to the working tree by the unpack_trees()
3102 * call in checkout(). Our conflicted entries would
3103 * have appeared clean to that code since we ignored
3104 * the higher order stages. Thus, we need override
3105 * the CE_SKIP_WORKTREE bit and manually write those
3106 * files to the working disk here.
3108 * TODO: Implement this CE_SKIP_WORKTREE fixup.
3112 * Mark this cache entry for removal and instead add
3113 * new stage>0 entries corresponding to the
3114 * conflicts. If there are many conflicted entries, we
3115 * want to avoid memmove'ing O(NM) entries by
3116 * inserting the new entries one at a time. So,
3117 * instead, we just add the new cache entries to the
3118 * end (ignoring normal index requirements on sort
3119 * order) and sort the index once we're all done.
3121 ce
->ce_flags
|= CE_REMOVE
;
3124 for (i
= MERGE_BASE
; i
<= MERGE_SIDE2
; i
++) {
3125 struct version_info
*vi
;
3126 if (!(ci
->filemask
& (1ul << i
)))
3128 vi
= &ci
->stages
[i
];
3129 ce
= make_cache_entry(index
, vi
->mode
, &vi
->oid
,
3131 add_index_entry(index
, ce
, ADD_CACHE_JUST_APPEND
);
3136 * Remove the unused cache entries (and invalidate the relevant
3137 * cache-trees), then sort the index entries to get the conflicted
3138 * entries we added to the end into their right locations.
3140 remove_marked_cache_entries(index
, 1);
3141 QSORT(index
->cache
, index
->cache_nr
, cmp_cache_name_compare
);
3146 void merge_switch_to_result(struct merge_options
*opt
,
3148 struct merge_result
*result
,
3149 int update_worktree_and_index
,
3150 int display_update_msgs
)
3152 assert(opt
->priv
== NULL
);
3153 if (result
->clean
>= 0 && update_worktree_and_index
) {
3154 struct merge_options_internal
*opti
= result
->priv
;
3156 trace2_region_enter("merge", "checkout", opt
->repo
);
3157 if (checkout(opt
, head
, result
->tree
)) {
3158 /* failure to function */
3162 trace2_region_leave("merge", "checkout", opt
->repo
);
3164 trace2_region_enter("merge", "record_conflicted", opt
->repo
);
3165 if (record_conflicted_index_entries(opt
, opt
->repo
->index
,
3167 &opti
->conflicted
)) {
3168 /* failure to function */
3172 trace2_region_leave("merge", "record_conflicted", opt
->repo
);
3175 if (display_update_msgs
) {
3176 struct merge_options_internal
*opti
= result
->priv
;
3177 struct hashmap_iter iter
;
3178 struct strmap_entry
*e
;
3179 struct string_list olist
= STRING_LIST_INIT_NODUP
;
3182 trace2_region_enter("merge", "display messages", opt
->repo
);
3184 /* Hack to pre-allocate olist to the desired size */
3185 ALLOC_GROW(olist
.items
, strmap_get_size(&opti
->output
),
3188 /* Put every entry from output into olist, then sort */
3189 strmap_for_each_entry(&opti
->output
, &iter
, e
) {
3190 string_list_append(&olist
, e
->key
)->util
= e
->value
;
3192 string_list_sort(&olist
);
3194 /* Iterate over the items, printing them */
3195 for (i
= 0; i
< olist
.nr
; ++i
) {
3196 struct strbuf
*sb
= olist
.items
[i
].util
;
3198 printf("%s", sb
->buf
);
3200 string_list_clear(&olist
, 0);
3202 /* Also include needed rename limit adjustment now */
3203 diff_warn_rename_limit("merge.renamelimit",
3204 opti
->renames
.needed_limit
, 0);
3206 trace2_region_leave("merge", "display messages", opt
->repo
);
3209 merge_finalize(opt
, result
);
3212 void merge_finalize(struct merge_options
*opt
,
3213 struct merge_result
*result
)
3215 struct merge_options_internal
*opti
= result
->priv
;
3217 assert(opt
->priv
== NULL
);
3219 clear_or_reinit_internal_opts(opti
, 0);
3220 FREE_AND_NULL(opti
);
3223 /*** Function Grouping: helper functions for merge_incore_*() ***/
3225 static inline void set_commit_tree(struct commit
*c
, struct tree
*t
)
3230 static struct commit
*make_virtual_commit(struct repository
*repo
,
3232 const char *comment
)
3234 struct commit
*commit
= alloc_commit_node(repo
);
3236 set_merge_remote_desc(commit
, comment
, (struct object
*)commit
);
3237 set_commit_tree(commit
, tree
);
3238 commit
->object
.parsed
= 1;
3242 static void merge_start(struct merge_options
*opt
, struct merge_result
*result
)
3244 struct rename_info
*renames
;
3247 /* Sanity checks on opt */
3248 trace2_region_enter("merge", "sanity checks", opt
->repo
);
3251 assert(opt
->branch1
&& opt
->branch2
);
3253 assert(opt
->detect_directory_renames
>= MERGE_DIRECTORY_RENAMES_NONE
&&
3254 opt
->detect_directory_renames
<= MERGE_DIRECTORY_RENAMES_TRUE
);
3255 assert(opt
->rename_limit
>= -1);
3256 assert(opt
->rename_score
>= 0 && opt
->rename_score
<= MAX_SCORE
);
3257 assert(opt
->show_rename_progress
>= 0 && opt
->show_rename_progress
<= 1);
3259 assert(opt
->xdl_opts
>= 0);
3260 assert(opt
->recursive_variant
>= MERGE_VARIANT_NORMAL
&&
3261 opt
->recursive_variant
<= MERGE_VARIANT_THEIRS
);
3264 * detect_renames, verbosity, buffer_output, and obuf are ignored
3265 * fields that were used by "recursive" rather than "ort" -- but
3266 * sanity check them anyway.
3268 assert(opt
->detect_renames
>= -1 &&
3269 opt
->detect_renames
<= DIFF_DETECT_COPY
);
3270 assert(opt
->verbosity
>= 0 && opt
->verbosity
<= 5);
3271 assert(opt
->buffer_output
<= 2);
3272 assert(opt
->obuf
.len
== 0);
3274 assert(opt
->priv
== NULL
);
3276 opt
->priv
= result
->priv
;
3277 result
->priv
= NULL
;
3279 * opt->priv non-NULL means we had results from a previous
3280 * run; do a few sanity checks that user didn't mess with
3281 * it in an obvious fashion.
3283 assert(opt
->priv
->call_depth
== 0);
3284 assert(!opt
->priv
->toplevel_dir
||
3285 0 == strlen(opt
->priv
->toplevel_dir
));
3287 trace2_region_leave("merge", "sanity checks", opt
->repo
);
3289 /* Default to histogram diff. Actually, just hardcode it...for now. */
3290 opt
->xdl_opts
= DIFF_WITH_ALG(opt
, HISTOGRAM_DIFF
);
3292 /* Initialization of opt->priv, our internal merge data */
3293 trace2_region_enter("merge", "allocate/init", opt
->repo
);
3295 clear_or_reinit_internal_opts(opt
->priv
, 1);
3296 trace2_region_leave("merge", "allocate/init", opt
->repo
);
3299 opt
->priv
= xcalloc(1, sizeof(*opt
->priv
));
3301 /* Initialization of various renames fields */
3302 renames
= &opt
->priv
->renames
;
3303 for (i
= MERGE_SIDE1
; i
<= MERGE_SIDE2
; i
++) {
3304 strset_init_with_options(&renames
->dirs_removed
[i
],
3306 strmap_init_with_options(&renames
->dir_rename_count
[i
],
3308 strmap_init_with_options(&renames
->dir_renames
[i
],
3313 * Although we initialize opt->priv->paths with strdup_strings=0,
3314 * that's just to avoid making yet another copy of an allocated
3315 * string. Putting the entry into paths means we are taking
3316 * ownership, so we will later free it. paths_to_free is similar.
3318 * In contrast, conflicted just has a subset of keys from paths, so
3319 * we don't want to free those (it'd be a duplicate free).
3321 strmap_init_with_options(&opt
->priv
->paths
, NULL
, 0);
3322 strmap_init_with_options(&opt
->priv
->conflicted
, NULL
, 0);
3323 string_list_init(&opt
->priv
->paths_to_free
, 0);
3326 * keys & strbufs in output will sometimes need to outlive "paths",
3327 * so it will have a copy of relevant keys. It's probably a small
3328 * subset of the overall paths that have special output.
3330 strmap_init(&opt
->priv
->output
);
3332 trace2_region_leave("merge", "allocate/init", opt
->repo
);
3335 /*** Function Grouping: merge_incore_*() and their internal variants ***/
3338 * Originally from merge_trees_internal(); heavily adapted, though.
3340 static void merge_ort_nonrecursive_internal(struct merge_options
*opt
,
3341 struct tree
*merge_base
,
3344 struct merge_result
*result
)
3346 struct object_id working_tree_oid
;
3348 trace2_region_enter("merge", "collect_merge_info", opt
->repo
);
3349 if (collect_merge_info(opt
, merge_base
, side1
, side2
) != 0) {
3351 * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
3352 * base, and 2-3) the trees for the two trees we're merging.
3354 err(opt
, _("collecting merge info failed for trees %s, %s, %s"),
3355 oid_to_hex(&merge_base
->object
.oid
),
3356 oid_to_hex(&side1
->object
.oid
),
3357 oid_to_hex(&side2
->object
.oid
));
3361 trace2_region_leave("merge", "collect_merge_info", opt
->repo
);
3363 trace2_region_enter("merge", "renames", opt
->repo
);
3364 result
->clean
= detect_and_process_renames(opt
, merge_base
,
3366 trace2_region_leave("merge", "renames", opt
->repo
);
3368 trace2_region_enter("merge", "process_entries", opt
->repo
);
3369 process_entries(opt
, &working_tree_oid
);
3370 trace2_region_leave("merge", "process_entries", opt
->repo
);
3372 /* Set return values */
3373 result
->tree
= parse_tree_indirect(&working_tree_oid
);
3374 /* existence of conflicted entries implies unclean */
3375 result
->clean
&= strmap_empty(&opt
->priv
->conflicted
);
3376 if (!opt
->priv
->call_depth
) {
3377 result
->priv
= opt
->priv
;
3383 * Originally from merge_recursive_internal(); somewhat adapted, though.
3385 static void merge_ort_internal(struct merge_options
*opt
,
3386 struct commit_list
*merge_bases
,
3389 struct merge_result
*result
)
3391 struct commit_list
*iter
;
3392 struct commit
*merged_merge_bases
;
3393 const char *ancestor_name
;
3394 struct strbuf merge_base_abbrev
= STRBUF_INIT
;
3397 merge_bases
= get_merge_bases(h1
, h2
);
3398 /* See merge-ort.h:merge_incore_recursive() declaration NOTE */
3399 merge_bases
= reverse_commit_list(merge_bases
);
3402 merged_merge_bases
= pop_commit(&merge_bases
);
3403 if (merged_merge_bases
== NULL
) {
3404 /* if there is no common ancestor, use an empty tree */
3407 tree
= lookup_tree(opt
->repo
, opt
->repo
->hash_algo
->empty_tree
);
3408 merged_merge_bases
= make_virtual_commit(opt
->repo
, tree
,
3410 ancestor_name
= "empty tree";
3411 } else if (merge_bases
) {
3412 ancestor_name
= "merged common ancestors";
3414 strbuf_add_unique_abbrev(&merge_base_abbrev
,
3415 &merged_merge_bases
->object
.oid
,
3417 ancestor_name
= merge_base_abbrev
.buf
;
3420 for (iter
= merge_bases
; iter
; iter
= iter
->next
) {
3421 const char *saved_b1
, *saved_b2
;
3422 struct commit
*prev
= merged_merge_bases
;
3424 opt
->priv
->call_depth
++;
3426 * When the merge fails, the result contains files
3427 * with conflict markers. The cleanness flag is
3428 * ignored (unless indicating an error), it was never
3429 * actually used, as result of merge_trees has always
3430 * overwritten it: the committed "conflicts" were
3433 saved_b1
= opt
->branch1
;
3434 saved_b2
= opt
->branch2
;
3435 opt
->branch1
= "Temporary merge branch 1";
3436 opt
->branch2
= "Temporary merge branch 2";
3437 merge_ort_internal(opt
, NULL
, prev
, iter
->item
, result
);
3438 if (result
->clean
< 0)
3440 opt
->branch1
= saved_b1
;
3441 opt
->branch2
= saved_b2
;
3442 opt
->priv
->call_depth
--;
3444 merged_merge_bases
= make_virtual_commit(opt
->repo
,
3447 commit_list_insert(prev
, &merged_merge_bases
->parents
);
3448 commit_list_insert(iter
->item
,
3449 &merged_merge_bases
->parents
->next
);
3451 clear_or_reinit_internal_opts(opt
->priv
, 1);
3454 opt
->ancestor
= ancestor_name
;
3455 merge_ort_nonrecursive_internal(opt
,
3456 repo_get_commit_tree(opt
->repo
,
3457 merged_merge_bases
),
3458 repo_get_commit_tree(opt
->repo
, h1
),
3459 repo_get_commit_tree(opt
->repo
, h2
),
3461 strbuf_release(&merge_base_abbrev
);
3462 opt
->ancestor
= NULL
; /* avoid accidental re-use of opt->ancestor */
3465 void merge_incore_nonrecursive(struct merge_options
*opt
,
3466 struct tree
*merge_base
,
3469 struct merge_result
*result
)
3471 trace2_region_enter("merge", "incore_nonrecursive", opt
->repo
);
3473 trace2_region_enter("merge", "merge_start", opt
->repo
);
3474 assert(opt
->ancestor
!= NULL
);
3475 merge_start(opt
, result
);
3476 trace2_region_leave("merge", "merge_start", opt
->repo
);
3478 merge_ort_nonrecursive_internal(opt
, merge_base
, side1
, side2
, result
);
3479 trace2_region_leave("merge", "incore_nonrecursive", opt
->repo
);
3482 void merge_incore_recursive(struct merge_options
*opt
,
3483 struct commit_list
*merge_bases
,
3484 struct commit
*side1
,
3485 struct commit
*side2
,
3486 struct merge_result
*result
)
3488 trace2_region_enter("merge", "incore_recursive", opt
->repo
);
3490 /* We set the ancestor label based on the merge_bases */
3491 assert(opt
->ancestor
== NULL
);
3493 trace2_region_enter("merge", "merge_start", opt
->repo
);
3494 merge_start(opt
, result
);
3495 trace2_region_leave("merge", "merge_start", opt
->repo
);
3497 merge_ort_internal(opt
, merge_bases
, side1
, side2
, result
);
3498 trace2_region_leave("merge", "incore_recursive", opt
->repo
);