]> git.ipfire.org Git - thirdparty/git.git/blame - merge-ort.c
The fifth batch
[thirdparty/git.git] / merge-ort.c
CommitLineData
17e5574b
EN
1/*
2 * "Ostensibly Recursive's Twin" merge strategy, or "ort" for short. Meant
3 * as a drop-in replacement for the "recursive" merge strategy, allowing one
4 * to replace
5 *
6 * git merge [-s recursive]
7 *
8 * with
9 *
10 * git merge -s ort
11 *
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"?)
15 */
16
17#include "cache.h"
18#include "merge-ort.h"
19
4296d8f1 20#include "alloc.h"
ea305a68 21#include "attr.h"
67845745 22#include "blob.h"
ef2b3693 23#include "cache-tree.h"
4296d8f1 24#include "commit.h"
67845745 25#include "commit-reach.h"
e4171b1b
EN
26#include "diff.h"
27#include "diffcore.h"
6681ce5c 28#include "dir.h"
7bec8e7f 29#include "entry.h"
f591c472 30#include "ll-merge.h"
ee4012dc 31#include "object-store.h"
2bff554b 32#include "promisor-remote.h"
4204cd59 33#include "revision.h"
5b59c3db 34#include "strmap.h"
10a0d6ae 35#include "submodule-config.h"
c73cda76 36#include "submodule.h"
231e2dd4 37#include "tree.h"
6681ce5c 38#include "unpack-trees.h"
c8017176 39#include "xdiff-interface.h"
5b59c3db 40
d2bc1994
EN
41/*
42 * We have many arrays of size 3. Whenever we have such an array, the
43 * indices refer to one of the sides of the three-way merge. This is so
44 * pervasive that the constants 0, 1, and 2 are used in many places in the
45 * code (especially in arithmetic operations to find the other side's index
46 * or to compute a relevant mask), but sometimes these enum names are used
47 * to aid code clarity.
48 *
49 * See also 'filemask' and 'dirmask' in struct conflict_info; the "ith side"
50 * referred to there is one of these three sides.
51 */
52enum merge_side {
53 MERGE_BASE = 0,
54 MERGE_SIDE1 = 1,
55 MERGE_SIDE2 = 2
56};
57
19ceb486
EN
58static unsigned RESULT_INITIALIZED = 0x1abe11ed; /* unlikely accidental value */
59
beb06145
EN
60struct traversal_callback_data {
61 unsigned long mask;
62 unsigned long dirmask;
63 struct name_entry names[3];
64};
65
d478f567
EN
66struct deferred_traversal_data {
67 /*
68 * possible_trivial_merges: directories to be explored only when needed
69 *
70 * possible_trivial_merges is a map of directory names to
71 * dir_rename_mask. When we detect that a directory is unchanged on
72 * one side, we can sometimes resolve the directory without recursing
73 * into it. Renames are the only things that can prevent such an
74 * optimization. However, for rename sources:
75 * - If no parent directory needed directory rename detection, then
76 * no path under such a directory can be a relevant_source.
77 * and for rename destinations:
78 * - If no cached rename has a target path under the directory AND
79 * - If there are no unpaired relevant_sources elsewhere in the
80 * repository
81 * then we don't need any path under this directory for a rename
82 * destination. The only way to know the last item above is to defer
83 * handling such directories until the end of collect_merge_info(),
84 * in handle_deferred_entries().
85 *
86 * For each we store dir_rename_mask, since that's the only bit of
87 * information we need, other than the path, to resume the recursive
88 * traversal.
89 */
90 struct strintmap possible_trivial_merges;
91
92 /*
93 * trivial_merges_okay: if trivial directory merges are okay
94 *
95 * See possible_trivial_merges above. The "no unpaired
96 * relevant_sources elsewhere in the repository" is a single boolean
97 * per merge side, which we store here. Note that while 0 means no,
98 * 1 only means "maybe" rather than "yes"; we optimistically set it
99 * to 1 initially and only clear when we determine it is unsafe to
100 * do trivial directory merges.
101 */
102 unsigned trivial_merges_okay;
103
104 /*
105 * target_dirs: ancestor directories of rename targets
106 *
107 * target_dirs contains all directory names that are an ancestor of
108 * any rename destination.
109 */
110 struct strset target_dirs;
111};
112
864075ec 113struct rename_info {
c09376d5
EN
114 /*
115 * All variables that are arrays of size 3 correspond to data tracked
116 * for the sides in enum merge_side. Index 0 is almost always unused
117 * because we often only need to track information for MERGE_SIDE1 and
118 * MERGE_SIDE2 (MERGE_BASE can't have rename information since renames
119 * are determined relative to what changed since the MERGE_BASE).
120 */
121
864075ec
EN
122 /*
123 * pairs: pairing of filenames from diffcore_rename()
864075ec
EN
124 */
125 struct diff_queue_struct pairs[3];
126
c09376d5
EN
127 /*
128 * dirs_removed: directories removed on a given side of history.
fb52938e
EN
129 *
130 * The keys of dirs_removed[side] are the directories that were removed
131 * on the given side of history. The value of the strintmap for each
132 * directory is a value from enum dir_rename_relevance.
c09376d5 133 */
a49b55d5 134 struct strintmap dirs_removed[3];
c09376d5
EN
135
136 /*
137 * dir_rename_count: tracking where parts of a directory were renamed to
138 *
139 * When files in a directory are renamed, they may not all go to the
140 * same location. Each strmap here tracks:
141 * old_dir => {new_dir => int}
142 * That is, dir_rename_count[side] is a strmap to a strintmap.
143 */
144 struct strmap dir_rename_count[3];
145
146 /*
147 * dir_renames: computed directory renames
148 *
149 * This is a map of old_dir => new_dir and is derived in part from
150 * dir_rename_count.
151 */
152 struct strmap dir_renames[3];
153
32a56dfb 154 /*
ec59da60 155 * relevant_sources: deleted paths wanted in rename detection, and why
32a56dfb
EN
156 *
157 * relevant_sources is a set of deleted paths on each side of
158 * history for which we need rename detection. If a path is deleted
159 * on one side of history, we need to detect if it is part of a
160 * rename if either
32a56dfb 161 * * the file is modified/deleted on the other side of history
ec59da60 162 * * we need to detect renames for an ancestor directory
32a56dfb 163 * If neither of those are true, we can skip rename detection for
ec59da60
EN
164 * that path. The reason is stored as a value from enum
165 * file_rename_relevance, as the reason can inform the algorithm in
166 * diffcore_rename_extended().
32a56dfb 167 */
a49b55d5 168 struct strintmap relevant_sources[3];
32a56dfb 169
d478f567
EN
170 struct deferred_traversal_data deferred[3];
171
2fd9eda4
EN
172 /*
173 * dir_rename_mask:
174 * 0: optimization removing unmodified potential rename source okay
175 * 2 or 4: optimization okay, but must check for files added to dir
176 * 7: optimization forbidden; need rename source in case of dir rename
177 */
178 unsigned dir_rename_mask:3;
179
beb06145
EN
180 /*
181 * callback_data_*: supporting data structures for alternate traversal
182 *
183 * We sometimes need to be able to traverse through all the files
184 * in a given tree before all immediate subdirectories within that
185 * tree. Since traverse_trees() doesn't do that naturally, we have
186 * a traverse_trees_wrapper() that stores any immediate
187 * subdirectories while traversing files, then traverses the
188 * immediate subdirectories later. These callback_data* variables
189 * store the information for the subdirectories so that we can do
190 * that traversal order.
191 */
192 struct traversal_callback_data *callback_data;
193 int callback_data_nr, callback_data_alloc;
194 char *callback_data_traverse_path;
195
64aceb6d
EN
196 /*
197 * merge_trees: trees passed to the merge algorithm for the merge
198 *
199 * merge_trees records the trees passed to the merge algorithm. But,
200 * this data also is stored in merge_result->priv. If a sequence of
201 * merges are being done (such as when cherry-picking or rebasing),
202 * the next merge can look at this and re-use information from
203 * previous merges under certain circumstances.
204 *
205 * See also all the cached_* variables.
206 */
207 struct tree *merge_trees[3];
208
209 /*
210 * cached_pairs_valid_side: which side's cached info can be reused
211 *
212 * See the description for merge_trees. For repeated merges, at most
213 * only one side's cached information can be used. Valid values:
214 * MERGE_SIDE2: cached data from side2 can be reused
215 * MERGE_SIDE1: cached data from side1 can be reused
216 * 0: no cached data can be reused
8b09a900 217 * -1: See redo_after_renames; both sides can be reused.
64aceb6d
EN
218 */
219 int cached_pairs_valid_side;
220
d29bd6d7
EN
221 /*
222 * cached_pairs: Caching of renames and deletions.
223 *
224 * These are mappings recording renames and deletions of individual
225 * files (not directories). They are thus a map from an old
226 * filename to either NULL (for deletions) or a new filename (for
227 * renames).
228 */
229 struct strmap cached_pairs[3];
230
231 /*
232 * cached_target_names: just the destinations from cached_pairs
233 *
234 * We sometimes want a fast lookup to determine if a given filename
235 * is one of the destinations in cached_pairs. cached_target_names
236 * is thus duplicative information, but it provides a fast lookup.
237 */
238 struct strset cached_target_names[3];
239
240 /*
241 * cached_irrelevant: Caching of rename_sources that aren't relevant.
242 *
243 * If we try to detect a rename for a source path and succeed, it's
244 * part of a rename. If we try to detect a rename for a source path
245 * and fail, then it's a delete. If we do not try to detect a rename
246 * for a path, then we don't know if it's a rename or a delete. If
247 * merge-ort doesn't think the path is relevant, then we just won't
248 * cache anything for that path. But there's a slight problem in
249 * that merge-ort can think a path is RELEVANT_LOCATION, but due to
250 * commit 9bd342137e ("diffcore-rename: determine which
251 * relevant_sources are no longer relevant", 2021-03-13),
252 * diffcore-rename can downgrade the path to RELEVANT_NO_MORE. To
253 * avoid excessive calls to diffcore_rename_extended() we still need
254 * to cache such paths, though we cannot record them as either
255 * renames or deletes. So we cache them here as a "turned out to be
256 * irrelevant *for this commit*" as they are often also irrelevant
257 * for subsequent commits, though we will have to do some extra
258 * checking to see whether such paths become relevant for rename
259 * detection when cherry-picking/rebasing subsequent commits.
260 */
261 struct strset cached_irrelevant[3];
262
8b09a900
EN
263 /*
264 * redo_after_renames: optimization flag for "restarting" the merge
265 *
266 * Sometimes it pays to detect renames, cache them, and then
267 * restart the merge operation from the beginning. The reason for
268 * this is that when we know where all the renames are, we know
269 * whether a certain directory has any paths under it affected --
270 * and if a directory is not affected then it permits us to do
271 * trivial tree merging in more cases. Doing trivial tree merging
272 * prevents the need to run process_entry() on every path
273 * underneath trees that can be trivially merged, and
274 * process_entry() is more expensive than collect_merge_info() --
275 * plus, the second collect_merge_info() will be much faster since
276 * it doesn't have to recurse into the relevant trees.
277 *
278 * Values for this flag:
279 * 0 = don't bother, not worth it (or conditions not yet checked)
280 * 1 = conditions for optimization met, optimization worthwhile
281 * 2 = we already did it (don't restart merge yet again)
282 */
283 unsigned redo_after_renames;
284
864075ec
EN
285 /*
286 * needed_limit: value needed for inexact rename detection to run
287 *
288 * If the current rename limit wasn't high enough for inexact
289 * rename detection to run, this records the limit needed. Otherwise,
290 * this value remains 0.
291 */
292 int needed_limit;
293};
294
5b59c3db
EN
295struct merge_options_internal {
296 /*
297 * paths: primary data structure in all of merge ort.
298 *
299 * The keys of paths:
300 * * are full relative paths from the toplevel of the repository
301 * (e.g. "drivers/firmware/raspberrypi.c").
302 * * store all relevant paths in the repo, both directories and
303 * files (e.g. drivers, drivers/firmware would also be included)
304 * * these keys serve to intern all the path strings, which allows
305 * us to do pointer comparison on directory names instead of
306 * strcmp; we just have to be careful to use the interned strings.
307 *
308 * The values of paths:
309 * * either a pointer to a merged_info, or a conflict_info struct
310 * * merged_info contains all relevant information for a
311 * non-conflicted entry.
312 * * conflict_info contains a merged_info, plus any additional
313 * information about a conflict such as the higher orders stages
314 * involved and the names of the paths those came from (handy
315 * once renames get involved).
316 * * a path may start "conflicted" (i.e. point to a conflict_info)
317 * and then a later step (e.g. three-way content merge) determines
318 * it can be cleanly merged, at which point it'll be marked clean
319 * and the algorithm will ignore any data outside the contained
320 * merged_info for that entry
321 * * If an entry remains conflicted, the merged_info portion of a
322 * conflict_info will later be filled with whatever version of
323 * the file should be placed in the working directory (e.g. an
324 * as-merged-as-possible variation that contains conflict markers).
325 */
326 struct strmap paths;
327
328 /*
329 * conflicted: a subset of keys->values from "paths"
330 *
331 * conflicted is basically an optimization between process_entries()
332 * and record_conflicted_index_entries(); the latter could loop over
333 * ALL the entries in paths AGAIN and look for the ones that are
334 * still conflicted, but since process_entries() has to loop over
335 * all of them, it saves the ones it couldn't resolve in this strmap
336 * so that record_conflicted_index_entries() can iterate just the
337 * relevant entries.
338 */
339 struct strmap conflicted;
340
43c1dccb 341 /*
4137c54b 342 * pool: memory pool for fast allocation/deallocation
43c1dccb 343 *
4137c54b
EN
344 * We allocate room for lots of filenames and auxiliary data
345 * structures in merge_options_internal, and it tends to all be
346 * freed together too. Using a memory pool for these provides a
347 * nice speedup.
43c1dccb 348 */
62a15162 349 struct mem_pool pool;
43c1dccb 350
c5a6f655 351 /*
6debb752 352 * conflicts: logical conflicts and messages stored by _primary_ path
c5a6f655
EN
353 *
354 * This is a map of pathnames (a subset of the keys in "paths" above)
6debb752
JS
355 * to struct string_list, with each item's `util` containing a
356 * `struct logical_conflict_info`. Note, though, that for each path,
357 * it only stores the logical conflicts for which that path is the
358 * primary path; the path might be part of additional conflicts.
c5a6f655 359 */
6debb752 360 struct strmap conflicts;
c5a6f655 361
5b59c3db 362 /*
864075ec
EN
363 * renames: various data relating to rename detection
364 */
365 struct rename_info renames;
366
ea305a68
EN
367 /*
368 * attr_index: hacky minimal index used for renormalization
369 *
370 * renormalization code _requires_ an index, though it only needs to
371 * find a .gitattributes file within the index. So, when
372 * renormalization is important, we create a special index with just
373 * that one file.
374 */
375 struct index_state attr_index;
376
5b59c3db 377 /*
05b85c6e 378 * current_dir_name, toplevel_dir: temporary vars
5b59c3db 379 *
05b85c6e
EN
380 * These are used in collect_merge_info_callback(), and will set the
381 * various merged_info.directory_name for the various paths we get;
382 * see documentation for that variable and the requirements placed on
383 * that field.
5b59c3db
EN
384 */
385 const char *current_dir_name;
05b85c6e 386 const char *toplevel_dir;
5b59c3db
EN
387
388 /* call_depth: recursion level counter for merging merge bases */
389 int call_depth;
4057523a
CW
390
391 /* field that holds submodule conflict information */
392 struct string_list conflicted_submodules;
393};
394
395struct conflicted_submodule_item {
396 char *abbrev;
397 int flag;
5b59c3db
EN
398};
399
4057523a
CW
400static void conflicted_submodule_item_free(void *util, const char *str)
401{
402 struct conflicted_submodule_item *item = util;
403
404 free(item->abbrev);
405 free(item);
406}
407
5b59c3db
EN
408struct version_info {
409 struct object_id oid;
410 unsigned short mode;
411};
412
413struct merged_info {
414 /* if is_null, ignore result. otherwise result has oid & mode */
415 struct version_info result;
416 unsigned is_null:1;
417
418 /*
419 * clean: whether the path in question is cleanly merged.
420 *
421 * see conflict_info.merged for more details.
422 */
423 unsigned clean:1;
424
425 /*
426 * basename_offset: offset of basename of path.
427 *
428 * perf optimization to avoid recomputing offset of final '/'
429 * character in pathname (0 if no '/' in pathname).
430 */
431 size_t basename_offset;
432
433 /*
434 * directory_name: containing directory name.
435 *
436 * Note that we assume directory_name is constructed such that
437 * strcmp(dir1_name, dir2_name) == 0 iff dir1_name == dir2_name,
438 * i.e. string equality is equivalent to pointer equality. For this
439 * to hold, we have to be careful setting directory_name.
440 */
441 const char *directory_name;
442};
443
444struct conflict_info {
445 /*
446 * merged: the version of the path that will be written to working tree
447 *
448 * WARNING: It is critical to check merged.clean and ensure it is 0
449 * before reading any conflict_info fields outside of merged.
450 * Allocated merge_info structs will always have clean set to 1.
451 * Allocated conflict_info structs will have merged.clean set to 0
452 * initially. The merged.clean field is how we know if it is safe
453 * to access other parts of conflict_info besides merged; if a
454 * conflict_info's merged.clean is changed to 1, the rest of the
455 * algorithm is not allowed to look at anything outside of the
456 * merged member anymore.
457 */
458 struct merged_info merged;
459
460 /* oids & modes from each of the three trees for this path */
461 struct version_info stages[3];
462
463 /* pathnames for each stage; may differ due to rename detection */
464 const char *pathnames[3];
465
466 /* Whether this path is/was involved in a directory/file conflict */
467 unsigned df_conflict:1;
468
1c7873cd
EN
469 /*
470 * Whether this path is/was involved in a non-content conflict other
471 * than a directory/file conflict (e.g. rename/rename, rename/delete,
472 * file location based on possible directory rename).
473 */
474 unsigned path_conflict:1;
475
5b59c3db
EN
476 /*
477 * For filemask and dirmask, the ith bit corresponds to whether the
478 * ith entry is a file (filemask) or a directory (dirmask). Thus,
479 * filemask & dirmask is always zero, and filemask | dirmask is at
480 * most 7 but can be less when a path does not appear as either a
481 * file or a directory on at least one side of history.
482 *
483 * Note that these masks are related to enum merge_side, as the ith
484 * entry corresponds to side i.
485 *
486 * These values come from a traverse_trees() call; more info may be
487 * found looking at tree-walk.h's struct traverse_info,
488 * particularly the documentation above the "fn" member (note that
489 * filemask = mask & ~dirmask from that documentation).
490 */
491 unsigned filemask:3;
492 unsigned dirmask:3;
493
494 /*
495 * Optimization to track which stages match, to avoid the need to
496 * recompute it in multiple steps. Either 0 or at least 2 bits are
497 * set; if at least 2 bits are set, their corresponding stages match.
498 */
499 unsigned match_mask:3;
500};
501
cb260775
EN
502enum conflict_and_info_types {
503 /* "Simple" conflicts and informational messages */
504 INFO_AUTO_MERGING = 0,
505 CONFLICT_CONTENTS, /* text file that failed to merge */
506 CONFLICT_BINARY,
507 CONFLICT_FILE_DIRECTORY,
508 CONFLICT_DISTINCT_MODES,
509 CONFLICT_MODIFY_DELETE,
cb260775
EN
510
511 /* Regular rename */
512 CONFLICT_RENAME_RENAME, /* same file renamed differently */
513 CONFLICT_RENAME_COLLIDES, /* rename/add or two files renamed to 1 */
514 CONFLICT_RENAME_DELETE,
515
516 /* Basic directory rename */
517 CONFLICT_DIR_RENAME_SUGGESTED,
518 INFO_DIR_RENAME_APPLIED,
519
520 /* Special directory rename cases */
521 INFO_DIR_RENAME_SKIPPED_DUE_TO_RERENAME,
522 CONFLICT_DIR_RENAME_FILE_IN_WAY,
523 CONFLICT_DIR_RENAME_COLLISION,
524 CONFLICT_DIR_RENAME_SPLIT,
525
526 /* Basic submodule */
527 INFO_SUBMODULE_FAST_FORWARDING,
528 CONFLICT_SUBMODULE_FAILED_TO_MERGE,
529
530 /* Special submodule cases broken out from FAILED_TO_MERGE */
531 CONFLICT_SUBMODULE_FAILED_TO_MERGE_BUT_POSSIBLE_RESOLUTION,
532 CONFLICT_SUBMODULE_NOT_INITIALIZED,
533 CONFLICT_SUBMODULE_HISTORY_NOT_AVAILABLE,
534 CONFLICT_SUBMODULE_MAY_HAVE_REWINDS,
4057523a 535 CONFLICT_SUBMODULE_NULL_MERGE_BASE,
cb260775
EN
536
537 /* Keep this entry _last_ in the list */
538 NB_CONFLICT_TYPES,
539};
540
541/*
542 * Short description of conflict type, relied upon by external tools.
543 *
544 * We can add more entries, but DO NOT change any of these strings. Also,
545 * Order MUST match conflict_info_and_types.
546 */
547static const char *type_short_descriptions[] = {
548 /*** "Simple" conflicts and informational messages ***/
549 [INFO_AUTO_MERGING] = "Auto-merging",
550 [CONFLICT_CONTENTS] = "CONFLICT (contents)",
551 [CONFLICT_BINARY] = "CONFLICT (binary)",
552 [CONFLICT_FILE_DIRECTORY] = "CONFLICT (file/directory)",
553 [CONFLICT_DISTINCT_MODES] = "CONFLICT (distinct modes)",
554 [CONFLICT_MODIFY_DELETE] = "CONFLICT (modify/delete)",
cb260775
EN
555
556 /*** Regular rename ***/
557 [CONFLICT_RENAME_RENAME] = "CONFLICT (rename/rename)",
558 [CONFLICT_RENAME_COLLIDES] = "CONFLICT (rename involved in collision)",
559 [CONFLICT_RENAME_DELETE] = "CONFLICT (rename/delete)",
560
561 /*** Basic directory rename ***/
562 [CONFLICT_DIR_RENAME_SUGGESTED] =
563 "CONFLICT (directory rename suggested)",
564 [INFO_DIR_RENAME_APPLIED] = "Path updated due to directory rename",
565
566 /*** Special directory rename cases ***/
567 [INFO_DIR_RENAME_SKIPPED_DUE_TO_RERENAME] =
568 "Directory rename skipped since directory was renamed on both sides",
569 [CONFLICT_DIR_RENAME_FILE_IN_WAY] =
570 "CONFLICT (file in way of directory rename)",
571 [CONFLICT_DIR_RENAME_COLLISION] = "CONFLICT(directory rename collision)",
572 [CONFLICT_DIR_RENAME_SPLIT] = "CONFLICT(directory rename unclear split)",
573
574 /*** Basic submodule ***/
575 [INFO_SUBMODULE_FAST_FORWARDING] = "Fast forwarding submodule",
576 [CONFLICT_SUBMODULE_FAILED_TO_MERGE] = "CONFLICT (submodule)",
577
578 /*** Special submodule cases broken out from FAILED_TO_MERGE ***/
579 [CONFLICT_SUBMODULE_FAILED_TO_MERGE_BUT_POSSIBLE_RESOLUTION] =
580 "CONFLICT (submodule with possible resolution)",
581 [CONFLICT_SUBMODULE_NOT_INITIALIZED] =
582 "CONFLICT (submodule not initialized)",
583 [CONFLICT_SUBMODULE_HISTORY_NOT_AVAILABLE] =
584 "CONFLICT (submodule history not available)",
585 [CONFLICT_SUBMODULE_MAY_HAVE_REWINDS] =
586 "CONFLICT (submodule may have rewinds)",
4057523a
CW
587 [CONFLICT_SUBMODULE_NULL_MERGE_BASE] =
588 "CONFLICT (submodule lacks merge base)"
cb260775
EN
589};
590
591struct logical_conflict_info {
592 enum conflict_and_info_types type;
593 struct strvec paths;
594};
595
04af1879
EN
596/*** Function Grouping: various utility functions ***/
597
98bf9841
EN
598/*
599 * For the next three macros, see warning for conflict_info.merged.
600 *
601 * In each of the below, mi is a struct merged_info*, and ci was defined
602 * as a struct conflict_info* (but we need to verify ci isn't actually
603 * pointed at a struct merged_info*).
604 *
605 * INITIALIZE_CI: Assign ci to mi but only if it's safe; set to NULL otherwise.
606 * VERIFY_CI: Ensure that something we assigned to a conflict_info* is one.
607 * ASSIGN_AND_VERIFY_CI: Similar to VERIFY_CI but do assignment first.
608 */
609#define INITIALIZE_CI(ci, mi) do { \
610 (ci) = (!(mi) || (mi)->clean) ? NULL : (struct conflict_info *)(mi); \
611} while (0)
612#define VERIFY_CI(ci) assert(ci && !ci->merged.clean);
613#define ASSIGN_AND_VERIFY_CI(ci, mi) do { \
614 (ci) = (struct conflict_info *)(mi); \
615 assert((ci) && !(mi)->clean); \
616} while (0)
617
89422d29
EN
618static void free_strmap_strings(struct strmap *map)
619{
620 struct hashmap_iter iter;
621 struct strmap_entry *entry;
622
623 strmap_for_each_entry(map, &iter, entry) {
624 free((char*)entry->key);
625 }
626}
627
43e9c4ee
EN
628static void clear_or_reinit_internal_opts(struct merge_options_internal *opti,
629 int reinitialize)
101bc5bc 630{
f5d9fbc2
EN
631 struct rename_info *renames = &opti->renames;
632 int i;
7afc0b03 633 void (*strmap_clear_func)(struct strmap *, int) =
43e9c4ee 634 reinitialize ? strmap_partial_clear : strmap_clear;
7afc0b03 635 void (*strintmap_clear_func)(struct strintmap *) =
a49b55d5 636 reinitialize ? strintmap_partial_clear : strintmap_clear;
7afc0b03 637 void (*strset_clear_func)(struct strset *) =
d29bd6d7 638 reinitialize ? strset_partial_clear : strset_clear;
101bc5bc 639
62a15162 640 strmap_clear_func(&opti->paths, 0);
101bc5bc
EN
641
642 /*
643 * All keys and values in opti->conflicted are a subset of those in
644 * opti->paths. We don't want to deallocate anything twice, so we
645 * don't free the keys and we pass 0 for free_values.
646 */
7afc0b03 647 strmap_clear_func(&opti->conflicted, 0);
c5a6f655 648
1218b3ab 649 if (opti->attr_index.cache_nr) /* true iff opt->renormalize */
ea305a68
EN
650 discard_index(&opti->attr_index);
651
f5d9fbc2
EN
652 /* Free memory used by various renames maps */
653 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; ++i) {
7afc0b03
EN
654 strintmap_clear_func(&renames->dirs_removed[i]);
655 strmap_clear_func(&renames->dir_renames[i], 0);
656 strintmap_clear_func(&renames->relevant_sources[i]);
d5098029
EN
657 if (!reinitialize)
658 assert(renames->cached_pairs_valid_side == 0);
8b09a900
EN
659 if (i != renames->cached_pairs_valid_side &&
660 -1 != renames->cached_pairs_valid_side) {
7afc0b03
EN
661 strset_clear_func(&renames->cached_target_names[i]);
662 strmap_clear_func(&renames->cached_pairs[i], 1);
663 strset_clear_func(&renames->cached_irrelevant[i]);
d5098029
EN
664 partial_clear_dir_rename_count(&renames->dir_rename_count[i]);
665 if (!reinitialize)
666 strmap_clear(&renames->dir_rename_count[i], 1);
667 }
f5d9fbc2 668 }
d478f567 669 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; ++i) {
7afc0b03
EN
670 strintmap_clear_func(&renames->deferred[i].possible_trivial_merges);
671 strset_clear_func(&renames->deferred[i].target_dirs);
d478f567
EN
672 renames->deferred[i].trivial_merges_okay = 1; /* 1 == maybe */
673 }
64aceb6d
EN
674 renames->cached_pairs_valid_side = 0;
675 renames->dir_rename_mask = 0;
f5d9fbc2 676
c5a6f655
EN
677 if (!reinitialize) {
678 struct hashmap_iter iter;
679 struct strmap_entry *e;
680
681 /* Release and free each strbuf found in output */
6debb752
JS
682 strmap_for_each_entry(&opti->conflicts, &iter, e) {
683 struct string_list *list = e->value;
cb260775
EN
684 for (int i = 0; i < list->nr; i++) {
685 struct logical_conflict_info *info =
686 list->items[i].util;
687 strvec_clear(&info->paths);
688 }
c5a6f655 689 /*
6debb752
JS
690 * While strictly speaking we don't need to
691 * free(conflicts) here because we could pass
692 * free_values=1 when calling strmap_clear() on
693 * opti->conflicts, that would require strmap_clear
694 * to do another strmap_for_each_entry() loop, so we
695 * just free it while we're iterating anyway.
c5a6f655 696 */
6debb752
JS
697 string_list_clear(list, 1);
698 free(list);
c5a6f655 699 }
6debb752 700 strmap_clear(&opti->conflicts, 0);
c5a6f655 701 }
beb06145 702
62a15162 703 mem_pool_discard(&opti->pool, 0);
4137c54b 704
4057523a
CW
705 string_list_clear_func(&opti->conflicted_submodules,
706 conflicted_submodule_item_free);
707
beb06145
EN
708 /* Clean out callback_data as well. */
709 FREE_AND_NULL(renames->callback_data);
710 renames->callback_data_nr = renames->callback_data_alloc = 0;
101bc5bc
EN
711}
712
48ca53ca 713__attribute__((format (printf, 2, 3)))
0c0d705b
EN
714static int err(struct merge_options *opt, const char *err, ...)
715{
716 va_list params;
717 struct strbuf sb = STRBUF_INIT;
718
719 strbuf_addstr(&sb, "error: ");
720 va_start(params, err);
721 strbuf_vaddf(&sb, err, params);
722 va_end(params);
723
724 error("%s", sb.buf);
725 strbuf_release(&sb);
726
727 return -1;
728}
729
c73cda76
EN
730static void format_commit(struct strbuf *sb,
731 int indent,
155b517d 732 struct repository *repo,
c73cda76
EN
733 struct commit *commit)
734{
70f19c7f
EN
735 struct merge_remote_desc *desc;
736 struct pretty_print_context ctx = {0};
737 ctx.abbrev = DEFAULT_ABBREV;
738
739 strbuf_addchars(sb, ' ', indent);
740 desc = merge_remote_util(commit);
741 if (desc) {
742 strbuf_addf(sb, "virtual %s\n", desc->name);
743 return;
744 }
745
155b517d 746 repo_format_commit_message(repo, commit, "%h %s", sb, &ctx);
70f19c7f 747 strbuf_addch(sb, '\n');
c73cda76
EN
748}
749
cb260775 750__attribute__((format (printf, 8, 9)))
c5a6f655 751static void path_msg(struct merge_options *opt,
cb260775 752 enum conflict_and_info_types type,
c5a6f655 753 int omittable_hint, /* skippable under --remerge-diff */
cb260775
EN
754 const char *primary_path,
755 const char *other_path_1, /* may be NULL */
756 const char *other_path_2, /* may be NULL */
757 struct string_list *other_paths, /* may be NULL */
c5a6f655
EN
758 const char *fmt, ...)
759{
760 va_list ap;
6debb752 761 struct string_list *path_conflicts;
cb260775 762 struct logical_conflict_info *info;
6debb752
JS
763 struct strbuf buf = STRBUF_INIT;
764 struct strbuf *dest;
6054d1aa
EN
765 struct strbuf tmp = STRBUF_INIT;
766
cb260775
EN
767 /* Sanity checks */
768 assert(omittable_hint ==
769 !starts_with(type_short_descriptions[type], "CONFLICT") ||
ff033db7 770 type == CONFLICT_DIR_RENAME_SUGGESTED);
6054d1aa 771 if (opt->record_conflict_msgs_as_headers && omittable_hint)
0d83d824 772 return; /* Do not record mere hints in headers */
624a9350
EN
773 if (opt->priv->call_depth && opt->verbosity < 5)
774 return; /* Ignore messages from inner merges */
775
6debb752 776 /* Ensure path_conflicts (ptr to array of logical_conflict) allocated */
cb260775 777 path_conflicts = strmap_get(&opt->priv->conflicts, primary_path);
6debb752
JS
778 if (!path_conflicts) {
779 path_conflicts = xmalloc(sizeof(*path_conflicts));
780 string_list_init_dup(path_conflicts);
cb260775 781 strmap_put(&opt->priv->conflicts, primary_path, path_conflicts);
c5a6f655
EN
782 }
783
cb260775
EN
784 /* Add a logical_conflict at the end to store info from this call */
785 info = xcalloc(1, sizeof(*info));
786 info->type = type;
787 strvec_init(&info->paths);
788
789 /* Handle the list of paths */
790 strvec_push(&info->paths, primary_path);
791 if (other_path_1)
792 strvec_push(&info->paths, other_path_1);
793 if (other_path_2)
794 strvec_push(&info->paths, other_path_2);
795 if (other_paths)
796 for (int i = 0; i < other_paths->nr; i++)
797 strvec_push(&info->paths, other_paths->items[i].string);
798
6debb752
JS
799 /* Handle message and its format, in normal case */
800 dest = (opt->record_conflict_msgs_as_headers ? &tmp : &buf);
6054d1aa 801
c5a6f655 802 va_start(ap, fmt);
4a3d86e1
EN
803 if (opt->priv->call_depth) {
804 strbuf_addchars(dest, ' ', 2);
805 strbuf_addstr(dest, "From inner merge:");
806 strbuf_addchars(dest, ' ', opt->priv->call_depth * 2);
807 }
6054d1aa 808 strbuf_vaddf(dest, fmt, ap);
c5a6f655
EN
809 va_end(ap);
810
6debb752 811 /* Handle specialized formatting of message under --remerge-diff */
6054d1aa
EN
812 if (opt->record_conflict_msgs_as_headers) {
813 int i_sb = 0, i_tmp = 0;
814
815 /* Start with the specified prefix */
816 if (opt->msg_header_prefix)
6debb752 817 strbuf_addf(&buf, "%s ", opt->msg_header_prefix);
6054d1aa
EN
818
819 /* Copy tmp to sb, adding spaces after newlines */
6debb752 820 strbuf_grow(&buf, buf.len + 2*tmp.len); /* more than sufficient */
6054d1aa
EN
821 for (; i_tmp < tmp.len; i_tmp++, i_sb++) {
822 /* Copy next character from tmp to sb */
6debb752 823 buf.buf[buf.len + i_sb] = tmp.buf[i_tmp];
6054d1aa
EN
824
825 /* If we copied a newline, add a space */
826 if (tmp.buf[i_tmp] == '\n')
6debb752 827 buf.buf[++i_sb] = ' ';
6054d1aa
EN
828 }
829 /* Update length and ensure it's NUL-terminated */
6debb752
JS
830 buf.len += i_sb;
831 buf.buf[buf.len] = '\0';
6054d1aa
EN
832
833 strbuf_release(&tmp);
834 }
cb260775
EN
835 string_list_append_nodup(path_conflicts, strbuf_detach(&buf, NULL))
836 ->util = info;
c5a6f655
EN
837}
838
a8791ef6
EN
839static struct diff_filespec *pool_alloc_filespec(struct mem_pool *pool,
840 const char *path)
841{
62a15162 842 /* Similar to alloc_filespec(), but allocate from pool and reuse path */
a8791ef6 843 struct diff_filespec *spec;
a8791ef6 844
092e5115
EN
845 spec = mem_pool_calloc(pool, 1, sizeof(*spec));
846 spec->path = (char*)path; /* spec won't modify it */
a8791ef6
EN
847
848 spec->count = 1;
849 spec->is_binary = -1;
850 return spec;
851}
852
a8791ef6
EN
853static struct diff_filepair *pool_diff_queue(struct mem_pool *pool,
854 struct diff_queue_struct *queue,
855 struct diff_filespec *one,
856 struct diff_filespec *two)
857{
62a15162 858 /* Same code as diff_queue(), except allocate from pool */
a8791ef6
EN
859 struct diff_filepair *dp;
860
a8791ef6
EN
861 dp = mem_pool_calloc(pool, 1, sizeof(*dp));
862 dp->one = one;
863 dp->two = two;
864 if (queue)
865 diff_q(queue, dp);
866 return dp;
867}
868
5a1a1e8e
EN
869/* add a string to a strbuf, but converting "/" to "_" */
870static void add_flattened_path(struct strbuf *out, const char *s)
871{
872 size_t i = out->len;
873 strbuf_addstr(out, s);
874 for (; i < out->len; i++)
875 if (out->buf[i] == '/')
876 out->buf[i] = '_';
877}
878
81afc794 879static char *unique_path(struct merge_options *opt,
23366d2a
EN
880 const char *path,
881 const char *branch)
882{
81afc794 883 char *ret = NULL;
5a1a1e8e
EN
884 struct strbuf newpath = STRBUF_INIT;
885 int suffix = 0;
886 size_t base_len;
81afc794 887 struct strmap *existing_paths = &opt->priv->paths;
5a1a1e8e
EN
888
889 strbuf_addf(&newpath, "%s~", path);
890 add_flattened_path(&newpath, branch);
891
892 base_len = newpath.len;
893 while (strmap_contains(existing_paths, newpath.buf)) {
894 strbuf_setlen(&newpath, base_len);
895 strbuf_addf(&newpath, "_%d", suffix++);
896 }
897
81afc794
EN
898 /* Track the new path in our memory pool */
899 ret = mem_pool_alloc(&opt->priv->pool, newpath.len + 1);
900 memcpy(ret, newpath.buf, newpath.len + 1);
901 strbuf_release(&newpath);
902 return ret;
23366d2a
EN
903}
904
04af1879
EN
905/*** Function Grouping: functions related to collect_merge_info() ***/
906
a68e6cea
EN
907static int traverse_trees_wrapper_callback(int n,
908 unsigned long mask,
909 unsigned long dirmask,
910 struct name_entry *names,
911 struct traverse_info *info)
912{
913 struct merge_options *opt = info->data;
914 struct rename_info *renames = &opt->priv->renames;
2fd9eda4 915 unsigned filemask = mask & ~dirmask;
a68e6cea
EN
916
917 assert(n==3);
918
919 if (!renames->callback_data_traverse_path)
920 renames->callback_data_traverse_path = xstrdup(info->traverse_path);
921
2fd9eda4
EN
922 if (filemask && filemask == renames->dir_rename_mask)
923 renames->dir_rename_mask = 0x07;
924
a68e6cea
EN
925 ALLOC_GROW(renames->callback_data, renames->callback_data_nr + 1,
926 renames->callback_data_alloc);
927 renames->callback_data[renames->callback_data_nr].mask = mask;
928 renames->callback_data[renames->callback_data_nr].dirmask = dirmask;
929 COPY_ARRAY(renames->callback_data[renames->callback_data_nr].names,
930 names, 3);
931 renames->callback_data_nr++;
932
933 return mask;
934}
935
936/*
937 * Much like traverse_trees(), BUT:
938 * - read all the tree entries FIRST, saving them
939 * - note that the above step provides an opportunity to compute necessary
940 * additional details before the "real" traversal
941 * - loop through the saved entries and call the original callback on them
942 */
a68e6cea
EN
943static int traverse_trees_wrapper(struct index_state *istate,
944 int n,
945 struct tree_desc *t,
946 struct traverse_info *info)
947{
948 int ret, i, old_offset;
949 traverse_callback_t old_fn;
950 char *old_callback_data_traverse_path;
951 struct merge_options *opt = info->data;
952 struct rename_info *renames = &opt->priv->renames;
953
2fd9eda4
EN
954 assert(renames->dir_rename_mask == 2 || renames->dir_rename_mask == 4);
955
a68e6cea
EN
956 old_callback_data_traverse_path = renames->callback_data_traverse_path;
957 old_fn = info->fn;
958 old_offset = renames->callback_data_nr;
959
960 renames->callback_data_traverse_path = NULL;
961 info->fn = traverse_trees_wrapper_callback;
962 ret = traverse_trees(istate, n, t, info);
963 if (ret < 0)
964 return ret;
965
966 info->traverse_path = renames->callback_data_traverse_path;
967 info->fn = old_fn;
968 for (i = old_offset; i < renames->callback_data_nr; ++i) {
969 info->fn(n,
970 renames->callback_data[i].mask,
971 renames->callback_data[i].dirmask,
972 renames->callback_data[i].names,
973 info);
974 }
975
976 renames->callback_data_nr = old_offset;
977 free(renames->callback_data_traverse_path);
978 renames->callback_data_traverse_path = old_callback_data_traverse_path;
979 info->traverse_path = NULL;
980 return 0;
981}
982
98bf9841
EN
983static void setup_path_info(struct merge_options *opt,
984 struct string_list_item *result,
985 const char *current_dir_name,
986 int current_dir_name_len,
987 char *fullpath, /* we'll take over ownership */
988 struct name_entry *names,
989 struct name_entry *merged_version,
990 unsigned is_null, /* boolean */
991 unsigned df_conflict, /* boolean */
992 unsigned filemask,
993 unsigned dirmask,
994 int resolved /* boolean */)
995{
996 /* result->util is void*, so mi is a convenience typed variable */
997 struct merged_info *mi;
998
999 assert(!is_null || resolved);
1000 assert(!df_conflict || !resolved); /* df_conflict implies !resolved */
1001 assert(resolved == (merged_version != NULL));
1002
62a15162
EN
1003 mi = mem_pool_calloc(&opt->priv->pool, 1,
1004 resolved ? sizeof(struct merged_info) :
1005 sizeof(struct conflict_info));
98bf9841
EN
1006 mi->directory_name = current_dir_name;
1007 mi->basename_offset = current_dir_name_len;
1008 mi->clean = !!resolved;
1009 if (resolved) {
1010 mi->result.mode = merged_version->mode;
1011 oidcpy(&mi->result.oid, &merged_version->oid);
1012 mi->is_null = !!is_null;
1013 } else {
1014 int i;
1015 struct conflict_info *ci;
1016
1017 ASSIGN_AND_VERIFY_CI(ci, mi);
1018 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1019 ci->pathnames[i] = fullpath;
1020 ci->stages[i].mode = names[i].mode;
1021 oidcpy(&ci->stages[i].oid, &names[i].oid);
1022 }
1023 ci->filemask = filemask;
1024 ci->dirmask = dirmask;
1025 ci->df_conflict = !!df_conflict;
1026 if (dirmask)
1027 /*
1028 * Assume is_null for now, but if we have entries
1029 * under the directory then when it is complete in
1030 * write_completed_directory() it'll update this.
1031 * Also, for D/F conflicts, we have to handle the
1032 * directory first, then clear this bit and process
1033 * the file to see how it is handled -- that occurs
1034 * near the top of process_entry().
1035 */
1036 mi->is_null = 1;
1037 }
1038 strmap_put(&opt->priv->paths, fullpath, mi);
1039 result->string = fullpath;
1040 result->util = mi;
1041}
1042
f78cf976
EN
1043static void add_pair(struct merge_options *opt,
1044 struct name_entry *names,
1045 const char *pathname,
1046 unsigned side,
32a56dfb 1047 unsigned is_add /* if false, is_delete */,
2fd9eda4
EN
1048 unsigned match_mask,
1049 unsigned dir_rename_mask)
f78cf976
EN
1050{
1051 struct diff_filespec *one, *two;
1052 struct rename_info *renames = &opt->priv->renames;
1053 int names_idx = is_add ? side : 0;
1054
25e65b6d 1055 if (is_add) {
ef68c3d8 1056 assert(match_mask == 0 || match_mask == 6);
25e65b6d
EN
1057 if (strset_contains(&renames->cached_target_names[side],
1058 pathname))
1059 return;
1060 } else {
32a56dfb 1061 unsigned content_relevant = (match_mask == 0);
2fd9eda4 1062 unsigned location_relevant = (dir_rename_mask == 0x07);
32a56dfb 1063
ef68c3d8
EN
1064 assert(match_mask == 0 || match_mask == 3 || match_mask == 5);
1065
25e65b6d
EN
1066 /*
1067 * If pathname is found in cached_irrelevant[side] due to
1068 * previous pick but for this commit content is relevant,
1069 * then we need to remove it from cached_irrelevant.
1070 */
1071 if (content_relevant)
1072 /* strset_remove is no-op if strset doesn't have key */
1073 strset_remove(&renames->cached_irrelevant[side],
1074 pathname);
1075
1076 /*
1077 * We do not need to re-detect renames for paths that we already
1078 * know the pairing, i.e. for cached_pairs (or
1079 * cached_irrelevant). However, handle_deferred_entries() needs
1080 * to loop over the union of keys from relevant_sources[side] and
1081 * cached_pairs[side], so for simplicity we set relevant_sources
1082 * for all the cached_pairs too and then strip them back out in
1083 * prune_cached_from_relevant() at the beginning of
1084 * detect_regular_renames().
1085 */
ec59da60
EN
1086 if (content_relevant || location_relevant) {
1087 /* content_relevant trumps location_relevant */
1088 strintmap_set(&renames->relevant_sources[side], pathname,
1089 content_relevant ? RELEVANT_CONTENT : RELEVANT_LOCATION);
1090 }
25e65b6d
EN
1091
1092 /*
1093 * Avoid creating pair if we've already cached rename results.
1094 * Note that we do this after setting relevant_sources[side]
1095 * as noted in the comment above.
1096 */
1097 if (strmap_contains(&renames->cached_pairs[side], pathname) ||
1098 strset_contains(&renames->cached_irrelevant[side], pathname))
1099 return;
32a56dfb
EN
1100 }
1101
62a15162
EN
1102 one = pool_alloc_filespec(&opt->priv->pool, pathname);
1103 two = pool_alloc_filespec(&opt->priv->pool, pathname);
f78cf976
EN
1104 fill_filespec(is_add ? two : one,
1105 &names[names_idx].oid, 1, names[names_idx].mode);
62a15162 1106 pool_diff_queue(&opt->priv->pool, &renames->pairs[side], one, two);
f78cf976
EN
1107}
1108
eb3e3e1d
EN
1109static void collect_rename_info(struct merge_options *opt,
1110 struct name_entry *names,
1111 const char *dirname,
1112 const char *fullname,
1113 unsigned filemask,
1114 unsigned dirmask,
1115 unsigned match_mask)
1116{
1117 struct rename_info *renames = &opt->priv->renames;
f78cf976 1118 unsigned side;
eb3e3e1d 1119
2fd9eda4
EN
1120 /*
1121 * Update dir_rename_mask (determines ignore-rename-source validity)
1122 *
1123 * dir_rename_mask helps us keep track of when directory rename
1124 * detection may be relevant. Basically, whenver a directory is
1125 * removed on one side of history, and a file is added to that
1126 * directory on the other side of history, directory rename
1127 * detection is relevant (meaning we have to detect renames for all
1128 * files within that directory to deduce where the directory
1129 * moved). Also, whenever a directory needs directory rename
1130 * detection, due to the "majority rules" choice for where to move
1131 * it (see t6423 testcase 1f), we also need to detect renames for
1132 * all files within subdirectories of that directory as well.
1133 *
1134 * Here we haven't looked at files within the directory yet, we are
1135 * just looking at the directory itself. So, if we aren't yet in
1136 * a case where a parent directory needed directory rename detection
1137 * (i.e. dir_rename_mask != 0x07), and if the directory was removed
1138 * on one side of history, record the mask of the other side of
1139 * history in dir_rename_mask.
1140 */
1141 if (renames->dir_rename_mask != 0x07 &&
1142 (dirmask == 3 || dirmask == 5)) {
1143 /* simple sanity check */
1144 assert(renames->dir_rename_mask == 0 ||
1145 renames->dir_rename_mask == (dirmask & ~1));
1146 /* update dir_rename_mask; have it record mask of new side */
1147 renames->dir_rename_mask = (dirmask & ~1);
1148 }
1149
eb3e3e1d
EN
1150 /* Update dirs_removed, as needed */
1151 if (dirmask == 1 || dirmask == 3 || dirmask == 5) {
1152 /* absent_mask = 0x07 - dirmask; sides = absent_mask/2 */
1153 unsigned sides = (0x07 - dirmask)/2;
fb52938e
EN
1154 unsigned relevance = (renames->dir_rename_mask == 0x07) ?
1155 RELEVANT_FOR_ANCESTOR : NOT_RELEVANT;
1156 /*
1157 * Record relevance of this directory. However, note that
1158 * when collect_merge_info_callback() recurses into this
1159 * directory and calls collect_rename_info() on paths
1160 * within that directory, if we find a path that was added
1161 * to this directory on the other side of history, we will
1162 * upgrade this value to RELEVANT_FOR_SELF; see below.
1163 */
eb3e3e1d 1164 if (sides & 1)
fb52938e
EN
1165 strintmap_set(&renames->dirs_removed[1], fullname,
1166 relevance);
eb3e3e1d 1167 if (sides & 2)
fb52938e
EN
1168 strintmap_set(&renames->dirs_removed[2], fullname,
1169 relevance);
1170 }
1171
1172 /*
1173 * Here's the block that potentially upgrades to RELEVANT_FOR_SELF.
1174 * When we run across a file added to a directory. In such a case,
1175 * find the directory of the file and upgrade its relevance.
1176 */
1177 if (renames->dir_rename_mask == 0x07 &&
1178 (filemask == 2 || filemask == 4)) {
1179 /*
1180 * Need directory rename for parent directory on other side
1181 * of history from added file. Thus
1182 * side = (~filemask & 0x06) >> 1
1183 * or
1184 * side = 3 - (filemask/2).
1185 */
1186 unsigned side = 3 - (filemask >> 1);
1187 strintmap_set(&renames->dirs_removed[side], dirname,
1188 RELEVANT_FOR_SELF);
eb3e3e1d 1189 }
f78cf976
EN
1190
1191 if (filemask == 0 || filemask == 7)
1192 return;
1193
1194 for (side = MERGE_SIDE1; side <= MERGE_SIDE2; ++side) {
1195 unsigned side_mask = (1 << side);
1196
1197 /* Check for deletion on side */
1198 if ((filemask & 1) && !(filemask & side_mask))
32a56dfb 1199 add_pair(opt, names, fullname, side, 0 /* delete */,
2fd9eda4
EN
1200 match_mask & filemask,
1201 renames->dir_rename_mask);
f78cf976
EN
1202
1203 /* Check for addition on side */
1204 if (!(filemask & 1) && (filemask & side_mask))
32a56dfb 1205 add_pair(opt, names, fullname, side, 1 /* add */,
2fd9eda4
EN
1206 match_mask & filemask,
1207 renames->dir_rename_mask);
f78cf976 1208 }
eb3e3e1d
EN
1209}
1210
d2bc1994
EN
1211static int collect_merge_info_callback(int n,
1212 unsigned long mask,
1213 unsigned long dirmask,
1214 struct name_entry *names,
1215 struct traverse_info *info)
1216{
1217 /*
1218 * n is 3. Always.
1219 * common ancestor (mbase) has mask 1, and stored in index 0 of names
1220 * head of side 1 (side1) has mask 2, and stored in index 1 of names
1221 * head of side 2 (side2) has mask 4, and stored in index 2 of names
1222 */
1223 struct merge_options *opt = info->data;
1224 struct merge_options_internal *opti = opt->priv;
2fd9eda4 1225 struct rename_info *renames = &opt->priv->renames;
98bf9841
EN
1226 struct string_list_item pi; /* Path Info */
1227 struct conflict_info *ci; /* typed alias to pi.util (which is void*) */
d2bc1994
EN
1228 struct name_entry *p;
1229 size_t len;
1230 char *fullpath;
98bf9841 1231 const char *dirname = opti->current_dir_name;
2fd9eda4 1232 unsigned prev_dir_rename_mask = renames->dir_rename_mask;
d2bc1994 1233 unsigned filemask = mask & ~dirmask;
34e557af 1234 unsigned match_mask = 0; /* will be updated below */
d2bc1994
EN
1235 unsigned mbase_null = !(mask & 1);
1236 unsigned side1_null = !(mask & 2);
1237 unsigned side2_null = !(mask & 4);
885f0063
EN
1238 unsigned side1_matches_mbase = (!side1_null && !mbase_null &&
1239 names[0].mode == names[1].mode &&
1240 oideq(&names[0].oid, &names[1].oid));
1241 unsigned side2_matches_mbase = (!side2_null && !mbase_null &&
1242 names[0].mode == names[2].mode &&
1243 oideq(&names[0].oid, &names[2].oid));
1244 unsigned sides_match = (!side1_null && !side2_null &&
1245 names[1].mode == names[2].mode &&
1246 oideq(&names[1].oid, &names[2].oid));
d2bc1994 1247
34e557af
EN
1248 /*
1249 * Note: When a path is a file on one side of history and a directory
1250 * in another, we have a directory/file conflict. In such cases, if
1251 * the conflict doesn't resolve from renames and deletions, then we
1252 * always leave directories where they are and move files out of the
1253 * way. Thus, while struct conflict_info has a df_conflict field to
1254 * track such conflicts, we ignore that field for any directories at
1255 * a path and only pay attention to it for files at the given path.
1256 * The fact that we leave directories were they are also means that
1257 * we do not need to worry about getting additional df_conflict
1258 * information propagated from parent directories down to children
1259 * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
1260 * sets a newinfo.df_conflicts field specifically to propagate it).
1261 */
1262 unsigned df_conflict = (filemask != 0) && (dirmask != 0);
1263
d2bc1994
EN
1264 /* n = 3 is a fundamental assumption. */
1265 if (n != 3)
1266 BUG("Called collect_merge_info_callback wrong");
1267
1268 /*
1269 * A bunch of sanity checks verifying that traverse_trees() calls
1270 * us the way I expect. Could just remove these at some point,
1271 * though maybe they are helpful to future code readers.
1272 */
1273 assert(mbase_null == is_null_oid(&names[0].oid));
1274 assert(side1_null == is_null_oid(&names[1].oid));
1275 assert(side2_null == is_null_oid(&names[2].oid));
1276 assert(!mbase_null || !side1_null || !side2_null);
1277 assert(mask > 0 && mask < 8);
1278
34e557af
EN
1279 /* Determine match_mask */
1280 if (side1_matches_mbase)
1281 match_mask = (side2_matches_mbase ? 7 : 3);
1282 else if (side2_matches_mbase)
1283 match_mask = 5;
1284 else if (sides_match)
1285 match_mask = 6;
1286
d2bc1994
EN
1287 /*
1288 * Get the name of the relevant filepath, which we'll pass to
1289 * setup_path_info() for tracking.
1290 */
1291 p = names;
1292 while (!p->mode)
1293 p++;
1294 len = traverse_path_len(info, p->pathlen);
1295
1296 /* +1 in both of the following lines to include the NUL byte */
62a15162 1297 fullpath = mem_pool_alloc(&opt->priv->pool, len + 1);
d2bc1994
EN
1298 make_traverse_path(fullpath, len + 1, info, p->path, p->pathlen);
1299
291f29ca
EN
1300 /*
1301 * If mbase, side1, and side2 all match, we can resolve early. Even
1302 * if these are trees, there will be no renames or anything
1303 * underneath.
1304 */
1305 if (side1_matches_mbase && side2_matches_mbase) {
1306 /* mbase, side1, & side2 all match; use mbase as resolution */
1307 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
528fc51b
EN
1308 names, names+0, mbase_null, 0 /* df_conflict */,
1309 filemask, dirmask, 1 /* resolved */);
291f29ca
EN
1310 return mask;
1311 }
1312
785bf208
EN
1313 /*
1314 * If the sides match, and all three paths are present and are
1315 * files, then we can take either as the resolution. We can't do
1316 * this with trees, because there may be rename sources from the
1317 * merge_base.
1318 */
1319 if (sides_match && filemask == 0x07) {
1320 /* use side1 (== side2) version as resolution */
1321 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1322 names, names+1, side1_null, 0,
1323 filemask, dirmask, 1);
1324 return mask;
1325 }
1326
1327 /*
1328 * If side1 matches mbase and all three paths are present and are
1329 * files, then we can use side2 as the resolution. We cannot
1330 * necessarily do so this for trees, because there may be rename
1331 * destinations within side2.
1332 */
1333 if (side1_matches_mbase && filemask == 0x07) {
1334 /* use side2 version as resolution */
1335 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1336 names, names+2, side2_null, 0,
1337 filemask, dirmask, 1);
1338 return mask;
1339 }
1340
1341 /* Similar to above but swapping sides 1 and 2 */
1342 if (side2_matches_mbase && filemask == 0x07) {
1343 /* use side1 version as resolution */
1344 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1345 names, names+1, side1_null, 0,
291f29ca
EN
1346 filemask, dirmask, 1);
1347 return mask;
1348 }
1349
eb3e3e1d 1350 /*
528fc51b
EN
1351 * Sometimes we can tell that a source path need not be included in
1352 * rename detection -- namely, whenever either
1353 * side1_matches_mbase && side2_null
1354 * or
1355 * side2_matches_mbase && side1_null
1356 * However, we call collect_rename_info() even in those cases,
1357 * because exact renames are cheap and would let us remove both a
1358 * source and destination path. We'll cull the unneeded sources
1359 * later.
eb3e3e1d
EN
1360 */
1361 collect_rename_info(opt, names, dirname, fullpath,
1362 filemask, dirmask, match_mask);
1363
d2bc1994 1364 /*
528fc51b
EN
1365 * None of the special cases above matched, so we have a
1366 * provisional conflict. (Rename detection might allow us to
1367 * unconflict some more cases, but that comes later so all we can
1368 * do now is record the different non-null file hashes.)
d2bc1994 1369 */
98bf9841
EN
1370 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1371 names, NULL, 0, df_conflict, filemask, dirmask, 0);
1372
1373 ci = pi.util;
1374 VERIFY_CI(ci);
34e557af 1375 ci->match_mask = match_mask;
d2bc1994
EN
1376
1377 /* If dirmask, recurse into subdirectories */
1378 if (dirmask) {
1379 struct traverse_info newinfo;
1380 struct tree_desc t[3];
1381 void *buf[3] = {NULL, NULL, NULL};
1382 const char *original_dir_name;
5e1ca57a 1383 int i, ret, side;
d2bc1994 1384
5e1ca57a
EN
1385 /*
1386 * Check for whether we can avoid recursing due to one side
1387 * matching the merge base. The side that does NOT match is
1388 * the one that might have a rename destination we need.
1389 */
1390 assert(!side1_matches_mbase || !side2_matches_mbase);
1391 side = side1_matches_mbase ? MERGE_SIDE2 :
1392 side2_matches_mbase ? MERGE_SIDE1 : MERGE_BASE;
1393 if (filemask == 0 && (dirmask == 2 || dirmask == 4)) {
1394 /*
1395 * Also defer recursing into new directories; set up a
1396 * few variables to let us do so.
1397 */
1398 ci->match_mask = (7 - dirmask);
1399 side = dirmask / 2;
1400 }
1401 if (renames->dir_rename_mask != 0x07 &&
1402 side != MERGE_BASE &&
1403 renames->deferred[side].trivial_merges_okay &&
1404 !strset_contains(&renames->deferred[side].target_dirs,
1405 pi.string)) {
1406 strintmap_set(&renames->deferred[side].possible_trivial_merges,
1407 pi.string, renames->dir_rename_mask);
1408 renames->dir_rename_mask = prev_dir_rename_mask;
1409 return mask;
1410 }
1411
1412 /* We need to recurse */
d2bc1994
EN
1413 ci->match_mask &= filemask;
1414 newinfo = *info;
1415 newinfo.prev = info;
1416 newinfo.name = p->path;
1417 newinfo.namelen = p->pathlen;
1418 newinfo.pathlen = st_add3(newinfo.pathlen, p->pathlen, 1);
34e557af
EN
1419 /*
1420 * If this directory we are about to recurse into cared about
1421 * its parent directory (the current directory) having a D/F
1422 * conflict, then we'd propagate the masks in this way:
1423 * newinfo.df_conflicts |= (mask & ~dirmask);
1424 * But we don't worry about propagating D/F conflicts. (See
1425 * comment near setting of local df_conflict variable near
1426 * the beginning of this function).
1427 */
d2bc1994
EN
1428
1429 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
885f0063
EN
1430 if (i == 1 && side1_matches_mbase)
1431 t[1] = t[0];
1432 else if (i == 2 && side2_matches_mbase)
1433 t[2] = t[0];
1434 else if (i == 2 && sides_match)
1435 t[2] = t[1];
1436 else {
1437 const struct object_id *oid = NULL;
1438 if (dirmask & 1)
1439 oid = &names[i].oid;
1440 buf[i] = fill_tree_descriptor(opt->repo,
1441 t + i, oid);
1442 }
d2bc1994
EN
1443 dirmask >>= 1;
1444 }
1445
1446 original_dir_name = opti->current_dir_name;
98bf9841 1447 opti->current_dir_name = pi.string;
2fd9eda4
EN
1448 if (renames->dir_rename_mask == 0 ||
1449 renames->dir_rename_mask == 0x07)
1450 ret = traverse_trees(NULL, 3, t, &newinfo);
1451 else
1452 ret = traverse_trees_wrapper(NULL, 3, t, &newinfo);
d2bc1994 1453 opti->current_dir_name = original_dir_name;
2fd9eda4 1454 renames->dir_rename_mask = prev_dir_rename_mask;
d2bc1994
EN
1455
1456 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
1457 free(buf[i]);
1458
1459 if (ret < 0)
1460 return -1;
1461 }
1462
1463 return mask;
1464}
1465
7bee6c10
EN
1466static void resolve_trivial_directory_merge(struct conflict_info *ci, int side)
1467{
1468 VERIFY_CI(ci);
1469 assert((side == 1 && ci->match_mask == 5) ||
1470 (side == 2 && ci->match_mask == 3));
1471 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1472 ci->merged.result.mode = ci->stages[side].mode;
1473 ci->merged.is_null = is_null_oid(&ci->stages[side].oid);
1474 ci->match_mask = 0;
1475 ci->merged.clean = 1; /* (ci->filemask == 0); */
1476}
1477
e0ef578e
EN
1478static int handle_deferred_entries(struct merge_options *opt,
1479 struct traverse_info *info)
1480{
1481 struct rename_info *renames = &opt->priv->renames;
1482 struct hashmap_iter iter;
1483 struct strmap_entry *entry;
1484 int side, ret = 0;
8b09a900 1485 int path_count_before, path_count_after = 0;
e0ef578e 1486
8b09a900 1487 path_count_before = strmap_get_size(&opt->priv->paths);
e0ef578e 1488 for (side = MERGE_SIDE1; side <= MERGE_SIDE2; side++) {
7bee6c10
EN
1489 unsigned optimization_okay = 1;
1490 struct strintmap copy;
1491
1492 /* Loop over the set of paths we need to know rename info for */
1493 strset_for_each_entry(&renames->relevant_sources[side],
1494 &iter, entry) {
1495 char *rename_target, *dir, *dir_marker;
1496 struct strmap_entry *e;
1497
1498 /*
1499 * If we don't know delete/rename info for this path,
1500 * then we need to recurse into all trees to get all
1501 * adds to make sure we have it.
1502 */
1503 if (strset_contains(&renames->cached_irrelevant[side],
1504 entry->key))
1505 continue;
1506 e = strmap_get_entry(&renames->cached_pairs[side],
1507 entry->key);
1508 if (!e) {
1509 optimization_okay = 0;
1510 break;
1511 }
1512
1513 /* If this is a delete, we have enough info already */
1514 rename_target = e->value;
1515 if (!rename_target)
1516 continue;
1517
1518 /* If we already walked the rename target, we're good */
1519 if (strmap_contains(&opt->priv->paths, rename_target))
1520 continue;
1521
1522 /*
1523 * Otherwise, we need to get a list of directories that
1524 * will need to be recursed into to get this
1525 * rename_target.
1526 */
1527 dir = xstrdup(rename_target);
1528 while ((dir_marker = strrchr(dir, '/'))) {
1529 *dir_marker = '\0';
1530 if (strset_contains(&renames->deferred[side].target_dirs,
1531 dir))
1532 break;
1533 strset_add(&renames->deferred[side].target_dirs,
1534 dir);
1535 }
1536 free(dir);
1537 }
1538 renames->deferred[side].trivial_merges_okay = optimization_okay;
1539 /*
1540 * We need to recurse into any directories in
1541 * possible_trivial_merges[side] found in target_dirs[side].
1542 * But when we recurse, we may need to queue up some of the
1543 * subdirectories for possible_trivial_merges[side]. Since
1544 * we can't safely iterate through a hashmap while also adding
1545 * entries, move the entries into 'copy', iterate over 'copy',
1546 * and then we'll also iterate anything added into
1547 * possible_trivial_merges[side] once this loop is done.
1548 */
1549 copy = renames->deferred[side].possible_trivial_merges;
1550 strintmap_init_with_options(&renames->deferred[side].possible_trivial_merges,
1551 0,
62a15162 1552 &opt->priv->pool,
7bee6c10
EN
1553 0);
1554 strintmap_for_each_entry(&copy, &iter, entry) {
e0ef578e
EN
1555 const char *path = entry->key;
1556 unsigned dir_rename_mask = (intptr_t)entry->value;
1557 struct conflict_info *ci;
1558 unsigned dirmask;
1559 struct tree_desc t[3];
1560 void *buf[3] = {NULL,};
1561 int i;
1562
1563 ci = strmap_get(&opt->priv->paths, path);
1564 VERIFY_CI(ci);
1565 dirmask = ci->dirmask;
1566
7bee6c10
EN
1567 if (optimization_okay &&
1568 !strset_contains(&renames->deferred[side].target_dirs,
1569 path)) {
1570 resolve_trivial_directory_merge(ci, side);
1571 continue;
1572 }
1573
e0ef578e
EN
1574 info->name = path;
1575 info->namelen = strlen(path);
1576 info->pathlen = info->namelen + 1;
1577
1578 for (i = 0; i < 3; i++, dirmask >>= 1) {
1579 if (i == 1 && ci->match_mask == 3)
1580 t[1] = t[0];
1581 else if (i == 2 && ci->match_mask == 5)
1582 t[2] = t[0];
1583 else if (i == 2 && ci->match_mask == 6)
1584 t[2] = t[1];
1585 else {
1586 const struct object_id *oid = NULL;
1587 if (dirmask & 1)
1588 oid = &ci->stages[i].oid;
1589 buf[i] = fill_tree_descriptor(opt->repo,
1590 t+i, oid);
1591 }
1592 }
1593
1594 ci->match_mask &= ci->filemask;
1595 opt->priv->current_dir_name = path;
1596 renames->dir_rename_mask = dir_rename_mask;
1597 if (renames->dir_rename_mask == 0 ||
1598 renames->dir_rename_mask == 0x07)
1599 ret = traverse_trees(NULL, 3, t, info);
1600 else
1601 ret = traverse_trees_wrapper(NULL, 3, t, info);
1602
1603 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
1604 free(buf[i]);
1605
1606 if (ret < 0)
1607 return ret;
1608 }
7bee6c10
EN
1609 strintmap_clear(&copy);
1610 strintmap_for_each_entry(&renames->deferred[side].possible_trivial_merges,
1611 &iter, entry) {
1612 const char *path = entry->key;
1613 struct conflict_info *ci;
1614
1615 ci = strmap_get(&opt->priv->paths, path);
1616 VERIFY_CI(ci);
1617
1618 assert(renames->deferred[side].trivial_merges_okay &&
1619 !strset_contains(&renames->deferred[side].target_dirs,
1620 path));
1621 resolve_trivial_directory_merge(ci, side);
1622 }
8b09a900
EN
1623 if (!optimization_okay || path_count_after)
1624 path_count_after = strmap_get_size(&opt->priv->paths);
e0ef578e 1625 }
8b09a900
EN
1626 if (path_count_after) {
1627 /*
1628 * The choice of wanted_factor here does not affect
1629 * correctness, only performance. When the
1630 * path_count_after / path_count_before
1631 * ratio is high, redoing after renames is a big
1632 * performance boost. I suspect that redoing is a wash
1633 * somewhere near a value of 2, and below that redoing will
1634 * slow things down. I applied a fudge factor and picked
1635 * 3; see the commit message when this was introduced for
1636 * back of the envelope calculations for this ratio.
1637 */
1638 const int wanted_factor = 3;
1639
1640 /* We should only redo collect_merge_info one time */
1641 assert(renames->redo_after_renames == 0);
1642
1643 if (path_count_after / path_count_before >= wanted_factor) {
1644 renames->redo_after_renames = 1;
1645 renames->cached_pairs_valid_side = -1;
1646 }
1647 } else if (renames->redo_after_renames == 2)
1648 renames->redo_after_renames = 0;
e0ef578e
EN
1649 return ret;
1650}
1651
231e2dd4
EN
1652static int collect_merge_info(struct merge_options *opt,
1653 struct tree *merge_base,
1654 struct tree *side1,
1655 struct tree *side2)
1656{
d2bc1994
EN
1657 int ret;
1658 struct tree_desc t[3];
1659 struct traverse_info info;
d2bc1994 1660
05b85c6e
EN
1661 opt->priv->toplevel_dir = "";
1662 opt->priv->current_dir_name = opt->priv->toplevel_dir;
1663 setup_traverse_info(&info, opt->priv->toplevel_dir);
d2bc1994
EN
1664 info.fn = collect_merge_info_callback;
1665 info.data = opt;
1666 info.show_all_errors = 1;
1667
1668 parse_tree(merge_base);
1669 parse_tree(side1);
1670 parse_tree(side2);
1671 init_tree_desc(t + 0, merge_base->buffer, merge_base->size);
1672 init_tree_desc(t + 1, side1->buffer, side1->size);
1673 init_tree_desc(t + 2, side2->buffer, side2->size);
1674
557ac035 1675 trace2_region_enter("merge", "traverse_trees", opt->repo);
d2bc1994 1676 ret = traverse_trees(NULL, 3, t, &info);
5e1ca57a
EN
1677 if (ret == 0)
1678 ret = handle_deferred_entries(opt, &info);
557ac035 1679 trace2_region_leave("merge", "traverse_trees", opt->repo);
d2bc1994
EN
1680
1681 return ret;
231e2dd4
EN
1682}
1683
04af1879
EN
1684/*** Function Grouping: functions related to threeway content merges ***/
1685
c73cda76
EN
1686static int find_first_merges(struct repository *repo,
1687 const char *path,
1688 struct commit *a,
1689 struct commit *b,
1690 struct object_array *result)
1691{
4204cd59
EN
1692 int i, j;
1693 struct object_array merges = OBJECT_ARRAY_INIT;
1694 struct commit *commit;
1695 int contains_another;
1696
1697 char merged_revision[GIT_MAX_HEXSZ + 2];
1698 const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1699 "--all", merged_revision, NULL };
1700 struct rev_info revs;
1701 struct setup_revision_opt rev_opts;
1702
1703 memset(result, 0, sizeof(struct object_array));
1704 memset(&rev_opts, 0, sizeof(rev_opts));
1705
1706 /* get all revisions that merge commit a */
1707 xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
1708 oid_to_hex(&a->object.oid));
1709 repo_init_revisions(repo, &revs, NULL);
4204cd59
EN
1710 /* FIXME: can't handle linked worktrees in submodules yet */
1711 revs.single_worktree = path != NULL;
1712 setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1713
1714 /* save all revisions from the above list that contain b */
1715 if (prepare_revision_walk(&revs))
1716 die("revision walk setup failed");
1717 while ((commit = get_revision(&revs)) != NULL) {
1718 struct object *o = &(commit->object);
10a0d6ae 1719 if (repo_in_merge_bases(repo, b, commit))
4204cd59
EN
1720 add_object_array(o, NULL, &merges);
1721 }
1722 reset_revision_walk();
1723
1724 /* Now we've got all merges that contain a and b. Prune all
1725 * merges that contain another found merge and save them in
1726 * result.
1727 */
1728 for (i = 0; i < merges.nr; i++) {
1729 struct commit *m1 = (struct commit *) merges.objects[i].item;
1730
1731 contains_another = 0;
1732 for (j = 0; j < merges.nr; j++) {
1733 struct commit *m2 = (struct commit *) merges.objects[j].item;
10a0d6ae 1734 if (i != j && repo_in_merge_bases(repo, m2, m1)) {
4204cd59
EN
1735 contains_another = 1;
1736 break;
1737 }
1738 }
1739
1740 if (!contains_another)
1741 add_object_array(merges.objects[i].item, NULL, result);
1742 }
1743
1744 object_array_clear(&merges);
2108fe4a 1745 release_revisions(&revs);
4204cd59 1746 return result->nr;
c73cda76
EN
1747}
1748
62fdec17
EN
1749static int merge_submodule(struct merge_options *opt,
1750 const char *path,
1751 const struct object_id *o,
1752 const struct object_id *a,
1753 const struct object_id *b,
1754 struct object_id *result)
1755{
10a0d6ae
JT
1756 struct repository subrepo;
1757 struct strbuf sb = STRBUF_INIT;
1758 int ret = 0;
c73cda76
EN
1759 struct commit *commit_o, *commit_a, *commit_b;
1760 int parent_count;
1761 struct object_array merges;
c73cda76
EN
1762
1763 int i;
1764 int search = !opt->priv->call_depth;
4057523a 1765 int sub_not_initialized = 1;
34ce504a 1766 int sub_flag = CONFLICT_SUBMODULE_FAILED_TO_MERGE;
c73cda76
EN
1767
1768 /* store fallback answer in result in case we fail */
1769 oidcpy(result, opt->priv->call_depth ? o : a);
1770
1771 /* we can not handle deletion conflicts */
4057523a
CW
1772 if (is_null_oid(a) || is_null_oid(b))
1773 BUG("submodule deleted on one side; this should be handled outside of merge_submodule()");
c73cda76 1774
4057523a
CW
1775 if ((sub_not_initialized = repo_submodule_init(&subrepo,
1776 opt->repo, path, null_oid()))) {
cb260775
EN
1777 path_msg(opt, CONFLICT_SUBMODULE_NOT_INITIALIZED, 0,
1778 path, NULL, NULL, NULL,
1779 _("Failed to merge submodule %s (not checked out)"),
1780 path);
4057523a
CW
1781 sub_flag = CONFLICT_SUBMODULE_NOT_INITIALIZED;
1782 goto cleanup;
1783 }
1784
1785 if (is_null_oid(o)) {
1786 path_msg(opt, CONFLICT_SUBMODULE_NULL_MERGE_BASE, 0,
1787 path, NULL, NULL, NULL,
1788 _("Failed to merge submodule %s (no merge base)"),
1789 path);
1790 goto cleanup;
10a0d6ae
JT
1791 }
1792
1793 if (!(commit_o = lookup_commit_reference(&subrepo, o)) ||
1794 !(commit_a = lookup_commit_reference(&subrepo, a)) ||
1795 !(commit_b = lookup_commit_reference(&subrepo, b))) {
cb260775
EN
1796 path_msg(opt, CONFLICT_SUBMODULE_HISTORY_NOT_AVAILABLE, 0,
1797 path, NULL, NULL, NULL,
c73cda76
EN
1798 _("Failed to merge submodule %s (commits not present)"),
1799 path);
4057523a 1800 sub_flag = CONFLICT_SUBMODULE_HISTORY_NOT_AVAILABLE;
10a0d6ae 1801 goto cleanup;
c73cda76
EN
1802 }
1803
1804 /* check whether both changes are forward */
10a0d6ae
JT
1805 if (!repo_in_merge_bases(&subrepo, commit_o, commit_a) ||
1806 !repo_in_merge_bases(&subrepo, commit_o, commit_b)) {
cb260775
EN
1807 path_msg(opt, CONFLICT_SUBMODULE_MAY_HAVE_REWINDS, 0,
1808 path, NULL, NULL, NULL,
c73cda76
EN
1809 _("Failed to merge submodule %s "
1810 "(commits don't follow merge-base)"),
1811 path);
10a0d6ae 1812 goto cleanup;
c73cda76
EN
1813 }
1814
1815 /* Case #1: a is contained in b or vice versa */
10a0d6ae 1816 if (repo_in_merge_bases(&subrepo, commit_a, commit_b)) {
c73cda76 1817 oidcpy(result, b);
cb260775
EN
1818 path_msg(opt, INFO_SUBMODULE_FAST_FORWARDING, 1,
1819 path, NULL, NULL, NULL,
c73cda76
EN
1820 _("Note: Fast-forwarding submodule %s to %s"),
1821 path, oid_to_hex(b));
10a0d6ae
JT
1822 ret = 1;
1823 goto cleanup;
c73cda76 1824 }
10a0d6ae 1825 if (repo_in_merge_bases(&subrepo, commit_b, commit_a)) {
c73cda76 1826 oidcpy(result, a);
cb260775
EN
1827 path_msg(opt, INFO_SUBMODULE_FAST_FORWARDING, 1,
1828 path, NULL, NULL, NULL,
c73cda76
EN
1829 _("Note: Fast-forwarding submodule %s to %s"),
1830 path, oid_to_hex(a));
10a0d6ae
JT
1831 ret = 1;
1832 goto cleanup;
c73cda76
EN
1833 }
1834
1835 /*
1836 * Case #2: There are one or more merges that contain a and b in
1837 * the submodule. If there is only one, then present it as a
1838 * suggestion to the user, but leave it marked unmerged so the
1839 * user needs to confirm the resolution.
1840 */
1841
1842 /* Skip the search if makes no sense to the calling context. */
1843 if (!search)
10a0d6ae 1844 goto cleanup;
c73cda76
EN
1845
1846 /* find commit which merges them */
10a0d6ae 1847 parent_count = find_first_merges(&subrepo, path, commit_a, commit_b,
c73cda76
EN
1848 &merges);
1849 switch (parent_count) {
1850 case 0:
cb260775
EN
1851 path_msg(opt, CONFLICT_SUBMODULE_FAILED_TO_MERGE, 0,
1852 path, NULL, NULL, NULL,
1853 _("Failed to merge submodule %s"), path);
c73cda76
EN
1854 break;
1855
1856 case 1:
155b517d 1857 format_commit(&sb, 4, &subrepo,
c73cda76 1858 (struct commit *)merges.objects[0].item);
cb260775
EN
1859 path_msg(opt, CONFLICT_SUBMODULE_FAILED_TO_MERGE_BUT_POSSIBLE_RESOLUTION, 0,
1860 path, NULL, NULL, NULL,
c73cda76 1861 _("Failed to merge submodule %s, but a possible merge "
a4040cfa 1862 "resolution exists: %s"),
c73cda76 1863 path, sb.buf);
c73cda76
EN
1864 strbuf_release(&sb);
1865 break;
1866 default:
1867 for (i = 0; i < merges.nr; i++)
155b517d 1868 format_commit(&sb, 4, &subrepo,
c73cda76 1869 (struct commit *)merges.objects[i].item);
cb260775
EN
1870 path_msg(opt, CONFLICT_SUBMODULE_FAILED_TO_MERGE_BUT_POSSIBLE_RESOLUTION, 0,
1871 path, NULL, NULL, NULL,
c73cda76
EN
1872 _("Failed to merge submodule %s, but multiple "
1873 "possible merges exist:\n%s"), path, sb.buf);
1874 strbuf_release(&sb);
1875 }
1876
1877 object_array_clear(&merges);
10a0d6ae 1878cleanup:
4057523a
CW
1879 if (!opt->priv->call_depth && !ret) {
1880 struct string_list *csub = &opt->priv->conflicted_submodules;
1881 struct conflicted_submodule_item *util;
1882 const char *abbrev;
1883
1884 util = xmalloc(sizeof(*util));
1885 util->flag = sub_flag;
1886 util->abbrev = NULL;
1887 if (!sub_not_initialized) {
1888 abbrev = repo_find_unique_abbrev(&subrepo, b, DEFAULT_ABBREV);
1889 util->abbrev = xstrdup(abbrev);
1890 }
1891 string_list_append(csub, path)->util = util;
1892 }
1893
1894 if (!sub_not_initialized)
1895 repo_clear(&subrepo);
10a0d6ae 1896 return ret;
62fdec17
EN
1897}
1898
1218b3ab
EN
1899static void initialize_attr_index(struct merge_options *opt)
1900{
1901 /*
1902 * The renormalize_buffer() functions require attributes, and
1903 * annoyingly those can only be read from the working tree or from
1904 * an index_state. merge-ort doesn't have an index_state, so we
1905 * generate a fake one containing only attribute information.
1906 */
1907 struct merged_info *mi;
1908 struct index_state *attr_index = &opt->priv->attr_index;
1909 struct cache_entry *ce;
1910
1911 attr_index->initialized = 1;
1912
1913 if (!opt->renormalize)
1914 return;
1915
1916 mi = strmap_get(&opt->priv->paths, GITATTRIBUTES_FILE);
1917 if (!mi)
1918 return;
1919
1920 if (mi->clean) {
1921 int len = strlen(GITATTRIBUTES_FILE);
1922 ce = make_empty_cache_entry(attr_index, len);
1923 ce->ce_mode = create_ce_mode(mi->result.mode);
1924 ce->ce_flags = create_ce_flags(0);
1925 ce->ce_namelen = len;
1926 oidcpy(&ce->oid, &mi->result.oid);
1927 memcpy(ce->name, GITATTRIBUTES_FILE, len);
1928 add_index_entry(attr_index, ce,
1929 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
1930 get_stream_filter(attr_index, GITATTRIBUTES_FILE, &ce->oid);
1931 } else {
1932 int stage, len;
1933 struct conflict_info *ci;
1934
1935 ASSIGN_AND_VERIFY_CI(ci, mi);
1936 for (stage = 0; stage < 3; stage++) {
1937 unsigned stage_mask = (1 << stage);
1938
1939 if (!(ci->filemask & stage_mask))
1940 continue;
1941 len = strlen(GITATTRIBUTES_FILE);
1942 ce = make_empty_cache_entry(attr_index, len);
1943 ce->ce_mode = create_ce_mode(ci->stages[stage].mode);
1944 ce->ce_flags = create_ce_flags(stage);
1945 ce->ce_namelen = len;
1946 oidcpy(&ce->oid, &ci->stages[stage].oid);
1947 memcpy(ce->name, GITATTRIBUTES_FILE, len);
1948 add_index_entry(attr_index, ce,
1949 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
1950 get_stream_filter(attr_index, GITATTRIBUTES_FILE,
1951 &ce->oid);
1952 }
1953 }
1954}
1955
62fdec17
EN
1956static int merge_3way(struct merge_options *opt,
1957 const char *path,
1958 const struct object_id *o,
1959 const struct object_id *a,
1960 const struct object_id *b,
1961 const char *pathnames[3],
1962 const int extra_marker_size,
1963 mmbuffer_t *result_buf)
1964{
f591c472
EN
1965 mmfile_t orig, src1, src2;
1966 struct ll_merge_options ll_opts = {0};
1967 char *base, *name1, *name2;
35f69671 1968 enum ll_merge_result merge_status;
f591c472 1969
1218b3ab
EN
1970 if (!opt->priv->attr_index.initialized)
1971 initialize_attr_index(opt);
1972
f591c472
EN
1973 ll_opts.renormalize = opt->renormalize;
1974 ll_opts.extra_marker_size = extra_marker_size;
1975 ll_opts.xdl_opts = opt->xdl_opts;
1976
1977 if (opt->priv->call_depth) {
1978 ll_opts.virtual_ancestor = 1;
1979 ll_opts.variant = 0;
1980 } else {
1981 switch (opt->recursive_variant) {
1982 case MERGE_VARIANT_OURS:
1983 ll_opts.variant = XDL_MERGE_FAVOR_OURS;
1984 break;
1985 case MERGE_VARIANT_THEIRS:
1986 ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
1987 break;
1988 default:
1989 ll_opts.variant = 0;
1990 break;
1991 }
1992 }
1993
1994 assert(pathnames[0] && pathnames[1] && pathnames[2] && opt->ancestor);
1995 if (pathnames[0] == pathnames[1] && pathnames[1] == pathnames[2]) {
1996 base = mkpathdup("%s", opt->ancestor);
1997 name1 = mkpathdup("%s", opt->branch1);
1998 name2 = mkpathdup("%s", opt->branch2);
1999 } else {
2000 base = mkpathdup("%s:%s", opt->ancestor, pathnames[0]);
2001 name1 = mkpathdup("%s:%s", opt->branch1, pathnames[1]);
2002 name2 = mkpathdup("%s:%s", opt->branch2, pathnames[2]);
2003 }
2004
2005 read_mmblob(&orig, o);
2006 read_mmblob(&src1, a);
2007 read_mmblob(&src2, b);
2008
2009 merge_status = ll_merge(result_buf, path, &orig, base,
2010 &src1, name1, &src2, name2,
1218b3ab 2011 &opt->priv->attr_index, &ll_opts);
35f69671 2012 if (merge_status == LL_MERGE_BINARY_CONFLICT)
cb260775
EN
2013 path_msg(opt, CONFLICT_BINARY, 0,
2014 path, NULL, NULL, NULL,
24dbdab5
EN
2015 "warning: Cannot merge binary files: %s (%s vs. %s)",
2016 path, name1, name2);
f591c472
EN
2017
2018 free(base);
2019 free(name1);
2020 free(name2);
2021 free(orig.ptr);
2022 free(src1.ptr);
2023 free(src2.ptr);
2024 return merge_status;
62fdec17
EN
2025}
2026
e2e9dc03
EN
2027static int handle_content_merge(struct merge_options *opt,
2028 const char *path,
2029 const struct version_info *o,
2030 const struct version_info *a,
2031 const struct version_info *b,
2032 const char *pathnames[3],
2033 const int extra_marker_size,
2034 struct version_info *result)
2035{
991bbdca 2036 /*
62fdec17
EN
2037 * path is the target location where we want to put the file, and
2038 * is used to determine any normalization rules in ll_merge.
2039 *
2040 * The normal case is that path and all entries in pathnames are
2041 * identical, though renames can affect which path we got one of
2042 * the three blobs to merge on various sides of history.
2043 *
2044 * extra_marker_size is the amount to extend conflict markers in
2045 * ll_merge; this is neeed if we have content merges of content
2046 * merges, which happens for example with rename/rename(2to1) and
2047 * rename/add conflicts.
2048 */
2049 unsigned clean = 1;
2050
2051 /*
2052 * handle_content_merge() needs both files to be of the same type, i.e.
2053 * both files OR both submodules OR both symlinks. Conflicting types
2054 * needs to be handled elsewhere.
991bbdca 2055 */
62fdec17
EN
2056 assert((S_IFMT & a->mode) == (S_IFMT & b->mode));
2057
2058 /* Merge modes */
2059 if (a->mode == b->mode || a->mode == o->mode)
2060 result->mode = b->mode;
2061 else {
2062 /* must be the 100644/100755 case */
2063 assert(S_ISREG(a->mode));
2064 result->mode = a->mode;
2065 clean = (b->mode == o->mode);
2066 /*
2067 * FIXME: If opt->priv->call_depth && !clean, then we really
2068 * should not make result->mode match either a->mode or
2069 * b->mode; that causes t6036 "check conflicting mode for
2070 * regular file" to fail. It would be best to use some other
2071 * mode, but we'll confuse all kinds of stuff if we use one
2072 * where S_ISREG(result->mode) isn't true, and if we use
2073 * something like 0100666, then tree-walk.c's calls to
2074 * canon_mode() will just normalize that to 100644 for us and
2075 * thus not solve anything.
2076 *
2077 * Figure out if there's some kind of way we can work around
2078 * this...
2079 */
2080 }
2081
2082 /*
2083 * Trivial oid merge.
2084 *
2085 * Note: While one might assume that the next four lines would
2086 * be unnecessary due to the fact that match_mask is often
2087 * setup and already handled, renames don't always take care
2088 * of that.
2089 */
2090 if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
2091 oidcpy(&result->oid, &b->oid);
2092 else if (oideq(&b->oid, &o->oid))
2093 oidcpy(&result->oid, &a->oid);
2094
2095 /* Remaining rules depend on file vs. submodule vs. symlink. */
2096 else if (S_ISREG(a->mode)) {
2097 mmbuffer_t result_buf;
2098 int ret = 0, merge_status;
2099 int two_way;
2100
2101 /*
2102 * If 'o' is different type, treat it as null so we do a
2103 * two-way merge.
2104 */
2105 two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
2106
2107 merge_status = merge_3way(opt, path,
14228447 2108 two_way ? null_oid() : &o->oid,
62fdec17
EN
2109 &a->oid, &b->oid,
2110 pathnames, extra_marker_size,
2111 &result_buf);
2112
2113 if ((merge_status < 0) || !result_buf.ptr)
2114 ret = err(opt, _("Failed to execute internal merge"));
2115
2116 if (!ret &&
2117 write_object_file(result_buf.ptr, result_buf.size,
c80d226a 2118 OBJ_BLOB, &result->oid))
62fdec17
EN
2119 ret = err(opt, _("Unable to add %s to database"),
2120 path);
2121
2122 free(result_buf.ptr);
2123 if (ret)
2124 return -1;
2125 clean &= (merge_status == 0);
cb260775
EN
2126 path_msg(opt, INFO_AUTO_MERGING, 1, path, NULL, NULL, NULL,
2127 _("Auto-merging %s"), path);
62fdec17
EN
2128 } else if (S_ISGITLINK(a->mode)) {
2129 int two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
2130 clean = merge_submodule(opt, pathnames[0],
14228447 2131 two_way ? null_oid() : &o->oid,
62fdec17
EN
2132 &a->oid, &b->oid, &result->oid);
2133 if (opt->priv->call_depth && two_way && !clean) {
2134 result->mode = o->mode;
2135 oidcpy(&result->oid, &o->oid);
2136 }
2137 } else if (S_ISLNK(a->mode)) {
2138 if (opt->priv->call_depth) {
2139 clean = 0;
2140 result->mode = o->mode;
2141 oidcpy(&result->oid, &o->oid);
2142 } else {
2143 switch (opt->recursive_variant) {
2144 case MERGE_VARIANT_NORMAL:
2145 clean = 0;
2146 oidcpy(&result->oid, &a->oid);
2147 break;
2148 case MERGE_VARIANT_OURS:
2149 oidcpy(&result->oid, &a->oid);
2150 break;
2151 case MERGE_VARIANT_THEIRS:
2152 oidcpy(&result->oid, &b->oid);
2153 break;
2154 }
2155 }
2156 } else
2157 BUG("unsupported object type in the tree: %06o for %s",
2158 a->mode, path);
2159
991bbdca 2160 return clean;
e2e9dc03
EN
2161}
2162
04af1879
EN
2163/*** Function Grouping: functions related to detect_and_process_renames(), ***
2164 *** which are split into directory and regular rename detection sections. ***/
2165
2166/*** Function Grouping: functions related to directory rename detection ***/
2167
fa5e06d6
EN
2168struct collision_info {
2169 struct string_list source_files;
2170 unsigned reported_already:1;
2171};
2172
d9d015df
EN
2173/*
2174 * Return a new string that replaces the beginning portion (which matches
2175 * rename_info->key), with rename_info->util.new_dir. In perl-speak:
2176 * new_path_name = (old_path =~ s/rename_info->key/rename_info->value/);
2177 * NOTE:
2178 * Caller must ensure that old_path starts with rename_info->key + '/'.
2179 */
2180static char *apply_dir_rename(struct strmap_entry *rename_info,
2181 const char *old_path)
2182{
fbcfc0cc
EN
2183 struct strbuf new_path = STRBUF_INIT;
2184 const char *old_dir = rename_info->key;
2185 const char *new_dir = rename_info->value;
2186 int oldlen, newlen, new_dir_len;
2187
2188 oldlen = strlen(old_dir);
2189 if (*new_dir == '\0')
2190 /*
2191 * If someone renamed/merged a subdirectory into the root
2192 * directory (e.g. 'some/subdir' -> ''), then we want to
2193 * avoid returning
2194 * '' + '/filename'
2195 * as the rename; we need to make old_path + oldlen advance
2196 * past the '/' character.
2197 */
2198 oldlen++;
2199 new_dir_len = strlen(new_dir);
2200 newlen = new_dir_len + (strlen(old_path) - oldlen) + 1;
2201 strbuf_grow(&new_path, newlen);
2202 strbuf_add(&new_path, new_dir, new_dir_len);
2203 strbuf_addstr(&new_path, &old_path[oldlen]);
2204
2205 return strbuf_detach(&new_path, NULL);
d9d015df
EN
2206}
2207
bea43365
EN
2208static int path_in_way(struct strmap *paths, const char *path, unsigned side_mask)
2209{
2210 struct merged_info *mi = strmap_get(paths, path);
2211 struct conflict_info *ci;
2212 if (!mi)
2213 return 0;
2214 INITIALIZE_CI(ci, mi);
2215 return mi->clean || (side_mask & (ci->filemask | ci->dirmask));
2216}
2217
47325e85
EN
2218/*
2219 * See if there is a directory rename for path, and if there are any file
2220 * level conflicts on the given side for the renamed location. If there is
2221 * a rename and there are no conflicts, return the new name. Otherwise,
2222 * return NULL.
2223 */
2224static char *handle_path_level_conflicts(struct merge_options *opt,
2225 const char *path,
2226 unsigned side_index,
2227 struct strmap_entry *rename_info,
2228 struct strmap *collisions)
2229{
bea43365
EN
2230 char *new_path = NULL;
2231 struct collision_info *c_info;
2232 int clean = 1;
2233 struct strbuf collision_paths = STRBUF_INIT;
2234
2235 /*
2236 * entry has the mapping of old directory name to new directory name
2237 * that we want to apply to path.
2238 */
2239 new_path = apply_dir_rename(rename_info, path);
2240 if (!new_path)
2241 BUG("Failed to apply directory rename!");
2242
2243 /*
2244 * The caller needs to have ensured that it has pre-populated
2245 * collisions with all paths that map to new_path. Do a quick check
2246 * to ensure that's the case.
2247 */
2248 c_info = strmap_get(collisions, new_path);
afe8a907 2249 if (!c_info)
bea43365
EN
2250 BUG("c_info is NULL");
2251
2252 /*
2253 * Check for one-sided add/add/.../add conflicts, i.e.
2254 * where implicit renames from the other side doing
2255 * directory rename(s) can affect this side of history
2256 * to put multiple paths into the same location. Warn
2257 * and bail on directory renames for such paths.
2258 */
2259 if (c_info->reported_already) {
2260 clean = 0;
2261 } else if (path_in_way(&opt->priv->paths, new_path, 1 << side_index)) {
2262 c_info->reported_already = 1;
2263 strbuf_add_separated_string_list(&collision_paths, ", ",
2264 &c_info->source_files);
cb260775
EN
2265 path_msg(opt, CONFLICT_DIR_RENAME_FILE_IN_WAY, 0,
2266 new_path, NULL, NULL, &c_info->source_files,
2267 _("CONFLICT (implicit dir rename): Existing "
2268 "file/dir at %s in the way of implicit "
2269 "directory rename(s) putting the following "
2270 "path(s) there: %s."),
2271 new_path, collision_paths.buf);
bea43365
EN
2272 clean = 0;
2273 } else if (c_info->source_files.nr > 1) {
2274 c_info->reported_already = 1;
2275 strbuf_add_separated_string_list(&collision_paths, ", ",
2276 &c_info->source_files);
cb260775
EN
2277 path_msg(opt, CONFLICT_DIR_RENAME_COLLISION, 0,
2278 new_path, NULL, NULL, &c_info->source_files,
2279 _("CONFLICT (implicit dir rename): Cannot map "
2280 "more than one path to %s; implicit directory "
2281 "renames tried to put these paths there: %s"),
2282 new_path, collision_paths.buf);
bea43365
EN
2283 clean = 0;
2284 }
2285
2286 /* Free memory we no longer need */
2287 strbuf_release(&collision_paths);
2288 if (!clean && new_path) {
2289 free(new_path);
2290 return NULL;
2291 }
2292
2293 return new_path;
47325e85
EN
2294}
2295
112e1112
EN
2296static void get_provisional_directory_renames(struct merge_options *opt,
2297 unsigned side,
2298 int *clean)
2299{
04264d40
EN
2300 struct hashmap_iter iter;
2301 struct strmap_entry *entry;
2302 struct rename_info *renames = &opt->priv->renames;
2303
04264d40
EN
2304 /*
2305 * Collapse
2306 * dir_rename_count: old_directory -> {new_directory -> count}
2307 * down to
2308 * dir_renames: old_directory -> best_new_directory
2309 * where best_new_directory is the one with the unique highest count.
2310 */
2311 strmap_for_each_entry(&renames->dir_rename_count[side], &iter, entry) {
2312 const char *source_dir = entry->key;
2313 struct strintmap *counts = entry->value;
2314 struct hashmap_iter count_iter;
2315 struct strmap_entry *count_entry;
2316 int max = 0;
2317 int bad_max = 0;
2318 const char *best = NULL;
2319
2320 strintmap_for_each_entry(counts, &count_iter, count_entry) {
2321 const char *target_dir = count_entry->key;
2322 intptr_t count = (intptr_t)count_entry->value;
2323
2324 if (count == max)
2325 bad_max = max;
2326 else if (count > max) {
2327 max = count;
2328 best = target_dir;
2329 }
2330 }
2331
bf238b71
EN
2332 if (max == 0)
2333 continue;
2334
04264d40 2335 if (bad_max == max) {
cb260775
EN
2336 path_msg(opt, CONFLICT_DIR_RENAME_SPLIT, 0,
2337 source_dir, NULL, NULL, NULL,
2338 _("CONFLICT (directory rename split): "
2339 "Unclear where to rename %s to; it was "
2340 "renamed to multiple other directories, "
2341 "with no destination getting a majority of "
2342 "the files."),
2343 source_dir);
41376b58 2344 *clean = 0;
04264d40
EN
2345 } else {
2346 strmap_put(&renames->dir_renames[side],
2347 source_dir, (void*)best);
2348 }
2349 }
112e1112
EN
2350}
2351
2352static void handle_directory_level_conflicts(struct merge_options *opt)
2353{
98d0d081
EN
2354 struct hashmap_iter iter;
2355 struct strmap_entry *entry;
2356 struct string_list duplicated = STRING_LIST_INIT_NODUP;
2357 struct rename_info *renames = &opt->priv->renames;
2358 struct strmap *side1_dir_renames = &renames->dir_renames[MERGE_SIDE1];
2359 struct strmap *side2_dir_renames = &renames->dir_renames[MERGE_SIDE2];
2360 int i;
2361
2362 strmap_for_each_entry(side1_dir_renames, &iter, entry) {
2363 if (strmap_contains(side2_dir_renames, entry->key))
2364 string_list_append(&duplicated, entry->key);
2365 }
2366
2367 for (i = 0; i < duplicated.nr; i++) {
2368 strmap_remove(side1_dir_renames, duplicated.items[i].string, 0);
2369 strmap_remove(side2_dir_renames, duplicated.items[i].string, 0);
2370 }
2371 string_list_clear(&duplicated, 0);
112e1112
EN
2372}
2373
d9d015df
EN
2374static struct strmap_entry *check_dir_renamed(const char *path,
2375 struct strmap *dir_renames)
2376{
fbcfc0cc
EN
2377 char *temp = xstrdup(path);
2378 char *end;
2379 struct strmap_entry *e = NULL;
2380
2381 while ((end = strrchr(temp, '/'))) {
2382 *end = '\0';
2383 e = strmap_get_entry(dir_renames, temp);
2384 if (e)
2385 break;
2386 }
2387 free(temp);
2388 return e;
d9d015df
EN
2389}
2390
fa5e06d6
EN
2391static void compute_collisions(struct strmap *collisions,
2392 struct strmap *dir_renames,
2393 struct diff_queue_struct *pairs)
2394{
d9d015df
EN
2395 int i;
2396
2397 strmap_init_with_options(collisions, NULL, 0);
2398 if (strmap_empty(dir_renames))
2399 return;
2400
2401 /*
2402 * Multiple files can be mapped to the same path due to directory
2403 * renames done by the other side of history. Since that other
2404 * side of history could have merged multiple directories into one,
2405 * if our side of history added the same file basename to each of
2406 * those directories, then all N of them would get implicitly
2407 * renamed by the directory rename detection into the same path,
2408 * and we'd get an add/add/.../add conflict, and all those adds
2409 * from *this* side of history. This is not representable in the
2410 * index, and users aren't going to easily be able to make sense of
2411 * it. So we need to provide a good warning about what's
2412 * happening, and fall back to no-directory-rename detection
2413 * behavior for those paths.
2414 *
2415 * See testcases 9e and all of section 5 from t6043 for examples.
2416 */
2417 for (i = 0; i < pairs->nr; ++i) {
2418 struct strmap_entry *rename_info;
2419 struct collision_info *collision_info;
2420 char *new_path;
2421 struct diff_filepair *pair = pairs->queue[i];
2422
2423 if (pair->status != 'A' && pair->status != 'R')
2424 continue;
2425 rename_info = check_dir_renamed(pair->two->path, dir_renames);
2426 if (!rename_info)
2427 continue;
2428
2429 new_path = apply_dir_rename(rename_info, pair->two->path);
2430 assert(new_path);
2431 collision_info = strmap_get(collisions, new_path);
2432 if (collision_info) {
2433 free(new_path);
2434 } else {
ca56dadb 2435 CALLOC_ARRAY(collision_info, 1);
bc40dfb1 2436 string_list_init_nodup(&collision_info->source_files);
d9d015df
EN
2437 strmap_put(collisions, new_path, collision_info);
2438 }
2439 string_list_insert(&collision_info->source_files,
2440 pair->two->path);
2441 }
fa5e06d6
EN
2442}
2443
6dd1f0e9
EN
2444static void free_collisions(struct strmap *collisions)
2445{
2446 struct hashmap_iter iter;
2447 struct strmap_entry *entry;
2448
2449 /* Free each value in the collisions map */
2450 strmap_for_each_entry(collisions, &iter, entry) {
2451 struct collision_info *info = entry->value;
2452 string_list_clear(&info->source_files, 0);
2453 }
2454 /*
2455 * In compute_collisions(), we set collisions.strdup_strings to 0
2456 * so that we wouldn't have to make another copy of the new_path
2457 * allocated by apply_dir_rename(). But now that we've used them
2458 * and have no other references to these strings, it is time to
2459 * deallocate them.
2460 */
2461 free_strmap_strings(collisions);
2462 strmap_clear(collisions, 1);
2463}
2464
fa5e06d6
EN
2465static char *check_for_directory_rename(struct merge_options *opt,
2466 const char *path,
2467 unsigned side_index,
2468 struct strmap *dir_renames,
2469 struct strmap *dir_rename_exclusions,
2470 struct strmap *collisions,
2471 int *clean_merge)
2472{
51e41e4e 2473 char *new_path;
47325e85 2474 struct strmap_entry *rename_info;
51e41e4e 2475 struct strmap_entry *otherinfo;
47325e85 2476 const char *new_dir;
751e1654 2477 int other_side = 3 - side_index;
47325e85 2478
751e1654
EN
2479 /*
2480 * Cases where we don't have or don't want a directory rename for
2481 * this path.
2482 */
47325e85 2483 if (strmap_empty(dir_renames))
51e41e4e 2484 return NULL;
751e1654
EN
2485 if (strmap_get(&collisions[other_side], path))
2486 return NULL;
47325e85
EN
2487 rename_info = check_dir_renamed(path, dir_renames);
2488 if (!rename_info)
51e41e4e 2489 return NULL;
47325e85
EN
2490
2491 /*
2492 * This next part is a little weird. We do not want to do an
2493 * implicit rename into a directory we renamed on our side, because
2494 * that will result in a spurious rename/rename(1to2) conflict. An
2495 * example:
2496 * Base commit: dumbdir/afile, otherdir/bfile
2497 * Side 1: smrtdir/afile, otherdir/bfile
2498 * Side 2: dumbdir/afile, dumbdir/bfile
2499 * Here, while working on Side 1, we could notice that otherdir was
2500 * renamed/merged to dumbdir, and change the diff_filepair for
2501 * otherdir/bfile into a rename into dumbdir/bfile. However, Side
2502 * 2 will notice the rename from dumbdir to smrtdir, and do the
2503 * transitive rename to move it from dumbdir/bfile to
2504 * smrtdir/bfile. That gives us bfile in dumbdir vs being in
2505 * smrtdir, a rename/rename(1to2) conflict. We really just want
2506 * the file to end up in smrtdir. And the way to achieve that is
2507 * to not let Side1 do the rename to dumbdir, since we know that is
2508 * the source of one of our directory renames.
2509 *
2510 * That's why otherinfo and dir_rename_exclusions is here.
2511 *
2512 * As it turns out, this also prevents N-way transient rename
2513 * confusion; See testcases 9c and 9d of t6043.
2514 */
51e41e4e 2515 new_dir = rename_info->value; /* old_dir = rename_info->key; */
47325e85
EN
2516 otherinfo = strmap_get_entry(dir_rename_exclusions, new_dir);
2517 if (otherinfo) {
cb260775
EN
2518 path_msg(opt, INFO_DIR_RENAME_SKIPPED_DUE_TO_RERENAME, 1,
2519 rename_info->key, path, new_dir, NULL,
47325e85
EN
2520 _("WARNING: Avoiding applying %s -> %s rename "
2521 "to %s, because %s itself was renamed."),
2522 rename_info->key, new_dir, path, new_dir);
2523 return NULL;
2524 }
2525
2526 new_path = handle_path_level_conflicts(opt, path, side_index,
3ffbe5a2
EN
2527 rename_info,
2528 &collisions[side_index]);
47325e85
EN
2529 *clean_merge &= (new_path != NULL);
2530
2531 return new_path;
fa5e06d6
EN
2532}
2533
2534static void apply_directory_rename_modifications(struct merge_options *opt,
2535 struct diff_filepair *pair,
2536 char *new_path)
2537{
089d82bc
EN
2538 /*
2539 * The basic idea is to get the conflict_info from opt->priv->paths
2540 * at old path, and insert it into new_path; basically just this:
2541 * ci = strmap_get(&opt->priv->paths, old_path);
2542 * strmap_remove(&opt->priv->paths, old_path, 0);
2543 * strmap_put(&opt->priv->paths, new_path, ci);
2544 * However, there are some factors complicating this:
2545 * - opt->priv->paths may already have an entry at new_path
2546 * - Each ci tracks its containing directory, so we need to
2547 * update that
2548 * - If another ci has the same containing directory, then
2549 * the two char*'s MUST point to the same location. See the
2550 * comment in struct merged_info. strcmp equality is not
2551 * enough; we need pointer equality.
2552 * - opt->priv->paths must hold the parent directories of any
2553 * entries that are added. So, if this directory rename
2554 * causes entirely new directories, we must recursively add
2555 * parent directories.
2556 * - For each parent directory added to opt->priv->paths, we
2557 * also need to get its parent directory stored in its
2558 * conflict_info->merged.directory_name with all the same
2559 * requirements about pointer equality.
2560 */
2561 struct string_list dirs_to_insert = STRING_LIST_INIT_NODUP;
2562 struct conflict_info *ci, *new_ci;
2563 struct strmap_entry *entry;
2564 const char *branch_with_new_path, *branch_with_dir_rename;
2565 const char *old_path = pair->two->path;
2566 const char *parent_name;
2567 const char *cur_path;
2568 int i, len;
2569
2570 entry = strmap_get_entry(&opt->priv->paths, old_path);
2571 old_path = entry->key;
2572 ci = entry->value;
2573 VERIFY_CI(ci);
2574
2575 /* Find parent directories missing from opt->priv->paths */
62a15162
EN
2576 cur_path = mem_pool_strdup(&opt->priv->pool, new_path);
2577 free((char*)new_path);
2578 new_path = (char *)cur_path;
6697ee01 2579
089d82bc
EN
2580 while (1) {
2581 /* Find the parent directory of cur_path */
2582 char *last_slash = strrchr(cur_path, '/');
2583 if (last_slash) {
62a15162
EN
2584 parent_name = mem_pool_strndup(&opt->priv->pool,
2585 cur_path,
2586 last_slash - cur_path);
089d82bc
EN
2587 } else {
2588 parent_name = opt->priv->toplevel_dir;
2589 break;
2590 }
2591
2592 /* Look it up in opt->priv->paths */
2593 entry = strmap_get_entry(&opt->priv->paths, parent_name);
2594 if (entry) {
089d82bc
EN
2595 parent_name = entry->key; /* reuse known pointer */
2596 break;
2597 }
2598
2599 /* Record this is one of the directories we need to insert */
2600 string_list_append(&dirs_to_insert, parent_name);
2601 cur_path = parent_name;
2602 }
2603
2604 /* Traverse dirs_to_insert and insert them into opt->priv->paths */
2605 for (i = dirs_to_insert.nr-1; i >= 0; --i) {
2606 struct conflict_info *dir_ci;
2607 char *cur_dir = dirs_to_insert.items[i].string;
2608
ca56dadb 2609 CALLOC_ARRAY(dir_ci, 1);
089d82bc
EN
2610
2611 dir_ci->merged.directory_name = parent_name;
2612 len = strlen(parent_name);
2613 /* len+1 because of trailing '/' character */
2614 dir_ci->merged.basename_offset = (len > 0 ? len+1 : len);
2615 dir_ci->dirmask = ci->filemask;
2616 strmap_put(&opt->priv->paths, cur_dir, dir_ci);
2617
2618 parent_name = cur_dir;
2619 }
2620
089d82bc
EN
2621 assert(ci->filemask == 2 || ci->filemask == 4);
2622 assert(ci->dirmask == 0);
2623 strmap_remove(&opt->priv->paths, old_path, 0);
2624
2625 branch_with_new_path = (ci->filemask == 2) ? opt->branch1 : opt->branch2;
2626 branch_with_dir_rename = (ci->filemask == 2) ? opt->branch2 : opt->branch1;
2627
2628 /* Now, finally update ci and stick it into opt->priv->paths */
2629 ci->merged.directory_name = parent_name;
2630 len = strlen(parent_name);
2631 ci->merged.basename_offset = (len > 0 ? len+1 : len);
2632 new_ci = strmap_get(&opt->priv->paths, new_path);
2633 if (!new_ci) {
2634 /* Place ci back into opt->priv->paths, but at new_path */
2635 strmap_put(&opt->priv->paths, new_path, ci);
2636 } else {
2637 int index;
2638
2639 /* A few sanity checks */
2640 VERIFY_CI(new_ci);
2641 assert(ci->filemask == 2 || ci->filemask == 4);
2642 assert((new_ci->filemask & ci->filemask) == 0);
2643 assert(!new_ci->merged.clean);
2644
2645 /* Copy stuff from ci into new_ci */
2646 new_ci->filemask |= ci->filemask;
2647 if (new_ci->dirmask)
2648 new_ci->df_conflict = 1;
2649 index = (ci->filemask >> 1);
2650 new_ci->pathnames[index] = ci->pathnames[index];
2651 new_ci->stages[index].mode = ci->stages[index].mode;
2652 oidcpy(&new_ci->stages[index].oid, &ci->stages[index].oid);
2653
089d82bc
EN
2654 ci = new_ci;
2655 }
2656
2657 if (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE) {
2658 /* Notify user of updated path */
2659 if (pair->status == 'A')
cb260775
EN
2660 path_msg(opt, INFO_DIR_RENAME_APPLIED, 1,
2661 new_path, old_path, NULL, NULL,
089d82bc
EN
2662 _("Path updated: %s added in %s inside a "
2663 "directory that was renamed in %s; moving "
2664 "it to %s."),
2665 old_path, branch_with_new_path,
2666 branch_with_dir_rename, new_path);
2667 else
cb260775
EN
2668 path_msg(opt, INFO_DIR_RENAME_APPLIED, 1,
2669 new_path, old_path, NULL, NULL,
089d82bc
EN
2670 _("Path updated: %s renamed to %s in %s, "
2671 "inside a directory that was renamed in %s; "
2672 "moving it to %s."),
2673 pair->one->path, old_path, branch_with_new_path,
2674 branch_with_dir_rename, new_path);
2675 } else {
2676 /*
2677 * opt->detect_directory_renames has the value
2678 * MERGE_DIRECTORY_RENAMES_CONFLICT, so mark these as conflicts.
2679 */
2680 ci->path_conflict = 1;
2681 if (pair->status == 'A')
cb260775
EN
2682 path_msg(opt, CONFLICT_DIR_RENAME_SUGGESTED, 1,
2683 new_path, old_path, NULL, NULL,
089d82bc
EN
2684 _("CONFLICT (file location): %s added in %s "
2685 "inside a directory that was renamed in %s, "
2686 "suggesting it should perhaps be moved to "
2687 "%s."),
2688 old_path, branch_with_new_path,
2689 branch_with_dir_rename, new_path);
2690 else
cb260775
EN
2691 path_msg(opt, CONFLICT_DIR_RENAME_SUGGESTED, 1,
2692 new_path, old_path, NULL, NULL,
089d82bc
EN
2693 _("CONFLICT (file location): %s renamed to %s "
2694 "in %s, inside a directory that was renamed "
2695 "in %s, suggesting it should perhaps be "
2696 "moved to %s."),
2697 pair->one->path, old_path, branch_with_new_path,
2698 branch_with_dir_rename, new_path);
2699 }
2700
2701 /*
2702 * Finally, record the new location.
2703 */
2704 pair->two->path = new_path;
fa5e06d6
EN
2705}
2706
04af1879
EN
2707/*** Function Grouping: functions related to regular rename detection ***/
2708
e1a124e8
EN
2709static int process_renames(struct merge_options *opt,
2710 struct diff_queue_struct *renames)
2711{
c2d267df
EN
2712 int clean_merge = 1, i;
2713
2714 for (i = 0; i < renames->nr; ++i) {
2715 const char *oldpath = NULL, *newpath;
2716 struct diff_filepair *pair = renames->queue[i];
2717 struct conflict_info *oldinfo = NULL, *newinfo = NULL;
2718 struct strmap_entry *old_ent, *new_ent;
2719 unsigned int old_sidemask;
2720 int target_index, other_source_index;
2721 int source_deleted, collision, type_changed;
2e91ddd2 2722 const char *rename_branch = NULL, *delete_branch = NULL;
c2d267df
EN
2723
2724 old_ent = strmap_get_entry(&opt->priv->paths, pair->one->path);
c2d267df 2725 new_ent = strmap_get_entry(&opt->priv->paths, pair->two->path);
1b6b902d
EN
2726 if (old_ent) {
2727 oldpath = old_ent->key;
2728 oldinfo = old_ent->value;
2729 }
2730 newpath = pair->two->path;
2731 if (new_ent) {
2732 newpath = new_ent->key;
2733 newinfo = new_ent->value;
2734 }
2735
2736 /*
2737 * If pair->one->path isn't in opt->priv->paths, that means
2738 * that either directory rename detection removed that
2739 * path, or a parent directory of oldpath was resolved and
2740 * we don't even need the rename; in either case, we can
2741 * skip it. If oldinfo->merged.clean, then the other side
2742 * of history had no changes to oldpath and we don't need
2743 * the rename and can skip it.
2744 */
2745 if (!oldinfo || oldinfo->merged.clean)
2746 continue;
c2d267df
EN
2747
2748 /*
2749 * diff_filepairs have copies of pathnames, thus we have to
2750 * use standard 'strcmp()' (negated) instead of '=='.
2751 */
2752 if (i + 1 < renames->nr &&
2753 !strcmp(oldpath, renames->queue[i+1]->one->path)) {
2754 /* Handle rename/rename(1to2) or rename/rename(1to1) */
2755 const char *pathnames[3];
af1e56c4
EN
2756 struct version_info merged;
2757 struct conflict_info *base, *side1, *side2;
53e88a03 2758 unsigned was_binary_blob = 0;
c2d267df
EN
2759
2760 pathnames[0] = oldpath;
2761 pathnames[1] = newpath;
2762 pathnames[2] = renames->queue[i+1]->two->path;
2763
af1e56c4
EN
2764 base = strmap_get(&opt->priv->paths, pathnames[0]);
2765 side1 = strmap_get(&opt->priv->paths, pathnames[1]);
2766 side2 = strmap_get(&opt->priv->paths, pathnames[2]);
2767
2768 VERIFY_CI(base);
2769 VERIFY_CI(side1);
2770 VERIFY_CI(side2);
2771
c2d267df 2772 if (!strcmp(pathnames[1], pathnames[2])) {
cbdca289
EN
2773 struct rename_info *ri = &opt->priv->renames;
2774 int j;
2775
af1e56c4
EN
2776 /* Both sides renamed the same way */
2777 assert(side1 == side2);
2778 memcpy(&side1->stages[0], &base->stages[0],
2779 sizeof(merged));
2780 side1->filemask |= (1 << MERGE_BASE);
2781 /* Mark base as resolved by removal */
2782 base->merged.is_null = 1;
2783 base->merged.clean = 1;
c2d267df 2784
cbdca289
EN
2785 /*
2786 * Disable remembering renames optimization;
2787 * rename/rename(1to1) is incredibly rare, and
2788 * just disabling the optimization is easier
2789 * than purging cached_pairs,
2790 * cached_target_names, and dir_rename_counts.
2791 */
2792 for (j = 0; j < 3; j++)
2793 ri->merge_trees[j] = NULL;
2794
c2d267df
EN
2795 /* We handled both renames, i.e. i+1 handled */
2796 i++;
2797 /* Move to next rename */
2798 continue;
2799 }
2800
2801 /* This is a rename/rename(1to2) */
53e88a03
EN
2802 clean_merge = handle_content_merge(opt,
2803 pair->one->path,
2804 &base->stages[0],
2805 &side1->stages[1],
2806 &side2->stages[2],
2807 pathnames,
2808 1 + 2 * opt->priv->call_depth,
2809 &merged);
92481d1b
JS
2810 if (clean_merge < 0)
2811 return -1;
53e88a03
EN
2812 if (!clean_merge &&
2813 merged.mode == side1->stages[1].mode &&
2814 oideq(&merged.oid, &side1->stages[1].oid))
2815 was_binary_blob = 1;
2816 memcpy(&side1->stages[1], &merged, sizeof(merged));
2817 if (was_binary_blob) {
2818 /*
2819 * Getting here means we were attempting to
2820 * merge a binary blob.
2821 *
2822 * Since we can't merge binaries,
2823 * handle_content_merge() just takes one
2824 * side. But we don't want to copy the
2825 * contents of one side to both paths. We
2826 * used the contents of side1 above for
2827 * side1->stages, let's use the contents of
2828 * side2 for side2->stages below.
2829 */
2830 oidcpy(&merged.oid, &side2->stages[2].oid);
2831 merged.mode = side2->stages[2].mode;
2832 }
2833 memcpy(&side2->stages[2], &merged, sizeof(merged));
2834
2835 side1->path_conflict = 1;
2836 side2->path_conflict = 1;
2837 /*
2838 * TODO: For renames we normally remove the path at the
2839 * old name. It would thus seem consistent to do the
2840 * same for rename/rename(1to2) cases, but we haven't
2841 * done so traditionally and a number of the regression
2842 * tests now encode an expectation that the file is
2843 * left there at stage 1. If we ever decide to change
2844 * this, add the following two lines here:
2845 * base->merged.is_null = 1;
2846 * base->merged.clean = 1;
2847 * and remove the setting of base->path_conflict to 1.
2848 */
2849 base->path_conflict = 1;
cb260775
EN
2850 path_msg(opt, CONFLICT_RENAME_RENAME, 0,
2851 pathnames[0], pathnames[1], pathnames[2], NULL,
53e88a03
EN
2852 _("CONFLICT (rename/rename): %s renamed to "
2853 "%s in %s and to %s in %s."),
2854 pathnames[0],
2855 pathnames[1], opt->branch1,
2856 pathnames[2], opt->branch2);
c2d267df
EN
2857
2858 i++; /* We handled both renames, i.e. i+1 handled */
2859 continue;
2860 }
2861
2862 VERIFY_CI(oldinfo);
2863 VERIFY_CI(newinfo);
2864 target_index = pair->score; /* from collect_renames() */
2865 assert(target_index == 1 || target_index == 2);
2866 other_source_index = 3 - target_index;
2867 old_sidemask = (1 << other_source_index); /* 2 or 4 */
2868 source_deleted = (oldinfo->filemask == 1);
2869 collision = ((newinfo->filemask & old_sidemask) != 0);
2870 type_changed = !source_deleted &&
2871 (S_ISREG(oldinfo->stages[other_source_index].mode) !=
2872 S_ISREG(newinfo->stages[target_index].mode));
2873 if (type_changed && collision) {
6fcccbd7
EN
2874 /*
2875 * special handling so later blocks can handle this...
2876 *
2877 * if type_changed && collision are both true, then this
2878 * was really a double rename, but one side wasn't
2879 * detected due to lack of break detection. I.e.
2880 * something like
2881 * orig: has normal file 'foo'
2882 * side1: renames 'foo' to 'bar', adds 'foo' symlink
2883 * side2: renames 'foo' to 'bar'
2884 * In this case, the foo->bar rename on side1 won't be
2885 * detected because the new symlink named 'foo' is
2886 * there and we don't do break detection. But we detect
2887 * this here because we don't want to merge the content
2888 * of the foo symlink with the foo->bar file, so we
2889 * have some logic to handle this special case. The
2890 * easiest way to do that is make 'bar' on side1 not
2891 * be considered a colliding file but the other part
2892 * of a normal rename. If the file is very different,
2893 * well we're going to get content merge conflicts
2894 * anyway so it doesn't hurt. And if the colliding
2895 * file also has a different type, that'll be handled
2896 * by the content merge logic in process_entry() too.
2897 *
2898 * See also t6430, 'rename vs. rename/symlink'
2899 */
2900 collision = 0;
c2d267df 2901 }
2e91ddd2
EN
2902 if (source_deleted) {
2903 if (target_index == 1) {
2904 rename_branch = opt->branch1;
2905 delete_branch = opt->branch2;
2906 } else {
2907 rename_branch = opt->branch2;
2908 delete_branch = opt->branch1;
2909 }
2910 }
c2d267df
EN
2911
2912 assert(source_deleted || oldinfo->filemask & old_sidemask);
2913
2914 /* Need to check for special types of rename conflicts... */
2915 if (collision && !source_deleted) {
2916 /* collision: rename/add or rename/rename(2to1) */
35e47e35
EN
2917 const char *pathnames[3];
2918 struct version_info merged;
2919
2920 struct conflict_info *base, *side1, *side2;
92481d1b 2921 int clean;
35e47e35
EN
2922
2923 pathnames[0] = oldpath;
2924 pathnames[other_source_index] = oldpath;
2925 pathnames[target_index] = newpath;
2926
2927 base = strmap_get(&opt->priv->paths, pathnames[0]);
2928 side1 = strmap_get(&opt->priv->paths, pathnames[1]);
2929 side2 = strmap_get(&opt->priv->paths, pathnames[2]);
2930
2931 VERIFY_CI(base);
2932 VERIFY_CI(side1);
2933 VERIFY_CI(side2);
2934
2935 clean = handle_content_merge(opt, pair->one->path,
2936 &base->stages[0],
2937 &side1->stages[1],
2938 &side2->stages[2],
2939 pathnames,
2940 1 + 2 * opt->priv->call_depth,
2941 &merged);
92481d1b
JS
2942 if (clean < 0)
2943 return -1;
35e47e35
EN
2944
2945 memcpy(&newinfo->stages[target_index], &merged,
2946 sizeof(merged));
2947 if (!clean) {
cb260775
EN
2948 path_msg(opt, CONFLICT_RENAME_COLLIDES, 0,
2949 newpath, oldpath, NULL, NULL,
35e47e35
EN
2950 _("CONFLICT (rename involved in "
2951 "collision): rename of %s -> %s has "
2952 "content conflicts AND collides "
2953 "with another path; this may result "
2954 "in nested conflict markers."),
2955 oldpath, newpath);
2956 }
c2d267df 2957 } else if (collision && source_deleted) {
35e47e35
EN
2958 /*
2959 * rename/add/delete or rename/rename(2to1)/delete:
2960 * since oldpath was deleted on the side that didn't
2961 * do the rename, there's not much of a content merge
2962 * we can do for the rename. oldinfo->merged.is_null
2963 * was already set, so we just leave things as-is so
2964 * they look like an add/add conflict.
2965 */
2966
2967 newinfo->path_conflict = 1;
cb260775
EN
2968 path_msg(opt, CONFLICT_RENAME_DELETE, 0,
2969 newpath, oldpath, NULL, NULL,
35e47e35
EN
2970 _("CONFLICT (rename/delete): %s renamed "
2971 "to %s in %s, but deleted in %s."),
2972 oldpath, newpath, rename_branch, delete_branch);
c2d267df 2973 } else {
2e91ddd2
EN
2974 /*
2975 * a few different cases...start by copying the
2976 * existing stage(s) from oldinfo over the newinfo
2977 * and update the pathname(s).
2978 */
2979 memcpy(&newinfo->stages[0], &oldinfo->stages[0],
2980 sizeof(newinfo->stages[0]));
2981 newinfo->filemask |= (1 << MERGE_BASE);
2982 newinfo->pathnames[0] = oldpath;
c2d267df
EN
2983 if (type_changed) {
2984 /* rename vs. typechange */
6fcccbd7 2985 /* Mark the original as resolved by removal */
14228447 2986 memcpy(&oldinfo->stages[0].oid, null_oid(),
6fcccbd7
EN
2987 sizeof(oldinfo->stages[0].oid));
2988 oldinfo->stages[0].mode = 0;
2989 oldinfo->filemask &= 0x06;
c2d267df
EN
2990 } else if (source_deleted) {
2991 /* rename/delete */
2e91ddd2 2992 newinfo->path_conflict = 1;
cb260775
EN
2993 path_msg(opt, CONFLICT_RENAME_DELETE, 0,
2994 newpath, oldpath, NULL, NULL,
2e91ddd2
EN
2995 _("CONFLICT (rename/delete): %s renamed"
2996 " to %s in %s, but deleted in %s."),
2997 oldpath, newpath,
2998 rename_branch, delete_branch);
c2d267df
EN
2999 } else {
3000 /* normal rename */
f1665e69
EN
3001 memcpy(&newinfo->stages[other_source_index],
3002 &oldinfo->stages[other_source_index],
3003 sizeof(newinfo->stages[0]));
3004 newinfo->filemask |= (1 << other_source_index);
3005 newinfo->pathnames[other_source_index] = oldpath;
c2d267df
EN
3006 }
3007 }
3008
3009 if (!type_changed) {
3010 /* Mark the original as resolved by removal */
3011 oldinfo->merged.is_null = 1;
3012 oldinfo->merged.clean = 1;
3013 }
3014
3015 }
3016
3017 return clean_merge;
e1a124e8
EN
3018}
3019
f89b4f2b
EN
3020static inline int possible_side_renames(struct rename_info *renames,
3021 unsigned side_index)
3022{
3023 return renames->pairs[side_index].nr > 0 &&
a49b55d5 3024 !strintmap_empty(&renames->relevant_sources[side_index]);
f89b4f2b
EN
3025}
3026
3027static inline int possible_renames(struct rename_info *renames)
3028{
3029 return possible_side_renames(renames, 1) ||
25e65b6d
EN
3030 possible_side_renames(renames, 2) ||
3031 !strmap_empty(&renames->cached_pairs[1]) ||
3032 !strmap_empty(&renames->cached_pairs[2]);
f89b4f2b
EN
3033}
3034
f78cf976
EN
3035static void resolve_diffpair_statuses(struct diff_queue_struct *q)
3036{
3037 /*
3038 * A simplified version of diff_resolve_rename_copy(); would probably
3039 * just use that function but it's static...
3040 */
3041 int i;
3042 struct diff_filepair *p;
3043
3044 for (i = 0; i < q->nr; ++i) {
3045 p = q->queue[i];
3046 p->status = 0; /* undecided */
3047 if (!DIFF_FILE_VALID(p->one))
3048 p->status = DIFF_STATUS_ADDED;
3049 else if (!DIFF_FILE_VALID(p->two))
3050 p->status = DIFF_STATUS_DELETED;
3051 else if (DIFF_PAIR_RENAME(p))
3052 p->status = DIFF_STATUS_RENAMED;
3053 }
3054}
3055
86b41b38
EN
3056static void prune_cached_from_relevant(struct rename_info *renames,
3057 unsigned side)
3058{
3059 /* Reason for this function described in add_pair() */
3060 struct hashmap_iter iter;
3061 struct strmap_entry *entry;
3062
3063 /* Remove from relevant_sources all entries in cached_pairs[side] */
3064 strmap_for_each_entry(&renames->cached_pairs[side], &iter, entry) {
3065 strintmap_remove(&renames->relevant_sources[side],
3066 entry->key);
3067 }
3068 /* Remove from relevant_sources all entries in cached_irrelevant[side] */
3069 strset_for_each_entry(&renames->cached_irrelevant[side], &iter, entry) {
3070 strintmap_remove(&renames->relevant_sources[side],
3071 entry->key);
3072 }
3073}
3074
86b41b38
EN
3075static void use_cached_pairs(struct merge_options *opt,
3076 struct strmap *cached_pairs,
3077 struct diff_queue_struct *pairs)
3078{
3079 struct hashmap_iter iter;
3080 struct strmap_entry *entry;
3081
3082 /*
3083 * Add to side_pairs all entries from renames->cached_pairs[side_index].
3084 * (Info in cached_irrelevant[side_index] is not relevant here.)
3085 */
3086 strmap_for_each_entry(cached_pairs, &iter, entry) {
3087 struct diff_filespec *one, *two;
3088 const char *old_name = entry->key;
3089 const char *new_name = entry->value;
3090 if (!new_name)
3091 new_name = old_name;
3092
62a15162
EN
3093 /*
3094 * cached_pairs has *copies* of old_name and new_name,
3095 * because it has to persist across merges. Since
3096 * pool_alloc_filespec() will just re-use the existing
3097 * filenames, which will also get re-used by
3098 * opt->priv->paths if they become renames, and then
3099 * get freed at the end of the merge, that would leave
3100 * the copy in cached_pairs dangling. Avoid this by
3101 * making a copy here.
3102 */
3103 old_name = mem_pool_strdup(&opt->priv->pool, old_name);
3104 new_name = mem_pool_strdup(&opt->priv->pool, new_name);
86b41b38
EN
3105
3106 /* We don't care about oid/mode, only filenames and status */
62a15162
EN
3107 one = pool_alloc_filespec(&opt->priv->pool, old_name);
3108 two = pool_alloc_filespec(&opt->priv->pool, new_name);
3109 pool_diff_queue(&opt->priv->pool, pairs, one, two);
86b41b38
EN
3110 pairs->queue[pairs->nr-1]->status = entry->value ? 'R' : 'D';
3111 }
3112}
3113
2734f2e3
EN
3114static void cache_new_pair(struct rename_info *renames,
3115 int side,
3116 char *old_path,
3117 char *new_path,
3118 int free_old_value)
3119{
3120 char *old_value;
3121 new_path = xstrdup(new_path);
3122 old_value = strmap_put(&renames->cached_pairs[side],
3123 old_path, new_path);
3124 strset_add(&renames->cached_target_names[side], new_path);
3125 if (free_old_value)
3126 free(old_value);
3127 else
3128 assert(!old_value);
3129}
3130
3131static void possibly_cache_new_pair(struct rename_info *renames,
3132 struct diff_filepair *p,
3133 unsigned side,
3134 char *new_path)
3135{
3136 int dir_renamed_side = 0;
3137
3138 if (new_path) {
3139 /*
3140 * Directory renames happen on the other side of history from
3141 * the side that adds new files to the old directory.
3142 */
3143 dir_renamed_side = 3 - side;
3144 } else {
3145 int val = strintmap_get(&renames->relevant_sources[side],
3146 p->one->path);
3147 if (val == RELEVANT_NO_MORE) {
3148 assert(p->status == 'D');
3149 strset_add(&renames->cached_irrelevant[side],
3150 p->one->path);
3151 }
3152 if (val <= 0)
3153 return;
3154 }
3155
3156 if (p->status == 'D') {
3157 /*
3158 * If we already had this delete, we'll just set it's value
3159 * to NULL again, so no harm.
3160 */
3161 strmap_put(&renames->cached_pairs[side], p->one->path, NULL);
3162 } else if (p->status == 'R') {
3163 if (!new_path)
3164 new_path = p->two->path;
3165 else
3166 cache_new_pair(renames, dir_renamed_side,
3167 p->two->path, new_path, 0);
3168 cache_new_pair(renames, side, p->one->path, new_path, 1);
3169 } else if (p->status == 'A' && new_path) {
3170 cache_new_pair(renames, dir_renamed_side,
3171 p->two->path, new_path, 0);
3172 }
3173}
3174
e1a124e8
EN
3175static int compare_pairs(const void *a_, const void *b_)
3176{
965a7bc2
EN
3177 const struct diff_filepair *a = *((const struct diff_filepair **)a_);
3178 const struct diff_filepair *b = *((const struct diff_filepair **)b_);
3179
3180 return strcmp(a->one->path, b->one->path);
e1a124e8
EN
3181}
3182
356da0f9 3183/* Call diffcore_rename() to update deleted/added pairs into rename pairs */
8b09a900
EN
3184static int detect_regular_renames(struct merge_options *opt,
3185 unsigned side_index)
e1a124e8 3186{
f39d05ca
EN
3187 struct diff_options diff_opts;
3188 struct rename_info *renames = &opt->priv->renames;
3189
25e65b6d 3190 prune_cached_from_relevant(renames, side_index);
f89b4f2b
EN
3191 if (!possible_side_renames(renames, side_index)) {
3192 /*
3193 * No rename detection needed for this side, but we still need
3194 * to make sure 'adds' are marked correctly in case the other
3195 * side had directory renames.
3196 */
3197 resolve_diffpair_statuses(&renames->pairs[side_index]);
8b09a900 3198 return 0;
f89b4f2b
EN
3199 }
3200
d5098029 3201 partial_clear_dir_rename_count(&renames->dir_rename_count[side_index]);
f39d05ca
EN
3202 repo_diff_setup(opt->repo, &diff_opts);
3203 diff_opts.flags.recursive = 1;
3204 diff_opts.flags.rename_empty = 0;
3205 diff_opts.detect_rename = DIFF_DETECT_RENAME;
3206 diff_opts.rename_limit = opt->rename_limit;
3207 if (opt->rename_limit <= 0)
94b82d56 3208 diff_opts.rename_limit = 7000;
f39d05ca
EN
3209 diff_opts.rename_score = opt->rename_score;
3210 diff_opts.show_rename_progress = opt->show_rename_progress;
3211 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
3212 diff_setup_done(&diff_opts);
557ac035 3213
f78cf976 3214 diff_queued_diff = renames->pairs[side_index];
557ac035 3215 trace2_region_enter("diff", "diffcore_rename", opt->repo);
0c4fd732 3216 diffcore_rename_extended(&diff_opts,
62a15162 3217 &opt->priv->pool,
174791f0 3218 &renames->relevant_sources[side_index],
0c4fd732 3219 &renames->dirs_removed[side_index],
25e65b6d
EN
3220 &renames->dir_rename_count[side_index],
3221 &renames->cached_pairs[side_index]);
557ac035 3222 trace2_region_leave("diff", "diffcore_rename", opt->repo);
f78cf976 3223 resolve_diffpair_statuses(&diff_queued_diff);
f39d05ca 3224
8b09a900
EN
3225 if (diff_opts.needed_rename_limit > 0)
3226 renames->redo_after_renames = 0;
f39d05ca
EN
3227 if (diff_opts.needed_rename_limit > renames->needed_limit)
3228 renames->needed_limit = diff_opts.needed_rename_limit;
3229
3230 renames->pairs[side_index] = diff_queued_diff;
3231
3232 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
3233 diff_queued_diff.nr = 0;
3234 diff_queued_diff.queue = NULL;
3235 diff_flush(&diff_opts);
8b09a900
EN
3236
3237 return 1;
e1a124e8
EN
3238}
3239
3240/*
356da0f9
EN
3241 * Get information of all renames which occurred in 'side_pairs', making use
3242 * of any implicit directory renames in side_dir_renames (also making use of
3243 * implicit directory renames rename_exclusions as needed by
3244 * check_for_directory_rename()). Add all (updated) renames into result.
e1a124e8
EN
3245 */
3246static int collect_renames(struct merge_options *opt,
3247 struct diff_queue_struct *result,
fa5e06d6 3248 unsigned side_index,
3ffbe5a2 3249 struct strmap *collisions,
fa5e06d6
EN
3250 struct strmap *dir_renames_for_side,
3251 struct strmap *rename_exclusions)
e1a124e8 3252{
965a7bc2
EN
3253 int i, clean = 1;
3254 struct diff_queue_struct *side_pairs;
3255 struct rename_info *renames = &opt->priv->renames;
3256
3257 side_pairs = &renames->pairs[side_index];
3258
3259 for (i = 0; i < side_pairs->nr; ++i) {
3260 struct diff_filepair *p = side_pairs->queue[i];
fa5e06d6 3261 char *new_path; /* non-NULL only with directory renames */
965a7bc2 3262
fa5e06d6 3263 if (p->status != 'A' && p->status != 'R') {
2734f2e3 3264 possibly_cache_new_pair(renames, p, side_index, NULL);
62a15162 3265 pool_diff_free_filepair(&opt->priv->pool, p);
965a7bc2
EN
3266 continue;
3267 }
3268
fa5e06d6
EN
3269 new_path = check_for_directory_rename(opt, p->two->path,
3270 side_index,
3271 dir_renames_for_side,
3272 rename_exclusions,
3ffbe5a2 3273 collisions,
fa5e06d6
EN
3274 &clean);
3275
2734f2e3 3276 possibly_cache_new_pair(renames, p, side_index, new_path);
fa5e06d6 3277 if (p->status != 'R' && !new_path) {
62a15162 3278 pool_diff_free_filepair(&opt->priv->pool, p);
fa5e06d6
EN
3279 continue;
3280 }
3281
3282 if (new_path)
3283 apply_directory_rename_modifications(opt, p, new_path);
3284
965a7bc2
EN
3285 /*
3286 * p->score comes back from diffcore_rename_extended() with
3287 * the similarity of the renamed file. The similarity is
3288 * was used to determine that the two files were related
3289 * and are a rename, which we have already used, but beyond
3290 * that we have no use for the similarity. So p->score is
3291 * now irrelevant. However, process_renames() will need to
3292 * know which side of the merge this rename was associated
3293 * with, so overwrite p->score with that value.
3294 */
3295 p->score = side_index;
3296 result->queue[result->nr++] = p;
3297 }
3298
3299 return clean;
e1a124e8
EN
3300}
3301
231e2dd4
EN
3302static int detect_and_process_renames(struct merge_options *opt,
3303 struct tree *merge_base,
3304 struct tree *side1,
3305 struct tree *side2)
3306{
8d60e9d2 3307 struct diff_queue_struct combined = { 0 };
e1a124e8 3308 struct rename_info *renames = &opt->priv->renames;
3ffbe5a2 3309 struct strmap collisions[3];
8d60e9d2 3310 int need_dir_renames, s, i, clean = 1;
8b09a900 3311 unsigned detection_run = 0;
e1a124e8 3312
f89b4f2b
EN
3313 if (!possible_renames(renames))
3314 goto cleanup;
e1a124e8 3315
557ac035 3316 trace2_region_enter("merge", "regular renames", opt->repo);
8b09a900
EN
3317 detection_run |= detect_regular_renames(opt, MERGE_SIDE1);
3318 detection_run |= detect_regular_renames(opt, MERGE_SIDE2);
9ae39fef
EN
3319 if (renames->needed_limit) {
3320 renames->cached_pairs_valid_side = 0;
3321 renames->redo_after_renames = 0;
3322 }
8b09a900
EN
3323 if (renames->redo_after_renames && detection_run) {
3324 int i, side;
3325 struct diff_filepair *p;
3326
3327 /* Cache the renames, we found */
3328 for (side = MERGE_SIDE1; side <= MERGE_SIDE2; side++) {
3329 for (i = 0; i < renames->pairs[side].nr; ++i) {
3330 p = renames->pairs[side].queue[i];
3331 possibly_cache_new_pair(renames, p, side, NULL);
3332 }
3333 }
3334
3335 /* Restart the merge with the cached renames */
3336 renames->redo_after_renames = 2;
3337 trace2_region_leave("merge", "regular renames", opt->repo);
3338 goto cleanup;
3339 }
25e65b6d
EN
3340 use_cached_pairs(opt, &renames->cached_pairs[1], &renames->pairs[1]);
3341 use_cached_pairs(opt, &renames->cached_pairs[2], &renames->pairs[2]);
557ac035 3342 trace2_region_leave("merge", "regular renames", opt->repo);
e1a124e8 3343
557ac035 3344 trace2_region_enter("merge", "directory renames", opt->repo);
112e1112
EN
3345 need_dir_renames =
3346 !opt->priv->call_depth &&
3347 (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE ||
3348 opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT);
3349
3350 if (need_dir_renames) {
3351 get_provisional_directory_renames(opt, MERGE_SIDE1, &clean);
3352 get_provisional_directory_renames(opt, MERGE_SIDE2, &clean);
3353 handle_directory_level_conflicts(opt);
3354 }
3355
e1a124e8
EN
3356 ALLOC_GROW(combined.queue,
3357 renames->pairs[1].nr + renames->pairs[2].nr,
3358 combined.alloc);
3ffbe5a2
EN
3359 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; i++) {
3360 int other_side = 3 - i;
3361 compute_collisions(&collisions[i],
3362 &renames->dir_renames[other_side],
3363 &renames->pairs[i]);
3364 }
fa5e06d6 3365 clean &= collect_renames(opt, &combined, MERGE_SIDE1,
3ffbe5a2 3366 collisions,
fa5e06d6
EN
3367 &renames->dir_renames[2],
3368 &renames->dir_renames[1]);
3369 clean &= collect_renames(opt, &combined, MERGE_SIDE2,
3ffbe5a2 3370 collisions,
fa5e06d6
EN
3371 &renames->dir_renames[1],
3372 &renames->dir_renames[2]);
3ffbe5a2
EN
3373 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; i++)
3374 free_collisions(&collisions[i]);
72b30910 3375 STABLE_QSORT(combined.queue, combined.nr, compare_pairs);
557ac035 3376 trace2_region_leave("merge", "directory renames", opt->repo);
e1a124e8 3377
557ac035 3378 trace2_region_enter("merge", "process renames", opt->repo);
e1a124e8 3379 clean &= process_renames(opt, &combined);
557ac035 3380 trace2_region_leave("merge", "process renames", opt->repo);
e1a124e8 3381
f89b4f2b
EN
3382 goto simple_cleanup; /* collect_renames() handles some of cleanup */
3383
3384cleanup:
3385 /*
3386 * Free now unneeded filepairs, which would have been handled
3387 * in collect_renames() normally but we skipped that code.
3388 */
3389 for (s = MERGE_SIDE1; s <= MERGE_SIDE2; s++) {
3390 struct diff_queue_struct *side_pairs;
3391 int i;
3392
3393 side_pairs = &renames->pairs[s];
3394 for (i = 0; i < side_pairs->nr; ++i) {
3395 struct diff_filepair *p = side_pairs->queue[i];
62a15162 3396 pool_diff_free_filepair(&opt->priv->pool, p);
f89b4f2b
EN
3397 }
3398 }
3399
3400simple_cleanup:
e1a124e8
EN
3401 /* Free memory for renames->pairs[] and combined */
3402 for (s = MERGE_SIDE1; s <= MERGE_SIDE2; s++) {
3403 free(renames->pairs[s].queue);
3404 DIFF_QUEUE_CLEAR(&renames->pairs[s]);
3405 }
8d60e9d2
EN
3406 for (i = 0; i < combined.nr; i++)
3407 pool_diff_free_filepair(&opt->priv->pool, combined.queue[i]);
3408 free(combined.queue);
231e2dd4 3409
231e2dd4
EN
3410 return clean;
3411}
3412
04af1879
EN
3413/*** Function Grouping: functions related to process_entries() ***/
3414
5a3743da 3415static int sort_dirs_next_to_their_children(const char *one, const char *two)
8adffaa8 3416{
5a3743da
EN
3417 unsigned char c1, c2;
3418
3419 /*
3420 * Here we only care that entries for directories appear adjacent
3421 * to and before files underneath the directory. We can achieve
3422 * that by pretending to add a trailing slash to every file and
3423 * then sorting. In other words, we do not want the natural
3424 * sorting of
3425 * foo
3426 * foo.txt
3427 * foo/bar
3428 * Instead, we want "foo" to sort as though it were "foo/", so that
3429 * we instead get
3430 * foo.txt
3431 * foo
3432 * foo/bar
3433 * To achieve this, we basically implement our own strcmp, except that
3434 * if we get to the end of either string instead of comparing NUL to
3435 * another character, we compare '/' to it.
3436 *
3437 * If this unusual "sort as though '/' were appended" perplexes
3438 * you, perhaps it will help to note that this is not the final
3439 * sort. write_tree() will sort again without the trailing slash
3440 * magic, but just on paths immediately under a given tree.
8adffaa8 3441 *
5a3743da
EN
3442 * The reason to not use df_name_compare directly was that it was
3443 * just too expensive (we don't have the string lengths handy), so
3444 * it was reimplemented.
8adffaa8 3445 */
5a3743da 3446
8adffaa8 3447 /*
5a3743da
EN
3448 * NOTE: This function will never be called with two equal strings,
3449 * because it is used to sort the keys of a strmap, and strmaps have
3450 * unique keys by construction. That simplifies our c1==c2 handling
3451 * below.
8adffaa8 3452 */
5a3743da
EN
3453
3454 while (*one && (*one == *two)) {
3455 one++;
3456 two++;
3457 }
3458
3459 c1 = *one ? *one : '/';
3460 c2 = *two ? *two : '/';
3461
3462 if (c1 == c2) {
3463 /* Getting here means one is a leading directory of the other */
3464 return (*one) ? 1 : -1;
3465 } else
3466 return c1 - c2;
8adffaa8
EN
3467}
3468
3860220b
EN
3469static int read_oid_strbuf(struct merge_options *opt,
3470 const struct object_id *oid,
3471 struct strbuf *dst)
3472{
3473 void *buf;
3474 enum object_type type;
3475 unsigned long size;
3476 buf = read_object_file(oid, &type, &size);
3477 if (!buf)
3478 return err(opt, _("cannot read object %s"), oid_to_hex(oid));
3479 if (type != OBJ_BLOB) {
3480 free(buf);
3481 return err(opt, _("object %s is not a blob"), oid_to_hex(oid));
3482 }
3483 strbuf_attach(dst, buf, size, size + 1);
3484 return 0;
3485}
3486
3487static int blob_unchanged(struct merge_options *opt,
3488 const struct version_info *base,
3489 const struct version_info *side,
3490 const char *path)
3491{
3492 struct strbuf basebuf = STRBUF_INIT;
3493 struct strbuf sidebuf = STRBUF_INIT;
3494 int ret = 0; /* assume changed for safety */
8e978529 3495 struct index_state *idx = &opt->priv->attr_index;
3860220b
EN
3496
3497 if (!idx->initialized)
3498 initialize_attr_index(opt);
3499
3500 if (base->mode != side->mode)
3501 return 0;
3502 if (oideq(&base->oid, &side->oid))
3503 return 1;
3504
3505 if (read_oid_strbuf(opt, &base->oid, &basebuf) ||
3506 read_oid_strbuf(opt, &side->oid, &sidebuf))
3507 goto error_return;
3508 /*
3509 * Note: binary | is used so that both renormalizations are
3510 * performed. Comparison can be skipped if both files are
3511 * unchanged since their sha1s have already been compared.
3512 */
3513 if (renormalize_buffer(idx, path, basebuf.buf, basebuf.len, &basebuf) |
3514 renormalize_buffer(idx, path, sidebuf.buf, sidebuf.len, &sidebuf))
3515 ret = (basebuf.len == sidebuf.len &&
3516 !memcmp(basebuf.buf, sidebuf.buf, basebuf.len));
3517
3518error_return:
3519 strbuf_release(&basebuf);
3520 strbuf_release(&sidebuf);
3521 return ret;
3522}
3523
a9945bba 3524struct directory_versions {
bb470f4e
EN
3525 /*
3526 * versions: list of (basename -> version_info)
3527 *
3528 * The basenames are in reverse lexicographic order of full pathnames,
3529 * as processed in process_entries(). This puts all entries within
3530 * a directory together, and covers the directory itself after
3531 * everything within it, allowing us to write subtrees before needing
3532 * to record information for the tree itself.
3533 */
a9945bba 3534 struct string_list versions;
bb470f4e
EN
3535
3536 /*
3537 * offsets: list of (full relative path directories -> integer offsets)
3538 *
3539 * Since versions contains basenames from files in multiple different
3540 * directories, we need to know which entries in versions correspond
3541 * to which directories. Values of e.g.
3542 * "" 0
3543 * src 2
3544 * src/moduleA 5
3545 * Would mean that entries 0-1 of versions are files in the toplevel
3546 * directory, entries 2-4 are files under src/, and the remaining
3547 * entries starting at index 5 are files under src/moduleA/.
3548 */
3549 struct string_list offsets;
3550
3551 /*
3552 * last_directory: directory that previously processed file found in
3553 *
3554 * last_directory starts NULL, but records the directory in which the
3555 * previous file was found within. As soon as
3556 * directory(current_file) != last_directory
3557 * then we need to start updating accounting in versions & offsets.
3558 * Note that last_directory is always the last path in "offsets" (or
3559 * NULL if "offsets" is empty) so this exists just for quick access.
3560 */
3561 const char *last_directory;
3562
3563 /* last_directory_len: cached computation of strlen(last_directory) */
3564 unsigned last_directory_len;
a9945bba
EN
3565};
3566
ee4012dc
EN
3567static int tree_entry_order(const void *a_, const void *b_)
3568{
3569 const struct string_list_item *a = a_;
3570 const struct string_list_item *b = b_;
3571
3572 const struct merged_info *ami = a->util;
3573 const struct merged_info *bmi = b->util;
3574 return base_name_compare(a->string, strlen(a->string), ami->result.mode,
3575 b->string, strlen(b->string), bmi->result.mode);
3576}
3577
0b55d930
JS
3578static int write_tree(struct object_id *result_oid,
3579 struct string_list *versions,
3580 unsigned int offset,
3581 size_t hash_size)
ee4012dc
EN
3582{
3583 size_t maxlen = 0, extra;
c1ea48a8 3584 unsigned int nr;
ee4012dc 3585 struct strbuf buf = STRBUF_INIT;
0b55d930 3586 int i, ret = 0;
ee4012dc 3587
c1ea48a8
AH
3588 assert(offset <= versions->nr);
3589 nr = versions->nr - offset;
3590 if (versions->nr)
257ae76b 3591 /* No need for STABLE_QSORT -- filenames must be unique */
c1ea48a8 3592 QSORT(versions->items + offset, nr, tree_entry_order);
ee4012dc
EN
3593
3594 /* Pre-allocate some space in buf */
3595 extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
3596 for (i = 0; i < nr; i++) {
3597 maxlen += strlen(versions->items[offset+i].string) + extra;
3598 }
3599 strbuf_grow(&buf, maxlen);
3600
3601 /* Write each entry out to buf */
3602 for (i = 0; i < nr; i++) {
3603 struct merged_info *mi = versions->items[offset+i].util;
3604 struct version_info *ri = &mi->result;
3605 strbuf_addf(&buf, "%o %s%c",
3606 ri->mode,
3607 versions->items[offset+i].string, '\0');
3608 strbuf_add(&buf, ri->oid.hash, hash_size);
3609 }
3610
3611 /* Write this object file out, and record in result_oid */
0b55d930
JS
3612 if (write_object_file(buf.buf, buf.len, OBJ_TREE, result_oid))
3613 ret = -1;
ee4012dc 3614 strbuf_release(&buf);
0b55d930 3615 return ret;
ee4012dc
EN
3616}
3617
a9945bba
EN
3618static void record_entry_for_tree(struct directory_versions *dir_metadata,
3619 const char *path,
3620 struct merged_info *mi)
3621{
3622 const char *basename;
3623
3624 if (mi->is_null)
3625 /* nothing to record */
3626 return;
3627
3628 basename = path + mi->basename_offset;
3629 assert(strchr(basename, '/') == NULL);
3630 string_list_append(&dir_metadata->versions,
3631 basename)->util = &mi->result;
3632}
3633
0b55d930
JS
3634static int write_completed_directory(struct merge_options *opt,
3635 const char *new_directory_name,
3636 struct directory_versions *info)
bb470f4e
EN
3637{
3638 const char *prev_dir;
3639 struct merged_info *dir_info = NULL;
0b55d930 3640 unsigned int offset, ret = 0;
bb470f4e
EN
3641
3642 /*
3643 * Some explanation of info->versions and info->offsets...
3644 *
3645 * process_entries() iterates over all relevant files AND
3646 * directories in reverse lexicographic order, and calls this
3647 * function. Thus, an example of the paths that process_entries()
3648 * could operate on (along with the directories for those paths
3649 * being shown) is:
3650 *
3651 * xtract.c ""
3652 * tokens.txt ""
3653 * src/moduleB/umm.c src/moduleB
3654 * src/moduleB/stuff.h src/moduleB
3655 * src/moduleB/baz.c src/moduleB
3656 * src/moduleB src
3657 * src/moduleA/foo.c src/moduleA
3658 * src/moduleA/bar.c src/moduleA
3659 * src/moduleA src
3660 * src ""
3661 * Makefile ""
3662 *
3663 * info->versions:
3664 *
3665 * always contains the unprocessed entries and their
3666 * version_info information. For example, after the first five
3667 * entries above, info->versions would be:
3668 *
3669 * xtract.c <xtract.c's version_info>
3670 * token.txt <token.txt's version_info>
3671 * umm.c <src/moduleB/umm.c's version_info>
3672 * stuff.h <src/moduleB/stuff.h's version_info>
3673 * baz.c <src/moduleB/baz.c's version_info>
3674 *
3675 * Once a subdirectory is completed we remove the entries in
3676 * that subdirectory from info->versions, writing it as a tree
3677 * (write_tree()). Thus, as soon as we get to src/moduleB,
3678 * info->versions would be updated to
3679 *
3680 * xtract.c <xtract.c's version_info>
3681 * token.txt <token.txt's version_info>
3682 * moduleB <src/moduleB's version_info>
3683 *
3684 * info->offsets:
3685 *
3686 * helps us track which entries in info->versions correspond to
3687 * which directories. When we are N directories deep (e.g. 4
3688 * for src/modA/submod/subdir/), we have up to N+1 unprocessed
3689 * directories (+1 because of toplevel dir). Corresponding to
3690 * the info->versions example above, after processing five entries
3691 * info->offsets will be:
3692 *
3693 * "" 0
3694 * src/moduleB 2
3695 *
3696 * which is used to know that xtract.c & token.txt are from the
3697 * toplevel dirctory, while umm.c & stuff.h & baz.c are from the
3698 * src/moduleB directory. Again, following the example above,
3699 * once we need to process src/moduleB, then info->offsets is
3700 * updated to
3701 *
3702 * "" 0
3703 * src 2
3704 *
3705 * which says that moduleB (and only moduleB so far) is in the
3706 * src directory.
3707 *
3708 * One unique thing to note about info->offsets here is that
3709 * "src" was not added to info->offsets until there was a path
3710 * (a file OR directory) immediately below src/ that got
3711 * processed.
3712 *
3713 * Since process_entry() just appends new entries to info->versions,
3714 * write_completed_directory() only needs to do work if the next path
3715 * is in a directory that is different than the last directory found
3716 * in info->offsets.
3717 */
3718
3719 /*
3720 * If we are working with the same directory as the last entry, there
3721 * is no work to do. (See comments above the directory_name member of
3722 * struct merged_info for why we can use pointer comparison instead of
3723 * strcmp here.)
3724 */
3725 if (new_directory_name == info->last_directory)
0b55d930 3726 return 0;
bb470f4e
EN
3727
3728 /*
3729 * If we are just starting (last_directory is NULL), or last_directory
3730 * is a prefix of the current directory, then we can just update
3731 * info->offsets to record the offset where we started this directory
3732 * and update last_directory to have quick access to it.
3733 */
3734 if (info->last_directory == NULL ||
3735 !strncmp(new_directory_name, info->last_directory,
3736 info->last_directory_len)) {
3737 uintptr_t offset = info->versions.nr;
3738
3739 info->last_directory = new_directory_name;
3740 info->last_directory_len = strlen(info->last_directory);
3741 /*
3742 * Record the offset into info->versions where we will
3743 * start recording basenames of paths found within
3744 * new_directory_name.
3745 */
3746 string_list_append(&info->offsets,
3747 info->last_directory)->util = (void*)offset;
0b55d930 3748 return 0;
bb470f4e
EN
3749 }
3750
3751 /*
3752 * The next entry that will be processed will be within
3753 * new_directory_name. Since at this point we know that
3754 * new_directory_name is within a different directory than
3755 * info->last_directory, we have all entries for info->last_directory
3756 * in info->versions and we need to create a tree object for them.
3757 */
3758 dir_info = strmap_get(&opt->priv->paths, info->last_directory);
3759 assert(dir_info);
3760 offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
3761 if (offset == info->versions.nr) {
3762 /*
3763 * Actually, we don't need to create a tree object in this
3764 * case. Whenever all files within a directory disappear
3765 * during the merge (e.g. unmodified on one side and
3766 * deleted on the other, or files were renamed elsewhere),
3767 * then we get here and the directory itself needs to be
3768 * omitted from its parent tree as well.
3769 */
3770 dir_info->is_null = 1;
3771 } else {
3772 /*
3773 * Write out the tree to the git object directory, and also
3774 * record the mode and oid in dir_info->result.
3775 */
3776 dir_info->is_null = 0;
3777 dir_info->result.mode = S_IFDIR;
0b55d930
JS
3778 if (write_tree(&dir_info->result.oid, &info->versions, offset,
3779 opt->repo->hash_algo->rawsz) < 0)
3780 ret = -1;
bb470f4e
EN
3781 }
3782
3783 /*
3784 * We've now used several entries from info->versions and one entry
3785 * from info->offsets, so we get rid of those values.
3786 */
3787 info->offsets.nr--;
3788 info->versions.nr = offset;
3789
3790 /*
3791 * Now we've taken care of the completed directory, but we need to
3792 * prepare things since future entries will be in
3793 * new_directory_name. (In particular, process_entry() will be
3794 * appending new entries to info->versions.) So, we need to make
3795 * sure new_directory_name is the last entry in info->offsets.
3796 */
3797 prev_dir = info->offsets.nr == 0 ? NULL :
3798 info->offsets.items[info->offsets.nr-1].string;
3799 if (new_directory_name != prev_dir) {
3800 uintptr_t c = info->versions.nr;
3801 string_list_append(&info->offsets,
3802 new_directory_name)->util = (void*)c;
3803 }
3804
3805 /* And, of course, we need to update last_directory to match. */
3806 info->last_directory = new_directory_name;
3807 info->last_directory_len = strlen(info->last_directory);
0b55d930
JS
3808
3809 return ret;
bb470f4e
EN
3810}
3811
6a02dd90 3812/* Per entry merge function */
92481d1b
JS
3813static int process_entry(struct merge_options *opt,
3814 const char *path,
3815 struct conflict_info *ci,
3816 struct directory_versions *dir_metadata)
6a02dd90 3817{
23366d2a
EN
3818 int df_file_index = 0;
3819
6a02dd90
EN
3820 VERIFY_CI(ci);
3821 assert(ci->filemask >= 0 && ci->filemask <= 7);
3822 /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
3823 assert(ci->match_mask == 0 || ci->match_mask == 3 ||
3824 ci->match_mask == 5 || ci->match_mask == 6);
3825
a9945bba
EN
3826 if (ci->dirmask) {
3827 record_entry_for_tree(dir_metadata, path, &ci->merged);
3828 if (ci->filemask == 0)
3829 /* nothing else to handle */
92481d1b 3830 return 0;
a9945bba
EN
3831 assert(ci->df_conflict);
3832 }
3833
0ccfa4e5
EN
3834 if (ci->df_conflict && ci->merged.result.mode == 0) {
3835 int i;
3836
3837 /*
3838 * directory no longer in the way, but we do have a file we
3839 * need to place here so we need to clean away the "directory
3840 * merges to nothing" result.
3841 */
3842 ci->df_conflict = 0;
3843 assert(ci->filemask != 0);
3844 ci->merged.clean = 0;
3845 ci->merged.is_null = 0;
3846 /* and we want to zero out any directory-related entries */
3847 ci->match_mask = (ci->match_mask & ~ci->dirmask);
3848 ci->dirmask = 0;
3849 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
3850 if (ci->filemask & (1 << i))
3851 continue;
3852 ci->stages[i].mode = 0;
14228447 3853 oidcpy(&ci->stages[i].oid, null_oid());
0ccfa4e5
EN
3854 }
3855 } else if (ci->df_conflict && ci->merged.result.mode != 0) {
23366d2a
EN
3856 /*
3857 * This started out as a D/F conflict, and the entries in
3858 * the competing directory were not removed by the merge as
3859 * evidenced by write_completed_directory() writing a value
3860 * to ci->merged.result.mode.
3861 */
3862 struct conflict_info *new_ci;
3863 const char *branch;
3864 const char *old_path = path;
3865 int i;
3866
3867 assert(ci->merged.result.mode == S_IFDIR);
3868
3869 /*
3870 * If filemask is 1, we can just ignore the file as having
3871 * been deleted on both sides. We do not want to overwrite
3872 * ci->merged.result, since it stores the tree for all the
3873 * files under it.
3874 */
3875 if (ci->filemask == 1) {
3876 ci->filemask = 0;
92481d1b 3877 return 0;
23366d2a
EN
3878 }
3879
3880 /*
3881 * This file still exists on at least one side, and we want
3882 * the directory to remain here, so we need to move this
3883 * path to some new location.
3884 */
62a15162 3885 new_ci = mem_pool_calloc(&opt->priv->pool, 1, sizeof(*new_ci));
6697ee01 3886
23366d2a
EN
3887 /* We don't really want new_ci->merged.result copied, but it'll
3888 * be overwritten below so it doesn't matter. We also don't
3889 * want any directory mode/oid values copied, but we'll zero
3890 * those out immediately. We do want the rest of ci copied.
3891 */
3892 memcpy(new_ci, ci, sizeof(*ci));
3893 new_ci->match_mask = (new_ci->match_mask & ~new_ci->dirmask);
3894 new_ci->dirmask = 0;
3895 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
3896 if (new_ci->filemask & (1 << i))
3897 continue;
3898 /* zero out any entries related to directories */
3899 new_ci->stages[i].mode = 0;
14228447 3900 oidcpy(&new_ci->stages[i].oid, null_oid());
23366d2a
EN
3901 }
3902
3903 /*
3904 * Find out which side this file came from; note that we
3905 * cannot just use ci->filemask, because renames could cause
3906 * the filemask to go back to 7. So we use dirmask, then
3907 * pick the opposite side's index.
3908 */
3909 df_file_index = (ci->dirmask & (1 << 1)) ? 2 : 1;
3910 branch = (df_file_index == 1) ? opt->branch1 : opt->branch2;
81afc794 3911 path = unique_path(opt, path, branch);
23366d2a
EN
3912 strmap_put(&opt->priv->paths, path, new_ci);
3913
cb260775
EN
3914 path_msg(opt, CONFLICT_FILE_DIRECTORY, 0,
3915 path, old_path, NULL, NULL,
23366d2a
EN
3916 _("CONFLICT (file/directory): directory in the way "
3917 "of %s from %s; moving it to %s instead."),
3918 old_path, branch, path);
3919
3920 /*
3921 * Zero out the filemask for the old ci. At this point, ci
3922 * was just an entry for a directory, so we don't need to
3923 * do anything more with it.
3924 */
3925 ci->filemask = 0;
3926
3927 /*
3928 * Now note that we're working on the new entry (path was
3929 * updated above.
3930 */
3931 ci = new_ci;
6a02dd90
EN
3932 }
3933
3934 /*
3935 * NOTE: Below there is a long switch-like if-elseif-elseif... block
3936 * which the code goes through even for the df_conflict cases
23366d2a 3937 * above.
6a02dd90
EN
3938 */
3939 if (ci->match_mask) {
a492d533 3940 ci->merged.clean = !ci->df_conflict && !ci->path_conflict;
6a02dd90
EN
3941 if (ci->match_mask == 6) {
3942 /* stages[1] == stages[2] */
3943 ci->merged.result.mode = ci->stages[1].mode;
3944 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
3945 } else {
3946 /* determine the mask of the side that didn't match */
3947 unsigned int othermask = 7 & ~ci->match_mask;
3948 int side = (othermask == 4) ? 2 : 1;
3949
3950 ci->merged.result.mode = ci->stages[side].mode;
3951 ci->merged.is_null = !ci->merged.result.mode;
a492d533
EN
3952 if (ci->merged.is_null)
3953 ci->merged.clean = 1;
6a02dd90
EN
3954 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
3955
3956 assert(othermask == 2 || othermask == 4);
3957 assert(ci->merged.is_null ==
3958 (ci->filemask == ci->match_mask));
3959 }
3960 } else if (ci->filemask >= 6 &&
3961 (S_IFMT & ci->stages[1].mode) !=
3962 (S_IFMT & ci->stages[2].mode)) {
4ef88fc3
EN
3963 /* Two different items from (file/submodule/symlink) */
3964 if (opt->priv->call_depth) {
3965 /* Just use the version from the merge base */
3966 ci->merged.clean = 0;
3967 oidcpy(&ci->merged.result.oid, &ci->stages[0].oid);
3968 ci->merged.result.mode = ci->stages[0].mode;
3969 ci->merged.is_null = (ci->merged.result.mode == 0);
3970 } else {
3971 /* Handle by renaming one or both to separate paths. */
3972 unsigned o_mode = ci->stages[0].mode;
3973 unsigned a_mode = ci->stages[1].mode;
3974 unsigned b_mode = ci->stages[2].mode;
3975 struct conflict_info *new_ci;
3976 const char *a_path = NULL, *b_path = NULL;
3977 int rename_a = 0, rename_b = 0;
3978
62a15162
EN
3979 new_ci = mem_pool_alloc(&opt->priv->pool,
3980 sizeof(*new_ci));
4ef88fc3
EN
3981
3982 if (S_ISREG(a_mode))
3983 rename_a = 1;
3984 else if (S_ISREG(b_mode))
3985 rename_b = 1;
3986 else {
3987 rename_a = 1;
3988 rename_b = 1;
3989 }
3990
cb260775
EN
3991 if (rename_a)
3992 a_path = unique_path(opt, path, opt->branch1);
3993 if (rename_b)
3994 b_path = unique_path(opt, path, opt->branch2);
3995
0e59f7ad 3996 if (rename_a && rename_b) {
cb260775
EN
3997 path_msg(opt, CONFLICT_DISTINCT_MODES, 0,
3998 path, a_path, b_path, NULL,
0e59f7ad
AH
3999 _("CONFLICT (distinct types): %s had "
4000 "different types on each side; "
4001 "renamed both of them so each can "
4002 "be recorded somewhere."),
4003 path);
4004 } else {
cb260775
EN
4005 path_msg(opt, CONFLICT_DISTINCT_MODES, 0,
4006 path, rename_a ? a_path : b_path,
4007 NULL, NULL,
0e59f7ad
AH
4008 _("CONFLICT (distinct types): %s had "
4009 "different types on each side; "
4010 "renamed one of them so each can be "
4011 "recorded somewhere."),
4012 path);
4013 }
4ef88fc3
EN
4014
4015 ci->merged.clean = 0;
4016 memcpy(new_ci, ci, sizeof(*new_ci));
4017
4018 /* Put b into new_ci, removing a from stages */
4019 new_ci->merged.result.mode = ci->stages[2].mode;
4020 oidcpy(&new_ci->merged.result.oid, &ci->stages[2].oid);
4021 new_ci->stages[1].mode = 0;
14228447 4022 oidcpy(&new_ci->stages[1].oid, null_oid());
4ef88fc3
EN
4023 new_ci->filemask = 5;
4024 if ((S_IFMT & b_mode) != (S_IFMT & o_mode)) {
4025 new_ci->stages[0].mode = 0;
14228447 4026 oidcpy(&new_ci->stages[0].oid, null_oid());
4ef88fc3
EN
4027 new_ci->filemask = 4;
4028 }
4029
4030 /* Leave only a in ci, fixing stages. */
4031 ci->merged.result.mode = ci->stages[1].mode;
4032 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
4033 ci->stages[2].mode = 0;
14228447 4034 oidcpy(&ci->stages[2].oid, null_oid());
4ef88fc3
EN
4035 ci->filemask = 3;
4036 if ((S_IFMT & a_mode) != (S_IFMT & o_mode)) {
4037 ci->stages[0].mode = 0;
14228447 4038 oidcpy(&ci->stages[0].oid, null_oid());
4ef88fc3
EN
4039 ci->filemask = 2;
4040 }
4041
4042 /* Insert entries into opt->priv_paths */
4043 assert(rename_a || rename_b);
cb260775 4044 if (rename_a)
4ef88fc3 4045 strmap_put(&opt->priv->paths, a_path, ci);
4ef88fc3 4046
cb260775 4047 if (!rename_b)
4ef88fc3
EN
4048 b_path = path;
4049 strmap_put(&opt->priv->paths, b_path, new_ci);
4050
62a15162 4051 if (rename_a && rename_b)
4ef88fc3 4052 strmap_remove(&opt->priv->paths, path, 0);
4ef88fc3
EN
4053
4054 /*
4055 * Do special handling for b_path since process_entry()
4056 * won't be called on it specially.
4057 */
4058 strmap_put(&opt->priv->conflicted, b_path, new_ci);
4059 record_entry_for_tree(dir_metadata, b_path,
4060 &new_ci->merged);
4061
4062 /*
4063 * Remaining code for processing this entry should
4064 * think in terms of processing a_path.
4065 */
4066 if (a_path)
4067 path = a_path;
4068 }
6a02dd90 4069 } else if (ci->filemask >= 6) {
991bbdca
EN
4070 /* Need a two-way or three-way content merge */
4071 struct version_info merged_file;
92481d1b 4072 int clean_merge;
991bbdca
EN
4073 struct version_info *o = &ci->stages[0];
4074 struct version_info *a = &ci->stages[1];
4075 struct version_info *b = &ci->stages[2];
4076
4077 clean_merge = handle_content_merge(opt, path, o, a, b,
4078 ci->pathnames,
4079 opt->priv->call_depth * 2,
4080 &merged_file);
92481d1b
JS
4081 if (clean_merge < 0)
4082 return -1;
991bbdca
EN
4083 ci->merged.clean = clean_merge &&
4084 !ci->df_conflict && !ci->path_conflict;
4085 ci->merged.result.mode = merged_file.mode;
4086 ci->merged.is_null = (merged_file.mode == 0);
4087 oidcpy(&ci->merged.result.oid, &merged_file.oid);
4088 if (clean_merge && ci->df_conflict) {
4089 assert(df_file_index == 1 || df_file_index == 2);
4090 ci->filemask = 1 << df_file_index;
4091 ci->stages[df_file_index].mode = merged_file.mode;
4092 oidcpy(&ci->stages[df_file_index].oid, &merged_file.oid);
4093 }
4094 if (!clean_merge) {
4095 const char *reason = _("content");
4096 if (ci->filemask == 6)
4097 reason = _("add/add");
4098 if (S_ISGITLINK(merged_file.mode))
4099 reason = _("submodule");
cb260775
EN
4100 path_msg(opt, CONFLICT_CONTENTS, 0,
4101 path, NULL, NULL, NULL,
991bbdca
EN
4102 _("CONFLICT (%s): Merge conflict in %s"),
4103 reason, path);
4104 }
6a02dd90
EN
4105 } else if (ci->filemask == 3 || ci->filemask == 5) {
4106 /* Modify/delete */
c5a6f655
EN
4107 const char *modify_branch, *delete_branch;
4108 int side = (ci->filemask == 5) ? 2 : 1;
4109 int index = opt->priv->call_depth ? 0 : side;
4110
4111 ci->merged.result.mode = ci->stages[index].mode;
4112 oidcpy(&ci->merged.result.oid, &ci->stages[index].oid);
4113 ci->merged.clean = 0;
4114
4115 modify_branch = (side == 1) ? opt->branch1 : opt->branch2;
4116 delete_branch = (side == 1) ? opt->branch2 : opt->branch1;
4117
3860220b
EN
4118 if (opt->renormalize &&
4119 blob_unchanged(opt, &ci->stages[0], &ci->stages[side],
4120 path)) {
d30126c2
EN
4121 if (!ci->path_conflict) {
4122 /*
4123 * Blob unchanged after renormalization, so
4124 * there's no modify/delete conflict after all;
4125 * we can just remove the file.
4126 */
4127 ci->merged.is_null = 1;
4128 ci->merged.clean = 1;
4129 /*
4130 * file goes away => even if there was a
4131 * directory/file conflict there isn't one now.
4132 */
4133 ci->df_conflict = 0;
4134 } else {
4135 /* rename/delete, so conflict remains */
4136 }
3860220b
EN
4137 } else if (ci->path_conflict &&
4138 oideq(&ci->stages[0].oid, &ci->stages[side].oid)) {
2e91ddd2
EN
4139 /*
4140 * This came from a rename/delete; no action to take,
4141 * but avoid printing "modify/delete" conflict notice
4142 * since the contents were not modified.
4143 */
4144 } else {
cb260775
EN
4145 path_msg(opt, CONFLICT_MODIFY_DELETE, 0,
4146 path, NULL, NULL, NULL,
2e91ddd2
EN
4147 _("CONFLICT (modify/delete): %s deleted in %s "
4148 "and modified in %s. Version %s of %s left "
4149 "in tree."),
4150 path, delete_branch, modify_branch,
4151 modify_branch, path);
4152 }
6a02dd90
EN
4153 } else if (ci->filemask == 2 || ci->filemask == 4) {
4154 /* Added on one side */
4155 int side = (ci->filemask == 4) ? 2 : 1;
4156 ci->merged.result.mode = ci->stages[side].mode;
4157 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
53e88a03 4158 ci->merged.clean = !ci->df_conflict && !ci->path_conflict;
6a02dd90
EN
4159 } else if (ci->filemask == 1) {
4160 /* Deleted on both sides */
4161 ci->merged.is_null = 1;
4162 ci->merged.result.mode = 0;
14228447 4163 oidcpy(&ci->merged.result.oid, null_oid());
a492d533 4164 assert(!ci->df_conflict);
53e88a03 4165 ci->merged.clean = !ci->path_conflict;
6a02dd90
EN
4166 }
4167
4168 /*
4169 * If still conflicted, record it separately. This allows us to later
4170 * iterate over just conflicted entries when updating the index instead
4171 * of iterating over all entries.
4172 */
4173 if (!ci->merged.clean)
4174 strmap_put(&opt->priv->conflicted, path, ci);
ef68c3d8
EN
4175
4176 /* Record metadata for ci->merged in dir_metadata */
a9945bba 4177 record_entry_for_tree(dir_metadata, path, &ci->merged);
92481d1b 4178 return 0;
6a02dd90
EN
4179}
4180
2bff554b
EN
4181static void prefetch_for_content_merges(struct merge_options *opt,
4182 struct string_list *plist)
4183{
4184 struct string_list_item *e;
4185 struct oid_array to_fetch = OID_ARRAY_INIT;
4186
4187 if (opt->repo != the_repository || !has_promisor_remote())
4188 return;
4189
4190 for (e = &plist->items[plist->nr-1]; e >= plist->items; --e) {
4191 /* char *path = e->string; */
4192 struct conflict_info *ci = e->util;
4193 int i;
4194
4195 /* Ignore clean entries */
4196 if (ci->merged.clean)
4197 continue;
4198
4199 /* Ignore entries that don't need a content merge */
4200 if (ci->match_mask || ci->filemask < 6 ||
4201 !S_ISREG(ci->stages[1].mode) ||
4202 !S_ISREG(ci->stages[2].mode) ||
4203 oideq(&ci->stages[1].oid, &ci->stages[2].oid))
4204 continue;
4205
4206 /* Also don't need content merge if base matches either side */
4207 if (ci->filemask == 7 &&
4208 S_ISREG(ci->stages[0].mode) &&
4209 (oideq(&ci->stages[0].oid, &ci->stages[1].oid) ||
4210 oideq(&ci->stages[0].oid, &ci->stages[2].oid)))
4211 continue;
4212
4213 for (i = 0; i < 3; i++) {
4214 unsigned side_mask = (1 << i);
4215 struct version_info *vi = &ci->stages[i];
4216
4217 if ((ci->filemask & side_mask) &&
4218 S_ISREG(vi->mode) &&
4219 oid_object_info_extended(opt->repo, &vi->oid, NULL,
4220 OBJECT_INFO_FOR_PREFETCH))
4221 oid_array_append(&to_fetch, &vi->oid);
4222 }
4223 }
4224
4225 promisor_remote_get_direct(opt->repo, to_fetch.oid, to_fetch.nr);
4226 oid_array_clear(&to_fetch);
4227}
4228
0b55d930
JS
4229static int process_entries(struct merge_options *opt,
4230 struct object_id *result_oid)
231e2dd4 4231{
6a02dd90
EN
4232 struct hashmap_iter iter;
4233 struct strmap_entry *e;
8adffaa8
EN
4234 struct string_list plist = STRING_LIST_INIT_NODUP;
4235 struct string_list_item *entry;
bb470f4e
EN
4236 struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
4237 STRING_LIST_INIT_NODUP,
4238 NULL, 0 };
0b55d930 4239 int ret = 0;
6a02dd90 4240
557ac035 4241 trace2_region_enter("merge", "process_entries setup", opt->repo);
6a02dd90
EN
4242 if (strmap_empty(&opt->priv->paths)) {
4243 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
0b55d930 4244 return 0;
6a02dd90
EN
4245 }
4246
8adffaa8 4247 /* Hack to pre-allocate plist to the desired size */
557ac035 4248 trace2_region_enter("merge", "plist grow", opt->repo);
8adffaa8 4249 ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
557ac035 4250 trace2_region_leave("merge", "plist grow", opt->repo);
8adffaa8
EN
4251
4252 /* Put every entry from paths into plist, then sort */
557ac035 4253 trace2_region_enter("merge", "plist copy", opt->repo);
6a02dd90 4254 strmap_for_each_entry(&opt->priv->paths, &iter, e) {
8adffaa8
EN
4255 string_list_append(&plist, e->key)->util = e->value;
4256 }
557ac035
EN
4257 trace2_region_leave("merge", "plist copy", opt->repo);
4258
4259 trace2_region_enter("merge", "plist special sort", opt->repo);
5a3743da 4260 plist.cmp = sort_dirs_next_to_their_children;
8adffaa8 4261 string_list_sort(&plist);
557ac035
EN
4262 trace2_region_leave("merge", "plist special sort", opt->repo);
4263
4264 trace2_region_leave("merge", "process_entries setup", opt->repo);
8adffaa8
EN
4265
4266 /*
4267 * Iterate over the items in reverse order, so we can handle paths
4268 * below a directory before needing to handle the directory itself.
bb470f4e
EN
4269 *
4270 * This allows us to write subtrees before we need to write trees,
4271 * and it also enables sane handling of directory/file conflicts
4272 * (because it allows us to know whether the directory is still in
4273 * the way when it is time to process the file at the same path).
8adffaa8 4274 */
557ac035 4275 trace2_region_enter("merge", "processing", opt->repo);
2bff554b 4276 prefetch_for_content_merges(opt, &plist);
8adffaa8
EN
4277 for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
4278 char *path = entry->string;
6a02dd90
EN
4279 /*
4280 * NOTE: mi may actually be a pointer to a conflict_info, but
4281 * we have to check mi->clean first to see if it's safe to
4282 * reassign to such a pointer type.
4283 */
8adffaa8 4284 struct merged_info *mi = entry->util;
6a02dd90 4285
0b55d930
JS
4286 if (write_completed_directory(opt, mi->directory_name,
4287 &dir_metadata) < 0) {
4288 ret = -1;
4289 goto cleanup;
4290 }
a9945bba
EN
4291 if (mi->clean)
4292 record_entry_for_tree(&dir_metadata, path, mi);
4293 else {
8adffaa8 4294 struct conflict_info *ci = (struct conflict_info *)mi;
92481d1b
JS
4295 if (process_entry(opt, path, ci, &dir_metadata) < 0) {
4296 ret = -1;
4297 goto cleanup;
4298 };
8adffaa8 4299 }
6a02dd90 4300 }
557ac035 4301 trace2_region_leave("merge", "processing", opt->repo);
6a02dd90 4302
557ac035 4303 trace2_region_enter("merge", "process_entries cleanup", opt->repo);
bb470f4e
EN
4304 if (dir_metadata.offsets.nr != 1 ||
4305 (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
99d60545
ÆAB
4306 printf("dir_metadata.offsets.nr = %"PRIuMAX" (should be 1)\n",
4307 (uintmax_t)dir_metadata.offsets.nr);
bb470f4e
EN
4308 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
4309 (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
4310 fflush(stdout);
4311 BUG("dir_metadata accounting completely off; shouldn't happen");
4312 }
0b55d930
JS
4313 if (write_tree(result_oid, &dir_metadata.versions, 0,
4314 opt->repo->hash_algo->rawsz) < 0)
4315 ret = -1;
4316cleanup:
8adffaa8 4317 string_list_clear(&plist, 0);
a9945bba 4318 string_list_clear(&dir_metadata.versions, 0);
bb470f4e 4319 string_list_clear(&dir_metadata.offsets, 0);
557ac035 4320 trace2_region_leave("merge", "process_entries cleanup", opt->repo);
0b55d930
JS
4321
4322 return ret;
231e2dd4
EN
4323}
4324
04af1879
EN
4325/*** Function Grouping: functions related to merge_switch_to_result() ***/
4326
9fefce68
EN
4327static int checkout(struct merge_options *opt,
4328 struct tree *prev,
4329 struct tree *next)
4330{
6681ce5c
EN
4331 /* Switch the index/working copy from old to new */
4332 int ret;
4333 struct tree_desc trees[2];
4334 struct unpack_trees_options unpack_opts;
4335
4336 memset(&unpack_opts, 0, sizeof(unpack_opts));
4337 unpack_opts.head_idx = -1;
4338 unpack_opts.src_index = opt->repo->index;
4339 unpack_opts.dst_index = opt->repo->index;
4340
4341 setup_unpack_trees_porcelain(&unpack_opts, "merge");
4342
4343 /*
4344 * NOTE: if this were just "git checkout" code, we would probably
4345 * read or refresh the cache and check for a conflicted index, but
4346 * builtin/merge.c or sequencer.c really needs to read the index
4347 * and check for conflicted entries before starting merging for a
4348 * good user experience (no sense waiting for merges/rebases before
4349 * erroring out), so there's no reason to duplicate that work here.
4350 */
4351
4352 /* 2-way merge to the new branch */
4353 unpack_opts.update = 1;
4354 unpack_opts.merge = 1;
4355 unpack_opts.quiet = 0; /* FIXME: sequencer might want quiet? */
4356 unpack_opts.verbose_update = (opt->verbosity > 2);
4357 unpack_opts.fn = twoway_merge;
1b5f3733 4358 unpack_opts.preserve_ignored = 0; /* FIXME: !opts->overwrite_ignore */
6681ce5c
EN
4359 parse_tree(prev);
4360 init_tree_desc(&trees[0], prev->buffer, prev->size);
4361 parse_tree(next);
4362 init_tree_desc(&trees[1], next->buffer, next->size);
4363
4364 ret = unpack_trees(2, trees, &unpack_opts);
4365 clear_unpack_trees_porcelain(&unpack_opts);
6681ce5c 4366 return ret;
9fefce68
EN
4367}
4368
66b209b8 4369static int record_conflicted_index_entries(struct merge_options *opt)
9fefce68 4370{
ef2b3693
EN
4371 struct hashmap_iter iter;
4372 struct strmap_entry *e;
66b209b8
EN
4373 struct index_state *index = opt->repo->index;
4374 struct checkout state = CHECKOUT_INIT;
ef2b3693
EN
4375 int errs = 0;
4376 int original_cache_nr;
4377
66b209b8 4378 if (strmap_empty(&opt->priv->conflicted))
9fefce68
EN
4379 return 0;
4380
a3380639
DS
4381 /*
4382 * We are in a conflicted state. These conflicts might be inside
69576367
DS
4383 * sparse-directory entries, so check if any entries are outside
4384 * of the sparse-checkout cone preemptively.
4385 *
4386 * We set original_cache_nr below, but that might change if
a3380639
DS
4387 * index_name_pos() calls ask for paths within sparse directories.
4388 */
69576367
DS
4389 strmap_for_each_entry(&opt->priv->conflicted, &iter, e) {
4390 if (!path_in_sparse_checkout(e->key, index)) {
4391 ensure_full_index(index);
4392 break;
4393 }
4394 }
a3380639 4395
66b209b8
EN
4396 /* If any entries have skip_worktree set, we'll have to check 'em out */
4397 state.force = 1;
4398 state.quiet = 1;
4399 state.refresh_cache = 1;
4400 state.istate = index;
ef2b3693
EN
4401 original_cache_nr = index->cache_nr;
4402
3584cff7 4403 /* Append every entry from conflicted into index, then sort */
66b209b8 4404 strmap_for_each_entry(&opt->priv->conflicted, &iter, e) {
ef2b3693
EN
4405 const char *path = e->key;
4406 struct conflict_info *ci = e->value;
4407 int pos;
4408 struct cache_entry *ce;
4409 int i;
4410
4411 VERIFY_CI(ci);
4412
4413 /*
4414 * The index will already have a stage=0 entry for this path,
4415 * because we created an as-merged-as-possible version of the
4416 * file and checkout() moved the working copy and index over
4417 * to that version.
4418 *
4419 * However, previous iterations through this loop will have
4420 * added unstaged entries to the end of the cache which
4421 * ignore the standard alphabetical ordering of cache
4422 * entries and break invariants needed for index_name_pos()
4423 * to work. However, we know the entry we want is before
4424 * those appended cache entries, so do a temporary swap on
4425 * cache_nr to only look through entries of interest.
4426 */
4427 SWAP(index->cache_nr, original_cache_nr);
4428 pos = index_name_pos(index, path, strlen(path));
4429 SWAP(index->cache_nr, original_cache_nr);
4430 if (pos < 0) {
4431 if (ci->filemask != 1)
4432 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path);
4433 cache_tree_invalidate_path(index, path);
4434 } else {
4435 ce = index->cache[pos];
4436
4437 /*
4438 * Clean paths with CE_SKIP_WORKTREE set will not be
4439 * written to the working tree by the unpack_trees()
4440 * call in checkout(). Our conflicted entries would
4441 * have appeared clean to that code since we ignored
4442 * the higher order stages. Thus, we need override
4443 * the CE_SKIP_WORKTREE bit and manually write those
4444 * files to the working disk here.
ef2b3693 4445 */
ff033db7 4446 if (ce_skip_worktree(ce))
66b209b8 4447 errs |= checkout_entry(ce, &state, NULL, NULL);
ef2b3693
EN
4448
4449 /*
4450 * Mark this cache entry for removal and instead add
4451 * new stage>0 entries corresponding to the
4452 * conflicts. If there are many conflicted entries, we
4453 * want to avoid memmove'ing O(NM) entries by
4454 * inserting the new entries one at a time. So,
4455 * instead, we just add the new cache entries to the
4456 * end (ignoring normal index requirements on sort
4457 * order) and sort the index once we're all done.
4458 */
4459 ce->ce_flags |= CE_REMOVE;
4460 }
4461
4462 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
4463 struct version_info *vi;
4464 if (!(ci->filemask & (1ul << i)))
4465 continue;
4466 vi = &ci->stages[i];
4467 ce = make_cache_entry(index, vi->mode, &vi->oid,
4468 path, i+1, 0);
4469 add_index_entry(index, ce, ADD_CACHE_JUST_APPEND);
4470 }
4471 }
4472
4473 /*
4474 * Remove the unused cache entries (and invalidate the relevant
4475 * cache-trees), then sort the index entries to get the conflicted
4476 * entries we added to the end into their right locations.
4477 */
4478 remove_marked_cache_entries(index, 1);
72b30910
EN
4479 /*
4480 * No need for STABLE_QSORT -- cmp_cache_name_compare sorts primarily
4481 * on filename and secondarily on stage, and (name, stage #) are a
4482 * unique tuple.
4483 */
ef2b3693
EN
4484 QSORT(index->cache, index->cache_nr, cmp_cache_name_compare);
4485
4486 return errs;
9fefce68
EN
4487}
4488
4057523a
CW
4489static void print_submodule_conflict_suggestion(struct string_list *csub) {
4490 struct string_list_item *item;
4491 struct strbuf msg = STRBUF_INIT;
4492 struct strbuf tmp = STRBUF_INIT;
4493 struct strbuf subs = STRBUF_INIT;
4494
4495 if (!csub->nr)
4496 return;
4497
565577ed 4498 strbuf_add_separated_string_list(&subs, " ", csub);
4057523a
CW
4499 for_each_string_list_item(item, csub) {
4500 struct conflicted_submodule_item *util = item->util;
4501
565577ed
EN
4502 /*
4503 * NEEDSWORK: The steps to resolve these errors deserve a more
4504 * detailed explanation than what is currently printed below.
4505 */
4057523a 4506 if (util->flag == CONFLICT_SUBMODULE_NOT_INITIALIZED ||
565577ed
EN
4507 util->flag == CONFLICT_SUBMODULE_HISTORY_NOT_AVAILABLE)
4508 continue;
a5834b77 4509
4057523a 4510 /*
a5834b77
EN
4511 * TRANSLATORS: This is a line of advice to resolve a merge
4512 * conflict in a submodule. The first argument is the submodule
4513 * name, and the second argument is the abbreviated id of the
4514 * commit that needs to be merged. For example:
4515 * - go to submodule (mysubmodule), and either merge commit abc1234"
4057523a 4516 */
a5834b77
EN
4517 strbuf_addf(&tmp, _(" - go to submodule (%s), and either merge commit %s\n"
4518 " or update to an existing commit which has merged those changes\n"),
4519 item->string, util->abbrev);
4057523a 4520 }
a5834b77
EN
4521
4522 /*
4523 * TRANSLATORS: This is a detailed message for resolving submodule
4524 * conflicts. The first argument is string containing one step per
4525 * submodule. The second is a space-separated list of submodule names.
4526 */
4527 strbuf_addf(&msg,
4528 _("Recursive merging with submodules currently only supports trivial cases.\n"
4529 "Please manually handle the merging of each conflicted submodule.\n"
4530 "This can be accomplished with the following steps:\n"
4531 "%s"
4532 " - come back to superproject and run:\n\n"
4533 " git add %s\n\n"
4534 " to record the above merge or update\n"
4535 " - resolve any other conflicts in the superproject\n"
4536 " - commit the resulting index in the superproject\n"),
4537 tmp.buf, subs.buf);
4057523a
CW
4538
4539 printf("%s", msg.buf);
a5834b77 4540
4057523a
CW
4541 strbuf_release(&subs);
4542 strbuf_release(&tmp);
4543 strbuf_release(&msg);
4544}
4545
a34edae6 4546void merge_display_update_messages(struct merge_options *opt,
de905811 4547 int detailed,
a34edae6
EN
4548 struct merge_result *result)
4549{
4550 struct merge_options_internal *opti = result->priv;
4551 struct hashmap_iter iter;
4552 struct strmap_entry *e;
4553 struct string_list olist = STRING_LIST_INIT_NODUP;
a34edae6
EN
4554
4555 if (opt->record_conflict_msgs_as_headers)
4556 BUG("Either display conflict messages or record them as headers, not both");
4557
4558 trace2_region_enter("merge", "display messages", opt->repo);
4559
4560 /* Hack to pre-allocate olist to the desired size */
6debb752 4561 ALLOC_GROW(olist.items, strmap_get_size(&opti->conflicts),
a34edae6
EN
4562 olist.alloc);
4563
4564 /* Put every entry from output into olist, then sort */
6debb752 4565 strmap_for_each_entry(&opti->conflicts, &iter, e) {
a34edae6
EN
4566 string_list_append(&olist, e->key)->util = e->value;
4567 }
4568 string_list_sort(&olist);
4569
4570 /* Iterate over the items, printing them */
6debb752
JS
4571 for (int path_nr = 0; path_nr < olist.nr; ++path_nr) {
4572 struct string_list *conflicts = olist.items[path_nr].util;
de905811
EN
4573 for (int i = 0; i < conflicts->nr; i++) {
4574 struct logical_conflict_info *info =
4575 conflicts->items[i].util;
4576
4577 if (detailed) {
4578 printf("%lu", (unsigned long)info->paths.nr);
4579 putchar('\0');
4580 for (int n = 0; n < info->paths.nr; n++) {
4581 fputs(info->paths.v[n], stdout);
4582 putchar('\0');
4583 }
4584 fputs(type_short_descriptions[info->type],
4585 stdout);
4586 putchar('\0');
4587 }
6debb752 4588 puts(conflicts->items[i].string);
de905811
EN
4589 if (detailed)
4590 putchar('\0');
4591 }
a34edae6
EN
4592 }
4593 string_list_clear(&olist, 0);
4594
4057523a
CW
4595 print_submodule_conflict_suggestion(&opti->conflicted_submodules);
4596
a34edae6
EN
4597 /* Also include needed rename limit adjustment now */
4598 diff_warn_rename_limit("merge.renamelimit",
4599 opti->renames.needed_limit, 0);
4600
4601 trace2_region_leave("merge", "display messages", opt->repo);
4602}
4603
fae26ce7
EN
4604void merge_get_conflicted_files(struct merge_result *result,
4605 struct string_list *conflicted_files)
4606{
4607 struct hashmap_iter iter;
4608 struct strmap_entry *e;
4609 struct merge_options_internal *opti = result->priv;
4610
4611 strmap_for_each_entry(&opti->conflicted, &iter, e) {
4612 const char *path = e->key;
4613 struct conflict_info *ci = e->value;
4614 int i;
4615
4616 VERIFY_CI(ci);
4617
4618 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
4619 struct stage_info *si;
4620
4621 if (!(ci->filemask & (1ul << i)))
4622 continue;
4623
4624 si = xmalloc(sizeof(*si));
4625 si->stage = i+1;
4626 si->mode = ci->stages[i].mode;
4627 oidcpy(&si->oid, &ci->stages[i].oid);
4628 string_list_append(conflicted_files, path)->util = si;
4629 }
4630 }
4631 /* string_list_sort() uses a stable sort, so we're good */
4632 string_list_sort(conflicted_files);
4633}
4634
17e5574b
EN
4635void merge_switch_to_result(struct merge_options *opt,
4636 struct tree *head,
4637 struct merge_result *result,
4638 int update_worktree_and_index,
4639 int display_update_msgs)
4640{
9fefce68
EN
4641 assert(opt->priv == NULL);
4642 if (result->clean >= 0 && update_worktree_and_index) {
5291828d
EN
4643 const char *filename;
4644 FILE *fp;
9fefce68 4645
557ac035 4646 trace2_region_enter("merge", "checkout", opt->repo);
9fefce68
EN
4647 if (checkout(opt, head, result->tree)) {
4648 /* failure to function */
4649 result->clean = -1;
fef2b6da 4650 merge_finalize(opt, result);
1250dff3 4651 trace2_region_leave("merge", "checkout", opt->repo);
9fefce68
EN
4652 return;
4653 }
557ac035 4654 trace2_region_leave("merge", "checkout", opt->repo);
9fefce68 4655
557ac035 4656 trace2_region_enter("merge", "record_conflicted", opt->repo);
66b209b8
EN
4657 opt->priv = result->priv;
4658 if (record_conflicted_index_entries(opt)) {
9fefce68 4659 /* failure to function */
66b209b8 4660 opt->priv = NULL;
9fefce68 4661 result->clean = -1;
fef2b6da 4662 merge_finalize(opt, result);
1250dff3
JS
4663 trace2_region_leave("merge", "record_conflicted",
4664 opt->repo);
9fefce68
EN
4665 return;
4666 }
66b209b8 4667 opt->priv = NULL;
557ac035 4668 trace2_region_leave("merge", "record_conflicted", opt->repo);
5291828d
EN
4669
4670 trace2_region_enter("merge", "write_auto_merge", opt->repo);
4671 filename = git_path_auto_merge(opt->repo);
4672 fp = xfopen(filename, "w");
4673 fprintf(fp, "%s\n", oid_to_hex(&result->tree->object.oid));
4674 fclose(fp);
4675 trace2_region_leave("merge", "write_auto_merge", opt->repo);
9fefce68 4676 }
a34edae6 4677 if (display_update_msgs)
de905811 4678 merge_display_update_messages(opt, /* detailed */ 0, result);
9fefce68 4679
17e5574b
EN
4680 merge_finalize(opt, result);
4681}
4682
4683void merge_finalize(struct merge_options *opt,
4684 struct merge_result *result)
4685{
89422d29
EN
4686 struct merge_options_internal *opti = result->priv;
4687
ea305a68
EN
4688 if (opt->renormalize)
4689 git_attr_set_direction(GIT_ATTR_CHECKIN);
89422d29
EN
4690 assert(opt->priv == NULL);
4691
43e9c4ee 4692 clear_or_reinit_internal_opts(opti, 0);
89422d29 4693 FREE_AND_NULL(opti);
17e5574b
EN
4694}
4695
04af1879
EN
4696/*** Function Grouping: helper functions for merge_incore_*() ***/
4697
3639dfb3
EN
4698static struct tree *shift_tree_object(struct repository *repo,
4699 struct tree *one, struct tree *two,
4700 const char *subtree_shift)
4701{
4702 struct object_id shifted;
4703
4704 if (!*subtree_shift) {
4705 shift_tree(repo, &one->object.oid, &two->object.oid, &shifted, 0);
4706 } else {
4707 shift_tree_by(repo, &one->object.oid, &two->object.oid, &shifted,
4708 subtree_shift);
4709 }
4710 if (oideq(&two->object.oid, &shifted))
4711 return two;
4712 return lookup_tree(repo, &shifted);
4713}
4714
4296d8f1
EN
4715static inline void set_commit_tree(struct commit *c, struct tree *t)
4716{
4717 c->maybe_tree = t;
4718}
4719
4296d8f1
EN
4720static struct commit *make_virtual_commit(struct repository *repo,
4721 struct tree *tree,
4722 const char *comment)
4723{
4724 struct commit *commit = alloc_commit_node(repo);
4725
4726 set_merge_remote_desc(commit, comment, (struct object *)commit);
4727 set_commit_tree(commit, tree);
4728 commit->object.parsed = 1;
4729 return commit;
4730}
4731
231e2dd4
EN
4732static void merge_start(struct merge_options *opt, struct merge_result *result)
4733{
f5d9fbc2
EN
4734 struct rename_info *renames;
4735 int i;
6697ee01 4736 struct mem_pool *pool = NULL;
f5d9fbc2 4737
e4171b1b 4738 /* Sanity checks on opt */
557ac035 4739 trace2_region_enter("merge", "sanity checks", opt->repo);
e4171b1b
EN
4740 assert(opt->repo);
4741
4742 assert(opt->branch1 && opt->branch2);
4743
4744 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
4745 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
4746 assert(opt->rename_limit >= -1);
4747 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
4748 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
4749
4750 assert(opt->xdl_opts >= 0);
4751 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
4752 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
4753
6054d1aa
EN
4754 if (opt->msg_header_prefix)
4755 assert(opt->record_conflict_msgs_as_headers);
4756
e4171b1b
EN
4757 /*
4758 * detect_renames, verbosity, buffer_output, and obuf are ignored
4759 * fields that were used by "recursive" rather than "ort" -- but
4760 * sanity check them anyway.
4761 */
4762 assert(opt->detect_renames >= -1 &&
4763 opt->detect_renames <= DIFF_DETECT_COPY);
4764 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
4765 assert(opt->buffer_output <= 2);
4766 assert(opt->obuf.len == 0);
4767
4768 assert(opt->priv == NULL);
19ceb486
EN
4769 if (result->_properly_initialized != 0 &&
4770 result->_properly_initialized != RESULT_INITIALIZED)
4771 BUG("struct merge_result passed to merge_incore_*recursive() must be zeroed or filled with values from a previous run");
4772 assert(!!result->priv == !!result->_properly_initialized);
cf8937ac
EN
4773 if (result->priv) {
4774 opt->priv = result->priv;
4775 result->priv = NULL;
4776 /*
4777 * opt->priv non-NULL means we had results from a previous
4778 * run; do a few sanity checks that user didn't mess with
4779 * it in an obvious fashion.
4780 */
4781 assert(opt->priv->call_depth == 0);
4782 assert(!opt->priv->toplevel_dir ||
4783 0 == strlen(opt->priv->toplevel_dir));
4784 }
557ac035 4785 trace2_region_leave("merge", "sanity checks", opt->repo);
e4171b1b 4786
c8017176
EN
4787 /* Default to histogram diff. Actually, just hardcode it...for now. */
4788 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
4789
ea305a68
EN
4790 /* Handle attr direction stuff for renormalization */
4791 if (opt->renormalize)
4792 git_attr_set_direction(GIT_ATTR_CHECKOUT);
4793
e4171b1b 4794 /* Initialization of opt->priv, our internal merge data */
557ac035 4795 trace2_region_enter("merge", "allocate/init", opt->repo);
cf8937ac
EN
4796 if (opt->priv) {
4797 clear_or_reinit_internal_opts(opt->priv, 1);
4057523a 4798 string_list_init_nodup(&opt->priv->conflicted_submodules);
cf8937ac
EN
4799 trace2_region_leave("merge", "allocate/init", opt->repo);
4800 return;
4801 }
e4171b1b
EN
4802 opt->priv = xcalloc(1, sizeof(*opt->priv));
4803
f5d9fbc2
EN
4804 /* Initialization of various renames fields */
4805 renames = &opt->priv->renames;
62a15162
EN
4806 mem_pool_init(&opt->priv->pool, 0);
4807 pool = &opt->priv->pool;
f5d9fbc2 4808 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; i++) {
a49b55d5 4809 strintmap_init_with_options(&renames->dirs_removed[i],
6697ee01 4810 NOT_RELEVANT, pool, 0);
f5d9fbc2
EN
4811 strmap_init_with_options(&renames->dir_rename_count[i],
4812 NULL, 1);
4813 strmap_init_with_options(&renames->dir_renames[i],
4814 NULL, 0);
2734f2e3
EN
4815 /*
4816 * relevant_sources uses -1 for the default, because we need
4817 * to be able to distinguish not-in-strintmap from valid
4818 * relevant_source values from enum file_rename_relevance.
4819 * In particular, possibly_cache_new_pair() expects a negative
4820 * value for not-found entries.
4821 */
a49b55d5 4822 strintmap_init_with_options(&renames->relevant_sources[i],
2734f2e3 4823 -1 /* explicitly invalid */,
6697ee01 4824 pool, 0);
d29bd6d7
EN
4825 strmap_init_with_options(&renames->cached_pairs[i],
4826 NULL, 1);
4827 strset_init_with_options(&renames->cached_irrelevant[i],
4828 NULL, 1);
4829 strset_init_with_options(&renames->cached_target_names[i],
4830 NULL, 0);
f5d9fbc2 4831 }
d478f567
EN
4832 for (i = MERGE_SIDE1; i <= MERGE_SIDE2; i++) {
4833 strintmap_init_with_options(&renames->deferred[i].possible_trivial_merges,
6697ee01 4834 0, pool, 0);
d478f567 4835 strset_init_with_options(&renames->deferred[i].target_dirs,
6697ee01 4836 pool, 1);
d478f567
EN
4837 renames->deferred[i].trivial_merges_okay = 1; /* 1 == maybe */
4838 }
f5d9fbc2 4839
e4171b1b
EN
4840 /*
4841 * Although we initialize opt->priv->paths with strdup_strings=0,
4842 * that's just to avoid making yet another copy of an allocated
4843 * string. Putting the entry into paths means we are taking
62a15162 4844 * ownership, so we will later free it.
e4171b1b
EN
4845 *
4846 * In contrast, conflicted just has a subset of keys from paths, so
4847 * we don't want to free those (it'd be a duplicate free).
4848 */
6697ee01
EN
4849 strmap_init_with_options(&opt->priv->paths, pool, 0);
4850 strmap_init_with_options(&opt->priv->conflicted, pool, 0);
c5a6f655
EN
4851
4852 /*
6debb752
JS
4853 * keys & string_lists in conflicts will sometimes need to outlive
4854 * "paths", so it will have a copy of relevant keys. It's probably
4855 * a small subset of the overall paths that have special output.
c5a6f655 4856 */
6debb752 4857 strmap_init(&opt->priv->conflicts);
557ac035
EN
4858
4859 trace2_region_leave("merge", "allocate/init", opt->repo);
231e2dd4
EN
4860}
4861
64aceb6d
EN
4862static void merge_check_renames_reusable(struct merge_options *opt,
4863 struct merge_result *result,
4864 struct tree *merge_base,
4865 struct tree *side1,
4866 struct tree *side2)
4867{
4868 struct rename_info *renames;
4869 struct tree **merge_trees;
4870 struct merge_options_internal *opti = result->priv;
4871
4872 if (!opti)
4873 return;
4874
4875 renames = &opti->renames;
4876 merge_trees = renames->merge_trees;
cbdca289
EN
4877
4878 /*
4879 * Handle case where previous merge operation did not want cache to
4880 * take effect, e.g. because rename/rename(1to1) makes it invalid.
4881 */
4882 if (!merge_trees[0]) {
4883 assert(!merge_trees[0] && !merge_trees[1] && !merge_trees[2]);
4884 renames->cached_pairs_valid_side = 0; /* neither side valid */
4885 return;
4886 }
4887
4888 /*
4889 * Handle other cases; note that merge_trees[0..2] will only
4890 * be NULL if opti is, or if all three were manually set to
4891 * NULL by e.g. rename/rename(1to1) handling.
4892 */
64aceb6d
EN
4893 assert(merge_trees[0] && merge_trees[1] && merge_trees[2]);
4894
4895 /* Check if we meet a condition for re-using cached_pairs */
4896 if (oideq(&merge_base->object.oid, &merge_trees[2]->object.oid) &&
4897 oideq(&side1->object.oid, &result->tree->object.oid))
4898 renames->cached_pairs_valid_side = MERGE_SIDE1;
4899 else if (oideq(&merge_base->object.oid, &merge_trees[1]->object.oid) &&
4900 oideq(&side2->object.oid, &result->tree->object.oid))
4901 renames->cached_pairs_valid_side = MERGE_SIDE2;
4902 else
4903 renames->cached_pairs_valid_side = 0; /* neither side valid */
4904}
4905
04af1879
EN
4906/*** Function Grouping: merge_incore_*() and their internal variants ***/
4907
231e2dd4
EN
4908/*
4909 * Originally from merge_trees_internal(); heavily adapted, though.
4910 */
4911static void merge_ort_nonrecursive_internal(struct merge_options *opt,
4912 struct tree *merge_base,
4913 struct tree *side1,
4914 struct tree *side2,
4915 struct merge_result *result)
4916{
4917 struct object_id working_tree_oid;
4918
3639dfb3
EN
4919 if (opt->subtree_shift) {
4920 side2 = shift_tree_object(opt->repo, side1, side2,
4921 opt->subtree_shift);
4922 merge_base = shift_tree_object(opt->repo, side1, merge_base,
4923 opt->subtree_shift);
4924 }
4925
8b09a900 4926redo:
557ac035 4927 trace2_region_enter("merge", "collect_merge_info", opt->repo);
0c0d705b
EN
4928 if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
4929 /*
4930 * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
4931 * base, and 2-3) the trees for the two trees we're merging.
4932 */
4933 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
4934 oid_to_hex(&merge_base->object.oid),
4935 oid_to_hex(&side1->object.oid),
4936 oid_to_hex(&side2->object.oid));
4937 result->clean = -1;
4938 return;
4939 }
557ac035 4940 trace2_region_leave("merge", "collect_merge_info", opt->repo);
0c0d705b 4941
557ac035 4942 trace2_region_enter("merge", "renames", opt->repo);
231e2dd4
EN
4943 result->clean = detect_and_process_renames(opt, merge_base,
4944 side1, side2);
557ac035 4945 trace2_region_leave("merge", "renames", opt->repo);
8b09a900
EN
4946 if (opt->priv->renames.redo_after_renames == 2) {
4947 trace2_region_enter("merge", "reset_maps", opt->repo);
4948 clear_or_reinit_internal_opts(opt->priv, 1);
4949 trace2_region_leave("merge", "reset_maps", opt->repo);
4950 goto redo;
4951 }
557ac035
EN
4952
4953 trace2_region_enter("merge", "process_entries", opt->repo);
0b55d930
JS
4954 if (process_entries(opt, &working_tree_oid) < 0)
4955 result->clean = -1;
557ac035 4956 trace2_region_leave("merge", "process_entries", opt->repo);
231e2dd4
EN
4957
4958 /* Set return values */
2715e8a9 4959 result->path_messages = &opt->priv->conflicts;
6debb752 4960
0b55d930
JS
4961 if (result->clean >= 0) {
4962 result->tree = parse_tree_indirect(&working_tree_oid);
4963 /* existence of conflicted entries implies unclean */
4964 result->clean &= strmap_empty(&opt->priv->conflicted);
4965 }
231e2dd4
EN
4966 if (!opt->priv->call_depth) {
4967 result->priv = opt->priv;
19ceb486 4968 result->_properly_initialized = RESULT_INITIALIZED;
231e2dd4
EN
4969 opt->priv = NULL;
4970 }
4971}
4972
8119214f
EN
4973/*
4974 * Originally from merge_recursive_internal(); somewhat adapted, though.
4975 */
4976static void merge_ort_internal(struct merge_options *opt,
4977 struct commit_list *merge_bases,
4978 struct commit *h1,
4979 struct commit *h2,
4980 struct merge_result *result)
4981{
a59b8dd9 4982 struct commit *next;
8119214f
EN
4983 struct commit *merged_merge_bases;
4984 const char *ancestor_name;
4985 struct strbuf merge_base_abbrev = STRBUF_INIT;
4986
4987 if (!merge_bases) {
4988 merge_bases = get_merge_bases(h1, h2);
4989 /* See merge-ort.h:merge_incore_recursive() declaration NOTE */
4990 merge_bases = reverse_commit_list(merge_bases);
4991 }
4992
4993 merged_merge_bases = pop_commit(&merge_bases);
afe8a907 4994 if (!merged_merge_bases) {
8119214f
EN
4995 /* if there is no common ancestor, use an empty tree */
4996 struct tree *tree;
4997
4998 tree = lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);
4999 merged_merge_bases = make_virtual_commit(opt->repo, tree,
5000 "ancestor");
5001 ancestor_name = "empty tree";
5002 } else if (merge_bases) {
5003 ancestor_name = "merged common ancestors";
5004 } else {
5005 strbuf_add_unique_abbrev(&merge_base_abbrev,
5006 &merged_merge_bases->object.oid,
5007 DEFAULT_ABBREV);
5008 ancestor_name = merge_base_abbrev.buf;
5009 }
5010
a59b8dd9
EN
5011 for (next = pop_commit(&merge_bases); next;
5012 next = pop_commit(&merge_bases)) {
8119214f
EN
5013 const char *saved_b1, *saved_b2;
5014 struct commit *prev = merged_merge_bases;
5015
5016 opt->priv->call_depth++;
5017 /*
5018 * When the merge fails, the result contains files
5019 * with conflict markers. The cleanness flag is
5020 * ignored (unless indicating an error), it was never
5021 * actually used, as result of merge_trees has always
5022 * overwritten it: the committed "conflicts" were
5023 * already resolved.
5024 */
5025 saved_b1 = opt->branch1;
5026 saved_b2 = opt->branch2;
5027 opt->branch1 = "Temporary merge branch 1";
5028 opt->branch2 = "Temporary merge branch 2";
a59b8dd9 5029 merge_ort_internal(opt, NULL, prev, next, result);
8119214f
EN
5030 if (result->clean < 0)
5031 return;
5032 opt->branch1 = saved_b1;
5033 opt->branch2 = saved_b2;
5034 opt->priv->call_depth--;
5035
5036 merged_merge_bases = make_virtual_commit(opt->repo,
5037 result->tree,
5038 "merged tree");
5039 commit_list_insert(prev, &merged_merge_bases->parents);
a59b8dd9 5040 commit_list_insert(next, &merged_merge_bases->parents->next);
8119214f
EN
5041
5042 clear_or_reinit_internal_opts(opt->priv, 1);
5043 }
5044
5045 opt->ancestor = ancestor_name;
5046 merge_ort_nonrecursive_internal(opt,
5047 repo_get_commit_tree(opt->repo,
5048 merged_merge_bases),
5049 repo_get_commit_tree(opt->repo, h1),
5050 repo_get_commit_tree(opt->repo, h2),
5051 result);
5052 strbuf_release(&merge_base_abbrev);
5053 opt->ancestor = NULL; /* avoid accidental re-use of opt->ancestor */
5054}
5055
17e5574b
EN
5056void merge_incore_nonrecursive(struct merge_options *opt,
5057 struct tree *merge_base,
5058 struct tree *side1,
5059 struct tree *side2,
5060 struct merge_result *result)
5061{
557ac035
EN
5062 trace2_region_enter("merge", "incore_nonrecursive", opt->repo);
5063
5064 trace2_region_enter("merge", "merge_start", opt->repo);
231e2dd4 5065 assert(opt->ancestor != NULL);
64aceb6d 5066 merge_check_renames_reusable(opt, result, merge_base, side1, side2);
231e2dd4 5067 merge_start(opt, result);
64aceb6d
EN
5068 /*
5069 * Record the trees used in this merge, so if there's a next merge in
5070 * a cherry-pick or rebase sequence it might be able to take advantage
5071 * of the cached_pairs in that next merge.
5072 */
5073 opt->priv->renames.merge_trees[0] = merge_base;
5074 opt->priv->renames.merge_trees[1] = side1;
5075 opt->priv->renames.merge_trees[2] = side2;
557ac035
EN
5076 trace2_region_leave("merge", "merge_start", opt->repo);
5077
231e2dd4 5078 merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
557ac035 5079 trace2_region_leave("merge", "incore_nonrecursive", opt->repo);
17e5574b
EN
5080}
5081
5082void merge_incore_recursive(struct merge_options *opt,
5083 struct commit_list *merge_bases,
5084 struct commit *side1,
5085 struct commit *side2,
5086 struct merge_result *result)
5087{
557ac035
EN
5088 trace2_region_enter("merge", "incore_recursive", opt->repo);
5089
8119214f
EN
5090 /* We set the ancestor label based on the merge_bases */
5091 assert(opt->ancestor == NULL);
5092
557ac035 5093 trace2_region_enter("merge", "merge_start", opt->repo);
8119214f 5094 merge_start(opt, result);
557ac035
EN
5095 trace2_region_leave("merge", "merge_start", opt->repo);
5096
8119214f 5097 merge_ort_internal(opt, merge_bases, side1, side2, result);
557ac035 5098 trace2_region_leave("merge", "incore_recursive", opt->repo);
17e5574b 5099}