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