]> git.ipfire.org Git - thirdparty/git.git/blob - merge-ort.c
Merge branch 'en/merge-ort-impl'
[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 "cache-tree.h"
21 #include "diff.h"
22 #include "diffcore.h"
23 #include "dir.h"
24 #include "object-store.h"
25 #include "strmap.h"
26 #include "tree.h"
27 #include "unpack-trees.h"
28 #include "xdiff-interface.h"
29
30 /*
31 * We have many arrays of size 3. Whenever we have such an array, the
32 * indices refer to one of the sides of the three-way merge. This is so
33 * pervasive that the constants 0, 1, and 2 are used in many places in the
34 * code (especially in arithmetic operations to find the other side's index
35 * or to compute a relevant mask), but sometimes these enum names are used
36 * to aid code clarity.
37 *
38 * See also 'filemask' and 'dirmask' in struct conflict_info; the "ith side"
39 * referred to there is one of these three sides.
40 */
41 enum merge_side {
42 MERGE_BASE = 0,
43 MERGE_SIDE1 = 1,
44 MERGE_SIDE2 = 2
45 };
46
47 struct merge_options_internal {
48 /*
49 * paths: primary data structure in all of merge ort.
50 *
51 * The keys of paths:
52 * * are full relative paths from the toplevel of the repository
53 * (e.g. "drivers/firmware/raspberrypi.c").
54 * * store all relevant paths in the repo, both directories and
55 * files (e.g. drivers, drivers/firmware would also be included)
56 * * these keys serve to intern all the path strings, which allows
57 * us to do pointer comparison on directory names instead of
58 * strcmp; we just have to be careful to use the interned strings.
59 *
60 * The values of paths:
61 * * either a pointer to a merged_info, or a conflict_info struct
62 * * merged_info contains all relevant information for a
63 * non-conflicted entry.
64 * * conflict_info contains a merged_info, plus any additional
65 * information about a conflict such as the higher orders stages
66 * involved and the names of the paths those came from (handy
67 * once renames get involved).
68 * * a path may start "conflicted" (i.e. point to a conflict_info)
69 * and then a later step (e.g. three-way content merge) determines
70 * it can be cleanly merged, at which point it'll be marked clean
71 * and the algorithm will ignore any data outside the contained
72 * merged_info for that entry
73 * * If an entry remains conflicted, the merged_info portion of a
74 * conflict_info will later be filled with whatever version of
75 * the file should be placed in the working directory (e.g. an
76 * as-merged-as-possible variation that contains conflict markers).
77 */
78 struct strmap paths;
79
80 /*
81 * conflicted: a subset of keys->values from "paths"
82 *
83 * conflicted is basically an optimization between process_entries()
84 * and record_conflicted_index_entries(); the latter could loop over
85 * ALL the entries in paths AGAIN and look for the ones that are
86 * still conflicted, but since process_entries() has to loop over
87 * all of them, it saves the ones it couldn't resolve in this strmap
88 * so that record_conflicted_index_entries() can iterate just the
89 * relevant entries.
90 */
91 struct strmap conflicted;
92
93 /*
94 * current_dir_name: temporary var used in collect_merge_info_callback()
95 *
96 * Used to set merged_info.directory_name; see documentation for that
97 * variable and the requirements placed on that field.
98 */
99 const char *current_dir_name;
100
101 /* call_depth: recursion level counter for merging merge bases */
102 int call_depth;
103 };
104
105 struct version_info {
106 struct object_id oid;
107 unsigned short mode;
108 };
109
110 struct merged_info {
111 /* if is_null, ignore result. otherwise result has oid & mode */
112 struct version_info result;
113 unsigned is_null:1;
114
115 /*
116 * clean: whether the path in question is cleanly merged.
117 *
118 * see conflict_info.merged for more details.
119 */
120 unsigned clean:1;
121
122 /*
123 * basename_offset: offset of basename of path.
124 *
125 * perf optimization to avoid recomputing offset of final '/'
126 * character in pathname (0 if no '/' in pathname).
127 */
128 size_t basename_offset;
129
130 /*
131 * directory_name: containing directory name.
132 *
133 * Note that we assume directory_name is constructed such that
134 * strcmp(dir1_name, dir2_name) == 0 iff dir1_name == dir2_name,
135 * i.e. string equality is equivalent to pointer equality. For this
136 * to hold, we have to be careful setting directory_name.
137 */
138 const char *directory_name;
139 };
140
141 struct conflict_info {
142 /*
143 * merged: the version of the path that will be written to working tree
144 *
145 * WARNING: It is critical to check merged.clean and ensure it is 0
146 * before reading any conflict_info fields outside of merged.
147 * Allocated merge_info structs will always have clean set to 1.
148 * Allocated conflict_info structs will have merged.clean set to 0
149 * initially. The merged.clean field is how we know if it is safe
150 * to access other parts of conflict_info besides merged; if a
151 * conflict_info's merged.clean is changed to 1, the rest of the
152 * algorithm is not allowed to look at anything outside of the
153 * merged member anymore.
154 */
155 struct merged_info merged;
156
157 /* oids & modes from each of the three trees for this path */
158 struct version_info stages[3];
159
160 /* pathnames for each stage; may differ due to rename detection */
161 const char *pathnames[3];
162
163 /* Whether this path is/was involved in a directory/file conflict */
164 unsigned df_conflict:1;
165
166 /*
167 * For filemask and dirmask, the ith bit corresponds to whether the
168 * ith entry is a file (filemask) or a directory (dirmask). Thus,
169 * filemask & dirmask is always zero, and filemask | dirmask is at
170 * most 7 but can be less when a path does not appear as either a
171 * file or a directory on at least one side of history.
172 *
173 * Note that these masks are related to enum merge_side, as the ith
174 * entry corresponds to side i.
175 *
176 * These values come from a traverse_trees() call; more info may be
177 * found looking at tree-walk.h's struct traverse_info,
178 * particularly the documentation above the "fn" member (note that
179 * filemask = mask & ~dirmask from that documentation).
180 */
181 unsigned filemask:3;
182 unsigned dirmask:3;
183
184 /*
185 * Optimization to track which stages match, to avoid the need to
186 * recompute it in multiple steps. Either 0 or at least 2 bits are
187 * set; if at least 2 bits are set, their corresponding stages match.
188 */
189 unsigned match_mask:3;
190 };
191
192 /*
193 * For the next three macros, see warning for conflict_info.merged.
194 *
195 * In each of the below, mi is a struct merged_info*, and ci was defined
196 * as a struct conflict_info* (but we need to verify ci isn't actually
197 * pointed at a struct merged_info*).
198 *
199 * INITIALIZE_CI: Assign ci to mi but only if it's safe; set to NULL otherwise.
200 * VERIFY_CI: Ensure that something we assigned to a conflict_info* is one.
201 * ASSIGN_AND_VERIFY_CI: Similar to VERIFY_CI but do assignment first.
202 */
203 #define INITIALIZE_CI(ci, mi) do { \
204 (ci) = (!(mi) || (mi)->clean) ? NULL : (struct conflict_info *)(mi); \
205 } while (0)
206 #define VERIFY_CI(ci) assert(ci && !ci->merged.clean);
207 #define ASSIGN_AND_VERIFY_CI(ci, mi) do { \
208 (ci) = (struct conflict_info *)(mi); \
209 assert((ci) && !(mi)->clean); \
210 } while (0)
211
212 static void free_strmap_strings(struct strmap *map)
213 {
214 struct hashmap_iter iter;
215 struct strmap_entry *entry;
216
217 strmap_for_each_entry(map, &iter, entry) {
218 free((char*)entry->key);
219 }
220 }
221
222 static int err(struct merge_options *opt, const char *err, ...)
223 {
224 va_list params;
225 struct strbuf sb = STRBUF_INIT;
226
227 strbuf_addstr(&sb, "error: ");
228 va_start(params, err);
229 strbuf_vaddf(&sb, err, params);
230 va_end(params);
231
232 error("%s", sb.buf);
233 strbuf_release(&sb);
234
235 return -1;
236 }
237
238 static void setup_path_info(struct merge_options *opt,
239 struct string_list_item *result,
240 const char *current_dir_name,
241 int current_dir_name_len,
242 char *fullpath, /* we'll take over ownership */
243 struct name_entry *names,
244 struct name_entry *merged_version,
245 unsigned is_null, /* boolean */
246 unsigned df_conflict, /* boolean */
247 unsigned filemask,
248 unsigned dirmask,
249 int resolved /* boolean */)
250 {
251 /* result->util is void*, so mi is a convenience typed variable */
252 struct merged_info *mi;
253
254 assert(!is_null || resolved);
255 assert(!df_conflict || !resolved); /* df_conflict implies !resolved */
256 assert(resolved == (merged_version != NULL));
257
258 mi = xcalloc(1, resolved ? sizeof(struct merged_info) :
259 sizeof(struct conflict_info));
260 mi->directory_name = current_dir_name;
261 mi->basename_offset = current_dir_name_len;
262 mi->clean = !!resolved;
263 if (resolved) {
264 mi->result.mode = merged_version->mode;
265 oidcpy(&mi->result.oid, &merged_version->oid);
266 mi->is_null = !!is_null;
267 } else {
268 int i;
269 struct conflict_info *ci;
270
271 ASSIGN_AND_VERIFY_CI(ci, mi);
272 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
273 ci->pathnames[i] = fullpath;
274 ci->stages[i].mode = names[i].mode;
275 oidcpy(&ci->stages[i].oid, &names[i].oid);
276 }
277 ci->filemask = filemask;
278 ci->dirmask = dirmask;
279 ci->df_conflict = !!df_conflict;
280 if (dirmask)
281 /*
282 * Assume is_null for now, but if we have entries
283 * under the directory then when it is complete in
284 * write_completed_directory() it'll update this.
285 * Also, for D/F conflicts, we have to handle the
286 * directory first, then clear this bit and process
287 * the file to see how it is handled -- that occurs
288 * near the top of process_entry().
289 */
290 mi->is_null = 1;
291 }
292 strmap_put(&opt->priv->paths, fullpath, mi);
293 result->string = fullpath;
294 result->util = mi;
295 }
296
297 static int collect_merge_info_callback(int n,
298 unsigned long mask,
299 unsigned long dirmask,
300 struct name_entry *names,
301 struct traverse_info *info)
302 {
303 /*
304 * n is 3. Always.
305 * common ancestor (mbase) has mask 1, and stored in index 0 of names
306 * head of side 1 (side1) has mask 2, and stored in index 1 of names
307 * head of side 2 (side2) has mask 4, and stored in index 2 of names
308 */
309 struct merge_options *opt = info->data;
310 struct merge_options_internal *opti = opt->priv;
311 struct string_list_item pi; /* Path Info */
312 struct conflict_info *ci; /* typed alias to pi.util (which is void*) */
313 struct name_entry *p;
314 size_t len;
315 char *fullpath;
316 const char *dirname = opti->current_dir_name;
317 unsigned filemask = mask & ~dirmask;
318 unsigned match_mask = 0; /* will be updated below */
319 unsigned mbase_null = !(mask & 1);
320 unsigned side1_null = !(mask & 2);
321 unsigned side2_null = !(mask & 4);
322 unsigned side1_matches_mbase = (!side1_null && !mbase_null &&
323 names[0].mode == names[1].mode &&
324 oideq(&names[0].oid, &names[1].oid));
325 unsigned side2_matches_mbase = (!side2_null && !mbase_null &&
326 names[0].mode == names[2].mode &&
327 oideq(&names[0].oid, &names[2].oid));
328 unsigned sides_match = (!side1_null && !side2_null &&
329 names[1].mode == names[2].mode &&
330 oideq(&names[1].oid, &names[2].oid));
331
332 /*
333 * Note: When a path is a file on one side of history and a directory
334 * in another, we have a directory/file conflict. In such cases, if
335 * the conflict doesn't resolve from renames and deletions, then we
336 * always leave directories where they are and move files out of the
337 * way. Thus, while struct conflict_info has a df_conflict field to
338 * track such conflicts, we ignore that field for any directories at
339 * a path and only pay attention to it for files at the given path.
340 * The fact that we leave directories were they are also means that
341 * we do not need to worry about getting additional df_conflict
342 * information propagated from parent directories down to children
343 * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
344 * sets a newinfo.df_conflicts field specifically to propagate it).
345 */
346 unsigned df_conflict = (filemask != 0) && (dirmask != 0);
347
348 /* n = 3 is a fundamental assumption. */
349 if (n != 3)
350 BUG("Called collect_merge_info_callback wrong");
351
352 /*
353 * A bunch of sanity checks verifying that traverse_trees() calls
354 * us the way I expect. Could just remove these at some point,
355 * though maybe they are helpful to future code readers.
356 */
357 assert(mbase_null == is_null_oid(&names[0].oid));
358 assert(side1_null == is_null_oid(&names[1].oid));
359 assert(side2_null == is_null_oid(&names[2].oid));
360 assert(!mbase_null || !side1_null || !side2_null);
361 assert(mask > 0 && mask < 8);
362
363 /* Determine match_mask */
364 if (side1_matches_mbase)
365 match_mask = (side2_matches_mbase ? 7 : 3);
366 else if (side2_matches_mbase)
367 match_mask = 5;
368 else if (sides_match)
369 match_mask = 6;
370
371 /*
372 * Get the name of the relevant filepath, which we'll pass to
373 * setup_path_info() for tracking.
374 */
375 p = names;
376 while (!p->mode)
377 p++;
378 len = traverse_path_len(info, p->pathlen);
379
380 /* +1 in both of the following lines to include the NUL byte */
381 fullpath = xmalloc(len + 1);
382 make_traverse_path(fullpath, len + 1, info, p->path, p->pathlen);
383
384 /*
385 * If mbase, side1, and side2 all match, we can resolve early. Even
386 * if these are trees, there will be no renames or anything
387 * underneath.
388 */
389 if (side1_matches_mbase && side2_matches_mbase) {
390 /* mbase, side1, & side2 all match; use mbase as resolution */
391 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
392 names, names+0, mbase_null, 0,
393 filemask, dirmask, 1);
394 return mask;
395 }
396
397 /*
398 * Record information about the path so we can resolve later in
399 * process_entries.
400 */
401 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
402 names, NULL, 0, df_conflict, filemask, dirmask, 0);
403
404 ci = pi.util;
405 VERIFY_CI(ci);
406 ci->match_mask = match_mask;
407
408 /* If dirmask, recurse into subdirectories */
409 if (dirmask) {
410 struct traverse_info newinfo;
411 struct tree_desc t[3];
412 void *buf[3] = {NULL, NULL, NULL};
413 const char *original_dir_name;
414 int i, ret;
415
416 ci->match_mask &= filemask;
417 newinfo = *info;
418 newinfo.prev = info;
419 newinfo.name = p->path;
420 newinfo.namelen = p->pathlen;
421 newinfo.pathlen = st_add3(newinfo.pathlen, p->pathlen, 1);
422 /*
423 * If this directory we are about to recurse into cared about
424 * its parent directory (the current directory) having a D/F
425 * conflict, then we'd propagate the masks in this way:
426 * newinfo.df_conflicts |= (mask & ~dirmask);
427 * But we don't worry about propagating D/F conflicts. (See
428 * comment near setting of local df_conflict variable near
429 * the beginning of this function).
430 */
431
432 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
433 if (i == 1 && side1_matches_mbase)
434 t[1] = t[0];
435 else if (i == 2 && side2_matches_mbase)
436 t[2] = t[0];
437 else if (i == 2 && sides_match)
438 t[2] = t[1];
439 else {
440 const struct object_id *oid = NULL;
441 if (dirmask & 1)
442 oid = &names[i].oid;
443 buf[i] = fill_tree_descriptor(opt->repo,
444 t + i, oid);
445 }
446 dirmask >>= 1;
447 }
448
449 original_dir_name = opti->current_dir_name;
450 opti->current_dir_name = pi.string;
451 ret = traverse_trees(NULL, 3, t, &newinfo);
452 opti->current_dir_name = original_dir_name;
453
454 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
455 free(buf[i]);
456
457 if (ret < 0)
458 return -1;
459 }
460
461 return mask;
462 }
463
464 static int collect_merge_info(struct merge_options *opt,
465 struct tree *merge_base,
466 struct tree *side1,
467 struct tree *side2)
468 {
469 int ret;
470 struct tree_desc t[3];
471 struct traverse_info info;
472 const char *toplevel_dir_placeholder = "";
473
474 opt->priv->current_dir_name = toplevel_dir_placeholder;
475 setup_traverse_info(&info, toplevel_dir_placeholder);
476 info.fn = collect_merge_info_callback;
477 info.data = opt;
478 info.show_all_errors = 1;
479
480 parse_tree(merge_base);
481 parse_tree(side1);
482 parse_tree(side2);
483 init_tree_desc(t + 0, merge_base->buffer, merge_base->size);
484 init_tree_desc(t + 1, side1->buffer, side1->size);
485 init_tree_desc(t + 2, side2->buffer, side2->size);
486
487 ret = traverse_trees(NULL, 3, t, &info);
488
489 return ret;
490 }
491
492 static int detect_and_process_renames(struct merge_options *opt,
493 struct tree *merge_base,
494 struct tree *side1,
495 struct tree *side2)
496 {
497 int clean = 1;
498
499 /*
500 * Rename detection works by detecting file similarity. Here we use
501 * a really easy-to-implement scheme: files are similar IFF they have
502 * the same filename. Therefore, by this scheme, there are no renames.
503 *
504 * TODO: Actually implement a real rename detection scheme.
505 */
506 return clean;
507 }
508
509 static int string_list_df_name_compare(const char *one, const char *two)
510 {
511 int onelen = strlen(one);
512 int twolen = strlen(two);
513 /*
514 * Here we only care that entries for D/F conflicts are
515 * adjacent, in particular with the file of the D/F conflict
516 * appearing before files below the corresponding directory.
517 * The order of the rest of the list is irrelevant for us.
518 *
519 * To achieve this, we sort with df_name_compare and provide
520 * the mode S_IFDIR so that D/F conflicts will sort correctly.
521 * We use the mode S_IFDIR for everything else for simplicity,
522 * since in other cases any changes in their order due to
523 * sorting cause no problems for us.
524 */
525 int cmp = df_name_compare(one, onelen, S_IFDIR,
526 two, twolen, S_IFDIR);
527 /*
528 * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
529 * that 'foo' comes before 'foo/bar'.
530 */
531 if (cmp)
532 return cmp;
533 return onelen - twolen;
534 }
535
536 struct directory_versions {
537 /*
538 * versions: list of (basename -> version_info)
539 *
540 * The basenames are in reverse lexicographic order of full pathnames,
541 * as processed in process_entries(). This puts all entries within
542 * a directory together, and covers the directory itself after
543 * everything within it, allowing us to write subtrees before needing
544 * to record information for the tree itself.
545 */
546 struct string_list versions;
547
548 /*
549 * offsets: list of (full relative path directories -> integer offsets)
550 *
551 * Since versions contains basenames from files in multiple different
552 * directories, we need to know which entries in versions correspond
553 * to which directories. Values of e.g.
554 * "" 0
555 * src 2
556 * src/moduleA 5
557 * Would mean that entries 0-1 of versions are files in the toplevel
558 * directory, entries 2-4 are files under src/, and the remaining
559 * entries starting at index 5 are files under src/moduleA/.
560 */
561 struct string_list offsets;
562
563 /*
564 * last_directory: directory that previously processed file found in
565 *
566 * last_directory starts NULL, but records the directory in which the
567 * previous file was found within. As soon as
568 * directory(current_file) != last_directory
569 * then we need to start updating accounting in versions & offsets.
570 * Note that last_directory is always the last path in "offsets" (or
571 * NULL if "offsets" is empty) so this exists just for quick access.
572 */
573 const char *last_directory;
574
575 /* last_directory_len: cached computation of strlen(last_directory) */
576 unsigned last_directory_len;
577 };
578
579 static int tree_entry_order(const void *a_, const void *b_)
580 {
581 const struct string_list_item *a = a_;
582 const struct string_list_item *b = b_;
583
584 const struct merged_info *ami = a->util;
585 const struct merged_info *bmi = b->util;
586 return base_name_compare(a->string, strlen(a->string), ami->result.mode,
587 b->string, strlen(b->string), bmi->result.mode);
588 }
589
590 static void write_tree(struct object_id *result_oid,
591 struct string_list *versions,
592 unsigned int offset,
593 size_t hash_size)
594 {
595 size_t maxlen = 0, extra;
596 unsigned int nr = versions->nr - offset;
597 struct strbuf buf = STRBUF_INIT;
598 struct string_list relevant_entries = STRING_LIST_INIT_NODUP;
599 int i;
600
601 /*
602 * We want to sort the last (versions->nr-offset) entries in versions.
603 * Do so by abusing the string_list API a bit: make another string_list
604 * that contains just those entries and then sort them.
605 *
606 * We won't use relevant_entries again and will let it just pop off the
607 * stack, so there won't be allocation worries or anything.
608 */
609 relevant_entries.items = versions->items + offset;
610 relevant_entries.nr = versions->nr - offset;
611 QSORT(relevant_entries.items, relevant_entries.nr, tree_entry_order);
612
613 /* Pre-allocate some space in buf */
614 extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
615 for (i = 0; i < nr; i++) {
616 maxlen += strlen(versions->items[offset+i].string) + extra;
617 }
618 strbuf_grow(&buf, maxlen);
619
620 /* Write each entry out to buf */
621 for (i = 0; i < nr; i++) {
622 struct merged_info *mi = versions->items[offset+i].util;
623 struct version_info *ri = &mi->result;
624 strbuf_addf(&buf, "%o %s%c",
625 ri->mode,
626 versions->items[offset+i].string, '\0');
627 strbuf_add(&buf, ri->oid.hash, hash_size);
628 }
629
630 /* Write this object file out, and record in result_oid */
631 write_object_file(buf.buf, buf.len, tree_type, result_oid);
632 strbuf_release(&buf);
633 }
634
635 static void record_entry_for_tree(struct directory_versions *dir_metadata,
636 const char *path,
637 struct merged_info *mi)
638 {
639 const char *basename;
640
641 if (mi->is_null)
642 /* nothing to record */
643 return;
644
645 basename = path + mi->basename_offset;
646 assert(strchr(basename, '/') == NULL);
647 string_list_append(&dir_metadata->versions,
648 basename)->util = &mi->result;
649 }
650
651 static void write_completed_directory(struct merge_options *opt,
652 const char *new_directory_name,
653 struct directory_versions *info)
654 {
655 const char *prev_dir;
656 struct merged_info *dir_info = NULL;
657 unsigned int offset;
658
659 /*
660 * Some explanation of info->versions and info->offsets...
661 *
662 * process_entries() iterates over all relevant files AND
663 * directories in reverse lexicographic order, and calls this
664 * function. Thus, an example of the paths that process_entries()
665 * could operate on (along with the directories for those paths
666 * being shown) is:
667 *
668 * xtract.c ""
669 * tokens.txt ""
670 * src/moduleB/umm.c src/moduleB
671 * src/moduleB/stuff.h src/moduleB
672 * src/moduleB/baz.c src/moduleB
673 * src/moduleB src
674 * src/moduleA/foo.c src/moduleA
675 * src/moduleA/bar.c src/moduleA
676 * src/moduleA src
677 * src ""
678 * Makefile ""
679 *
680 * info->versions:
681 *
682 * always contains the unprocessed entries and their
683 * version_info information. For example, after the first five
684 * entries above, info->versions would be:
685 *
686 * xtract.c <xtract.c's version_info>
687 * token.txt <token.txt's version_info>
688 * umm.c <src/moduleB/umm.c's version_info>
689 * stuff.h <src/moduleB/stuff.h's version_info>
690 * baz.c <src/moduleB/baz.c's version_info>
691 *
692 * Once a subdirectory is completed we remove the entries in
693 * that subdirectory from info->versions, writing it as a tree
694 * (write_tree()). Thus, as soon as we get to src/moduleB,
695 * info->versions would be updated to
696 *
697 * xtract.c <xtract.c's version_info>
698 * token.txt <token.txt's version_info>
699 * moduleB <src/moduleB's version_info>
700 *
701 * info->offsets:
702 *
703 * helps us track which entries in info->versions correspond to
704 * which directories. When we are N directories deep (e.g. 4
705 * for src/modA/submod/subdir/), we have up to N+1 unprocessed
706 * directories (+1 because of toplevel dir). Corresponding to
707 * the info->versions example above, after processing five entries
708 * info->offsets will be:
709 *
710 * "" 0
711 * src/moduleB 2
712 *
713 * which is used to know that xtract.c & token.txt are from the
714 * toplevel dirctory, while umm.c & stuff.h & baz.c are from the
715 * src/moduleB directory. Again, following the example above,
716 * once we need to process src/moduleB, then info->offsets is
717 * updated to
718 *
719 * "" 0
720 * src 2
721 *
722 * which says that moduleB (and only moduleB so far) is in the
723 * src directory.
724 *
725 * One unique thing to note about info->offsets here is that
726 * "src" was not added to info->offsets until there was a path
727 * (a file OR directory) immediately below src/ that got
728 * processed.
729 *
730 * Since process_entry() just appends new entries to info->versions,
731 * write_completed_directory() only needs to do work if the next path
732 * is in a directory that is different than the last directory found
733 * in info->offsets.
734 */
735
736 /*
737 * If we are working with the same directory as the last entry, there
738 * is no work to do. (See comments above the directory_name member of
739 * struct merged_info for why we can use pointer comparison instead of
740 * strcmp here.)
741 */
742 if (new_directory_name == info->last_directory)
743 return;
744
745 /*
746 * If we are just starting (last_directory is NULL), or last_directory
747 * is a prefix of the current directory, then we can just update
748 * info->offsets to record the offset where we started this directory
749 * and update last_directory to have quick access to it.
750 */
751 if (info->last_directory == NULL ||
752 !strncmp(new_directory_name, info->last_directory,
753 info->last_directory_len)) {
754 uintptr_t offset = info->versions.nr;
755
756 info->last_directory = new_directory_name;
757 info->last_directory_len = strlen(info->last_directory);
758 /*
759 * Record the offset into info->versions where we will
760 * start recording basenames of paths found within
761 * new_directory_name.
762 */
763 string_list_append(&info->offsets,
764 info->last_directory)->util = (void*)offset;
765 return;
766 }
767
768 /*
769 * The next entry that will be processed will be within
770 * new_directory_name. Since at this point we know that
771 * new_directory_name is within a different directory than
772 * info->last_directory, we have all entries for info->last_directory
773 * in info->versions and we need to create a tree object for them.
774 */
775 dir_info = strmap_get(&opt->priv->paths, info->last_directory);
776 assert(dir_info);
777 offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
778 if (offset == info->versions.nr) {
779 /*
780 * Actually, we don't need to create a tree object in this
781 * case. Whenever all files within a directory disappear
782 * during the merge (e.g. unmodified on one side and
783 * deleted on the other, or files were renamed elsewhere),
784 * then we get here and the directory itself needs to be
785 * omitted from its parent tree as well.
786 */
787 dir_info->is_null = 1;
788 } else {
789 /*
790 * Write out the tree to the git object directory, and also
791 * record the mode and oid in dir_info->result.
792 */
793 dir_info->is_null = 0;
794 dir_info->result.mode = S_IFDIR;
795 write_tree(&dir_info->result.oid, &info->versions, offset,
796 opt->repo->hash_algo->rawsz);
797 }
798
799 /*
800 * We've now used several entries from info->versions and one entry
801 * from info->offsets, so we get rid of those values.
802 */
803 info->offsets.nr--;
804 info->versions.nr = offset;
805
806 /*
807 * Now we've taken care of the completed directory, but we need to
808 * prepare things since future entries will be in
809 * new_directory_name. (In particular, process_entry() will be
810 * appending new entries to info->versions.) So, we need to make
811 * sure new_directory_name is the last entry in info->offsets.
812 */
813 prev_dir = info->offsets.nr == 0 ? NULL :
814 info->offsets.items[info->offsets.nr-1].string;
815 if (new_directory_name != prev_dir) {
816 uintptr_t c = info->versions.nr;
817 string_list_append(&info->offsets,
818 new_directory_name)->util = (void*)c;
819 }
820
821 /* And, of course, we need to update last_directory to match. */
822 info->last_directory = new_directory_name;
823 info->last_directory_len = strlen(info->last_directory);
824 }
825
826 /* Per entry merge function */
827 static void process_entry(struct merge_options *opt,
828 const char *path,
829 struct conflict_info *ci,
830 struct directory_versions *dir_metadata)
831 {
832 VERIFY_CI(ci);
833 assert(ci->filemask >= 0 && ci->filemask <= 7);
834 /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
835 assert(ci->match_mask == 0 || ci->match_mask == 3 ||
836 ci->match_mask == 5 || ci->match_mask == 6);
837
838 if (ci->dirmask) {
839 record_entry_for_tree(dir_metadata, path, &ci->merged);
840 if (ci->filemask == 0)
841 /* nothing else to handle */
842 return;
843 assert(ci->df_conflict);
844 }
845
846 if (ci->df_conflict) {
847 die("Not yet implemented.");
848 }
849
850 /*
851 * NOTE: Below there is a long switch-like if-elseif-elseif... block
852 * which the code goes through even for the df_conflict cases
853 * above. Well, it will once we don't die-not-implemented above.
854 */
855 if (ci->match_mask) {
856 ci->merged.clean = 1;
857 if (ci->match_mask == 6) {
858 /* stages[1] == stages[2] */
859 ci->merged.result.mode = ci->stages[1].mode;
860 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
861 } else {
862 /* determine the mask of the side that didn't match */
863 unsigned int othermask = 7 & ~ci->match_mask;
864 int side = (othermask == 4) ? 2 : 1;
865
866 ci->merged.result.mode = ci->stages[side].mode;
867 ci->merged.is_null = !ci->merged.result.mode;
868 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
869
870 assert(othermask == 2 || othermask == 4);
871 assert(ci->merged.is_null ==
872 (ci->filemask == ci->match_mask));
873 }
874 } else if (ci->filemask >= 6 &&
875 (S_IFMT & ci->stages[1].mode) !=
876 (S_IFMT & ci->stages[2].mode)) {
877 /*
878 * Two different items from (file/submodule/symlink)
879 */
880 die("Not yet implemented.");
881 } else if (ci->filemask >= 6) {
882 /*
883 * TODO: Needs a two-way or three-way content merge, but we're
884 * just being lazy and copying the version from HEAD and
885 * leaving it as conflicted.
886 */
887 ci->merged.clean = 0;
888 ci->merged.result.mode = ci->stages[1].mode;
889 oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
890 } else if (ci->filemask == 3 || ci->filemask == 5) {
891 /* Modify/delete */
892 die("Not yet implemented.");
893 } else if (ci->filemask == 2 || ci->filemask == 4) {
894 /* Added on one side */
895 int side = (ci->filemask == 4) ? 2 : 1;
896 ci->merged.result.mode = ci->stages[side].mode;
897 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
898 ci->merged.clean = !ci->df_conflict;
899 } else if (ci->filemask == 1) {
900 /* Deleted on both sides */
901 ci->merged.is_null = 1;
902 ci->merged.result.mode = 0;
903 oidcpy(&ci->merged.result.oid, &null_oid);
904 ci->merged.clean = 1;
905 }
906
907 /*
908 * If still conflicted, record it separately. This allows us to later
909 * iterate over just conflicted entries when updating the index instead
910 * of iterating over all entries.
911 */
912 if (!ci->merged.clean)
913 strmap_put(&opt->priv->conflicted, path, ci);
914 record_entry_for_tree(dir_metadata, path, &ci->merged);
915 }
916
917 static void process_entries(struct merge_options *opt,
918 struct object_id *result_oid)
919 {
920 struct hashmap_iter iter;
921 struct strmap_entry *e;
922 struct string_list plist = STRING_LIST_INIT_NODUP;
923 struct string_list_item *entry;
924 struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
925 STRING_LIST_INIT_NODUP,
926 NULL, 0 };
927
928 if (strmap_empty(&opt->priv->paths)) {
929 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
930 return;
931 }
932
933 /* Hack to pre-allocate plist to the desired size */
934 ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
935
936 /* Put every entry from paths into plist, then sort */
937 strmap_for_each_entry(&opt->priv->paths, &iter, e) {
938 string_list_append(&plist, e->key)->util = e->value;
939 }
940 plist.cmp = string_list_df_name_compare;
941 string_list_sort(&plist);
942
943 /*
944 * Iterate over the items in reverse order, so we can handle paths
945 * below a directory before needing to handle the directory itself.
946 *
947 * This allows us to write subtrees before we need to write trees,
948 * and it also enables sane handling of directory/file conflicts
949 * (because it allows us to know whether the directory is still in
950 * the way when it is time to process the file at the same path).
951 */
952 for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
953 char *path = entry->string;
954 /*
955 * NOTE: mi may actually be a pointer to a conflict_info, but
956 * we have to check mi->clean first to see if it's safe to
957 * reassign to such a pointer type.
958 */
959 struct merged_info *mi = entry->util;
960
961 write_completed_directory(opt, mi->directory_name,
962 &dir_metadata);
963 if (mi->clean)
964 record_entry_for_tree(&dir_metadata, path, mi);
965 else {
966 struct conflict_info *ci = (struct conflict_info *)mi;
967 process_entry(opt, path, ci, &dir_metadata);
968 }
969 }
970
971 if (dir_metadata.offsets.nr != 1 ||
972 (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
973 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
974 dir_metadata.offsets.nr);
975 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
976 (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
977 fflush(stdout);
978 BUG("dir_metadata accounting completely off; shouldn't happen");
979 }
980 write_tree(result_oid, &dir_metadata.versions, 0,
981 opt->repo->hash_algo->rawsz);
982 string_list_clear(&plist, 0);
983 string_list_clear(&dir_metadata.versions, 0);
984 string_list_clear(&dir_metadata.offsets, 0);
985 }
986
987 static int checkout(struct merge_options *opt,
988 struct tree *prev,
989 struct tree *next)
990 {
991 /* Switch the index/working copy from old to new */
992 int ret;
993 struct tree_desc trees[2];
994 struct unpack_trees_options unpack_opts;
995
996 memset(&unpack_opts, 0, sizeof(unpack_opts));
997 unpack_opts.head_idx = -1;
998 unpack_opts.src_index = opt->repo->index;
999 unpack_opts.dst_index = opt->repo->index;
1000
1001 setup_unpack_trees_porcelain(&unpack_opts, "merge");
1002
1003 /*
1004 * NOTE: if this were just "git checkout" code, we would probably
1005 * read or refresh the cache and check for a conflicted index, but
1006 * builtin/merge.c or sequencer.c really needs to read the index
1007 * and check for conflicted entries before starting merging for a
1008 * good user experience (no sense waiting for merges/rebases before
1009 * erroring out), so there's no reason to duplicate that work here.
1010 */
1011
1012 /* 2-way merge to the new branch */
1013 unpack_opts.update = 1;
1014 unpack_opts.merge = 1;
1015 unpack_opts.quiet = 0; /* FIXME: sequencer might want quiet? */
1016 unpack_opts.verbose_update = (opt->verbosity > 2);
1017 unpack_opts.fn = twoway_merge;
1018 if (1/* FIXME: opts->overwrite_ignore*/) {
1019 unpack_opts.dir = xcalloc(1, sizeof(*unpack_opts.dir));
1020 unpack_opts.dir->flags |= DIR_SHOW_IGNORED;
1021 setup_standard_excludes(unpack_opts.dir);
1022 }
1023 parse_tree(prev);
1024 init_tree_desc(&trees[0], prev->buffer, prev->size);
1025 parse_tree(next);
1026 init_tree_desc(&trees[1], next->buffer, next->size);
1027
1028 ret = unpack_trees(2, trees, &unpack_opts);
1029 clear_unpack_trees_porcelain(&unpack_opts);
1030 dir_clear(unpack_opts.dir);
1031 FREE_AND_NULL(unpack_opts.dir);
1032 return ret;
1033 }
1034
1035 static int record_conflicted_index_entries(struct merge_options *opt,
1036 struct index_state *index,
1037 struct strmap *paths,
1038 struct strmap *conflicted)
1039 {
1040 struct hashmap_iter iter;
1041 struct strmap_entry *e;
1042 int errs = 0;
1043 int original_cache_nr;
1044
1045 if (strmap_empty(conflicted))
1046 return 0;
1047
1048 original_cache_nr = index->cache_nr;
1049
1050 /* Put every entry from paths into plist, then sort */
1051 strmap_for_each_entry(conflicted, &iter, e) {
1052 const char *path = e->key;
1053 struct conflict_info *ci = e->value;
1054 int pos;
1055 struct cache_entry *ce;
1056 int i;
1057
1058 VERIFY_CI(ci);
1059
1060 /*
1061 * The index will already have a stage=0 entry for this path,
1062 * because we created an as-merged-as-possible version of the
1063 * file and checkout() moved the working copy and index over
1064 * to that version.
1065 *
1066 * However, previous iterations through this loop will have
1067 * added unstaged entries to the end of the cache which
1068 * ignore the standard alphabetical ordering of cache
1069 * entries and break invariants needed for index_name_pos()
1070 * to work. However, we know the entry we want is before
1071 * those appended cache entries, so do a temporary swap on
1072 * cache_nr to only look through entries of interest.
1073 */
1074 SWAP(index->cache_nr, original_cache_nr);
1075 pos = index_name_pos(index, path, strlen(path));
1076 SWAP(index->cache_nr, original_cache_nr);
1077 if (pos < 0) {
1078 if (ci->filemask != 1)
1079 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path);
1080 cache_tree_invalidate_path(index, path);
1081 } else {
1082 ce = index->cache[pos];
1083
1084 /*
1085 * Clean paths with CE_SKIP_WORKTREE set will not be
1086 * written to the working tree by the unpack_trees()
1087 * call in checkout(). Our conflicted entries would
1088 * have appeared clean to that code since we ignored
1089 * the higher order stages. Thus, we need override
1090 * the CE_SKIP_WORKTREE bit and manually write those
1091 * files to the working disk here.
1092 *
1093 * TODO: Implement this CE_SKIP_WORKTREE fixup.
1094 */
1095
1096 /*
1097 * Mark this cache entry for removal and instead add
1098 * new stage>0 entries corresponding to the
1099 * conflicts. If there are many conflicted entries, we
1100 * want to avoid memmove'ing O(NM) entries by
1101 * inserting the new entries one at a time. So,
1102 * instead, we just add the new cache entries to the
1103 * end (ignoring normal index requirements on sort
1104 * order) and sort the index once we're all done.
1105 */
1106 ce->ce_flags |= CE_REMOVE;
1107 }
1108
1109 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1110 struct version_info *vi;
1111 if (!(ci->filemask & (1ul << i)))
1112 continue;
1113 vi = &ci->stages[i];
1114 ce = make_cache_entry(index, vi->mode, &vi->oid,
1115 path, i+1, 0);
1116 add_index_entry(index, ce, ADD_CACHE_JUST_APPEND);
1117 }
1118 }
1119
1120 /*
1121 * Remove the unused cache entries (and invalidate the relevant
1122 * cache-trees), then sort the index entries to get the conflicted
1123 * entries we added to the end into their right locations.
1124 */
1125 remove_marked_cache_entries(index, 1);
1126 QSORT(index->cache, index->cache_nr, cmp_cache_name_compare);
1127
1128 return errs;
1129 }
1130
1131 void merge_switch_to_result(struct merge_options *opt,
1132 struct tree *head,
1133 struct merge_result *result,
1134 int update_worktree_and_index,
1135 int display_update_msgs)
1136 {
1137 assert(opt->priv == NULL);
1138 if (result->clean >= 0 && update_worktree_and_index) {
1139 struct merge_options_internal *opti = result->priv;
1140
1141 if (checkout(opt, head, result->tree)) {
1142 /* failure to function */
1143 result->clean = -1;
1144 return;
1145 }
1146
1147 if (record_conflicted_index_entries(opt, opt->repo->index,
1148 &opti->paths,
1149 &opti->conflicted)) {
1150 /* failure to function */
1151 result->clean = -1;
1152 return;
1153 }
1154 }
1155
1156 if (display_update_msgs) {
1157 /* TODO: print out CONFLICT and other informational messages. */
1158 }
1159
1160 merge_finalize(opt, result);
1161 }
1162
1163 void merge_finalize(struct merge_options *opt,
1164 struct merge_result *result)
1165 {
1166 struct merge_options_internal *opti = result->priv;
1167
1168 assert(opt->priv == NULL);
1169
1170 /*
1171 * We marked opti->paths with strdup_strings = 0, so that we
1172 * wouldn't have to make another copy of the fullpath created by
1173 * make_traverse_path from setup_path_info(). But, now that we've
1174 * used it and have no other references to these strings, it is time
1175 * to deallocate them.
1176 */
1177 free_strmap_strings(&opti->paths);
1178 strmap_clear(&opti->paths, 1);
1179
1180 /*
1181 * All keys and values in opti->conflicted are a subset of those in
1182 * opti->paths. We don't want to deallocate anything twice, so we
1183 * don't free the keys and we pass 0 for free_values.
1184 */
1185 strmap_clear(&opti->conflicted, 0);
1186 FREE_AND_NULL(opti);
1187 }
1188
1189 static void merge_start(struct merge_options *opt, struct merge_result *result)
1190 {
1191 /* Sanity checks on opt */
1192 assert(opt->repo);
1193
1194 assert(opt->branch1 && opt->branch2);
1195
1196 assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
1197 opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
1198 assert(opt->rename_limit >= -1);
1199 assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
1200 assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
1201
1202 assert(opt->xdl_opts >= 0);
1203 assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
1204 opt->recursive_variant <= MERGE_VARIANT_THEIRS);
1205
1206 /*
1207 * detect_renames, verbosity, buffer_output, and obuf are ignored
1208 * fields that were used by "recursive" rather than "ort" -- but
1209 * sanity check them anyway.
1210 */
1211 assert(opt->detect_renames >= -1 &&
1212 opt->detect_renames <= DIFF_DETECT_COPY);
1213 assert(opt->verbosity >= 0 && opt->verbosity <= 5);
1214 assert(opt->buffer_output <= 2);
1215 assert(opt->obuf.len == 0);
1216
1217 assert(opt->priv == NULL);
1218
1219 /* Default to histogram diff. Actually, just hardcode it...for now. */
1220 opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
1221
1222 /* Initialization of opt->priv, our internal merge data */
1223 opt->priv = xcalloc(1, sizeof(*opt->priv));
1224
1225 /*
1226 * Although we initialize opt->priv->paths with strdup_strings=0,
1227 * that's just to avoid making yet another copy of an allocated
1228 * string. Putting the entry into paths means we are taking
1229 * ownership, so we will later free it.
1230 *
1231 * In contrast, conflicted just has a subset of keys from paths, so
1232 * we don't want to free those (it'd be a duplicate free).
1233 */
1234 strmap_init_with_options(&opt->priv->paths, NULL, 0);
1235 strmap_init_with_options(&opt->priv->conflicted, NULL, 0);
1236 }
1237
1238 /*
1239 * Originally from merge_trees_internal(); heavily adapted, though.
1240 */
1241 static void merge_ort_nonrecursive_internal(struct merge_options *opt,
1242 struct tree *merge_base,
1243 struct tree *side1,
1244 struct tree *side2,
1245 struct merge_result *result)
1246 {
1247 struct object_id working_tree_oid;
1248
1249 if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
1250 /*
1251 * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
1252 * base, and 2-3) the trees for the two trees we're merging.
1253 */
1254 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
1255 oid_to_hex(&merge_base->object.oid),
1256 oid_to_hex(&side1->object.oid),
1257 oid_to_hex(&side2->object.oid));
1258 result->clean = -1;
1259 return;
1260 }
1261
1262 result->clean = detect_and_process_renames(opt, merge_base,
1263 side1, side2);
1264 process_entries(opt, &working_tree_oid);
1265
1266 /* Set return values */
1267 result->tree = parse_tree_indirect(&working_tree_oid);
1268 /* existence of conflicted entries implies unclean */
1269 result->clean &= strmap_empty(&opt->priv->conflicted);
1270 if (!opt->priv->call_depth) {
1271 result->priv = opt->priv;
1272 opt->priv = NULL;
1273 }
1274 }
1275
1276 void merge_incore_nonrecursive(struct merge_options *opt,
1277 struct tree *merge_base,
1278 struct tree *side1,
1279 struct tree *side2,
1280 struct merge_result *result)
1281 {
1282 assert(opt->ancestor != NULL);
1283 merge_start(opt, result);
1284 merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
1285 }
1286
1287 void merge_incore_recursive(struct merge_options *opt,
1288 struct commit_list *merge_bases,
1289 struct commit *side1,
1290 struct commit *side2,
1291 struct merge_result *result)
1292 {
1293 die("Not yet implemented");
1294 }