merge-ort: flesh out implementation of handle_content_merge()
[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 "blob.h"
21 #include "cache-tree.h"
22 #include "commit-reach.h"
23 #include "diff.h"
24 #include "diffcore.h"
25 #include "dir.h"
26 #include "object-store.h"
27 #include "strmap.h"
28 #include "tree.h"
29 #include "unpack-trees.h"
30 #include "xdiff-interface.h"
31
32 /*
33  * We have many arrays of size 3.  Whenever we have such an array, the
34  * indices refer to one of the sides of the three-way merge.  This is so
35  * pervasive that the constants 0, 1, and 2 are used in many places in the
36  * code (especially in arithmetic operations to find the other side's index
37  * or to compute a relevant mask), but sometimes these enum names are used
38  * to aid code clarity.
39  *
40  * See also 'filemask' and 'dirmask' in struct conflict_info; the "ith side"
41  * referred to there is one of these three sides.
42  */
43 enum merge_side {
44         MERGE_BASE = 0,
45         MERGE_SIDE1 = 1,
46         MERGE_SIDE2 = 2
47 };
48
49 struct merge_options_internal {
50         /*
51          * paths: primary data structure in all of merge ort.
52          *
53          * The keys of paths:
54          *   * are full relative paths from the toplevel of the repository
55          *     (e.g. "drivers/firmware/raspberrypi.c").
56          *   * store all relevant paths in the repo, both directories and
57          *     files (e.g. drivers, drivers/firmware would also be included)
58          *   * these keys serve to intern all the path strings, which allows
59          *     us to do pointer comparison on directory names instead of
60          *     strcmp; we just have to be careful to use the interned strings.
61          *     (Technically paths_to_free may track some strings that were
62          *      removed from froms paths.)
63          *
64          * The values of paths:
65          *   * either a pointer to a merged_info, or a conflict_info struct
66          *   * merged_info contains all relevant information for a
67          *     non-conflicted entry.
68          *   * conflict_info contains a merged_info, plus any additional
69          *     information about a conflict such as the higher orders stages
70          *     involved and the names of the paths those came from (handy
71          *     once renames get involved).
72          *   * a path may start "conflicted" (i.e. point to a conflict_info)
73          *     and then a later step (e.g. three-way content merge) determines
74          *     it can be cleanly merged, at which point it'll be marked clean
75          *     and the algorithm will ignore any data outside the contained
76          *     merged_info for that entry
77          *   * If an entry remains conflicted, the merged_info portion of a
78          *     conflict_info will later be filled with whatever version of
79          *     the file should be placed in the working directory (e.g. an
80          *     as-merged-as-possible variation that contains conflict markers).
81          */
82         struct strmap paths;
83
84         /*
85          * conflicted: a subset of keys->values from "paths"
86          *
87          * conflicted is basically an optimization between process_entries()
88          * and record_conflicted_index_entries(); the latter could loop over
89          * ALL the entries in paths AGAIN and look for the ones that are
90          * still conflicted, but since process_entries() has to loop over
91          * all of them, it saves the ones it couldn't resolve in this strmap
92          * so that record_conflicted_index_entries() can iterate just the
93          * relevant entries.
94          */
95         struct strmap conflicted;
96
97         /*
98          * paths_to_free: additional list of strings to free
99          *
100          * If keys are removed from "paths", they are added to paths_to_free
101          * to ensure they are later freed.  We avoid free'ing immediately since
102          * other places (e.g. conflict_info.pathnames[]) may still be
103          * referencing these paths.
104          */
105         struct string_list paths_to_free;
106
107         /*
108          * output: special messages and conflict notices for various paths
109          *
110          * This is a map of pathnames (a subset of the keys in "paths" above)
111          * to strbufs.  It gathers various warning/conflict/notice messages
112          * for later processing.
113          */
114         struct strmap output;
115
116         /*
117          * current_dir_name: temporary var used in collect_merge_info_callback()
118          *
119          * Used to set merged_info.directory_name; see documentation for that
120          * variable and the requirements placed on that field.
121          */
122         const char *current_dir_name;
123
124         /* call_depth: recursion level counter for merging merge bases */
125         int call_depth;
126 };
127
128 struct version_info {
129         struct object_id oid;
130         unsigned short mode;
131 };
132
133 struct merged_info {
134         /* if is_null, ignore result.  otherwise result has oid & mode */
135         struct version_info result;
136         unsigned is_null:1;
137
138         /*
139          * clean: whether the path in question is cleanly merged.
140          *
141          * see conflict_info.merged for more details.
142          */
143         unsigned clean:1;
144
145         /*
146          * basename_offset: offset of basename of path.
147          *
148          * perf optimization to avoid recomputing offset of final '/'
149          * character in pathname (0 if no '/' in pathname).
150          */
151         size_t basename_offset;
152
153          /*
154           * directory_name: containing directory name.
155           *
156           * Note that we assume directory_name is constructed such that
157           *    strcmp(dir1_name, dir2_name) == 0 iff dir1_name == dir2_name,
158           * i.e. string equality is equivalent to pointer equality.  For this
159           * to hold, we have to be careful setting directory_name.
160           */
161         const char *directory_name;
162 };
163
164 struct conflict_info {
165         /*
166          * merged: the version of the path that will be written to working tree
167          *
168          * WARNING: It is critical to check merged.clean and ensure it is 0
169          * before reading any conflict_info fields outside of merged.
170          * Allocated merge_info structs will always have clean set to 1.
171          * Allocated conflict_info structs will have merged.clean set to 0
172          * initially.  The merged.clean field is how we know if it is safe
173          * to access other parts of conflict_info besides merged; if a
174          * conflict_info's merged.clean is changed to 1, the rest of the
175          * algorithm is not allowed to look at anything outside of the
176          * merged member anymore.
177          */
178         struct merged_info merged;
179
180         /* oids & modes from each of the three trees for this path */
181         struct version_info stages[3];
182
183         /* pathnames for each stage; may differ due to rename detection */
184         const char *pathnames[3];
185
186         /* Whether this path is/was involved in a directory/file conflict */
187         unsigned df_conflict:1;
188
189         /*
190          * Whether this path is/was involved in a non-content conflict other
191          * than a directory/file conflict (e.g. rename/rename, rename/delete,
192          * file location based on possible directory rename).
193          */
194         unsigned path_conflict:1;
195
196         /*
197          * For filemask and dirmask, the ith bit corresponds to whether the
198          * ith entry is a file (filemask) or a directory (dirmask).  Thus,
199          * filemask & dirmask is always zero, and filemask | dirmask is at
200          * most 7 but can be less when a path does not appear as either a
201          * file or a directory on at least one side of history.
202          *
203          * Note that these masks are related to enum merge_side, as the ith
204          * entry corresponds to side i.
205          *
206          * These values come from a traverse_trees() call; more info may be
207          * found looking at tree-walk.h's struct traverse_info,
208          * particularly the documentation above the "fn" member (note that
209          * filemask = mask & ~dirmask from that documentation).
210          */
211         unsigned filemask:3;
212         unsigned dirmask:3;
213
214         /*
215          * Optimization to track which stages match, to avoid the need to
216          * recompute it in multiple steps. Either 0 or at least 2 bits are
217          * set; if at least 2 bits are set, their corresponding stages match.
218          */
219         unsigned match_mask:3;
220 };
221
222 /*** Function Grouping: various utility functions ***/
223
224 /*
225  * For the next three macros, see warning for conflict_info.merged.
226  *
227  * In each of the below, mi is a struct merged_info*, and ci was defined
228  * as a struct conflict_info* (but we need to verify ci isn't actually
229  * pointed at a struct merged_info*).
230  *
231  * INITIALIZE_CI: Assign ci to mi but only if it's safe; set to NULL otherwise.
232  * VERIFY_CI: Ensure that something we assigned to a conflict_info* is one.
233  * ASSIGN_AND_VERIFY_CI: Similar to VERIFY_CI but do assignment first.
234  */
235 #define INITIALIZE_CI(ci, mi) do {                                           \
236         (ci) = (!(mi) || (mi)->clean) ? NULL : (struct conflict_info *)(mi); \
237 } while (0)
238 #define VERIFY_CI(ci) assert(ci && !ci->merged.clean);
239 #define ASSIGN_AND_VERIFY_CI(ci, mi) do {    \
240         (ci) = (struct conflict_info *)(mi);  \
241         assert((ci) && !(mi)->clean);        \
242 } while (0)
243
244 static void free_strmap_strings(struct strmap *map)
245 {
246         struct hashmap_iter iter;
247         struct strmap_entry *entry;
248
249         strmap_for_each_entry(map, &iter, entry) {
250                 free((char*)entry->key);
251         }
252 }
253
254 static void clear_internal_opts(struct merge_options_internal *opti,
255                                 int reinitialize)
256 {
257         assert(!reinitialize);
258
259         /*
260          * We marked opti->paths with strdup_strings = 0, so that we
261          * wouldn't have to make another copy of the fullpath created by
262          * make_traverse_path from setup_path_info().  But, now that we've
263          * used it and have no other references to these strings, it is time
264          * to deallocate them.
265          */
266         free_strmap_strings(&opti->paths);
267         strmap_clear(&opti->paths, 1);
268
269         /*
270          * All keys and values in opti->conflicted are a subset of those in
271          * opti->paths.  We don't want to deallocate anything twice, so we
272          * don't free the keys and we pass 0 for free_values.
273          */
274         strmap_clear(&opti->conflicted, 0);
275
276         /*
277          * opti->paths_to_free is similar to opti->paths; we created it with
278          * strdup_strings = 0 to avoid making _another_ copy of the fullpath
279          * but now that we've used it and have no other references to these
280          * strings, it is time to deallocate them.  We do so by temporarily
281          * setting strdup_strings to 1.
282          */
283         opti->paths_to_free.strdup_strings = 1;
284         string_list_clear(&opti->paths_to_free, 0);
285         opti->paths_to_free.strdup_strings = 0;
286
287         if (!reinitialize) {
288                 struct hashmap_iter iter;
289                 struct strmap_entry *e;
290
291                 /* Release and free each strbuf found in output */
292                 strmap_for_each_entry(&opti->output, &iter, e) {
293                         struct strbuf *sb = e->value;
294                         strbuf_release(sb);
295                         /*
296                          * While strictly speaking we don't need to free(sb)
297                          * here because we could pass free_values=1 when
298                          * calling strmap_clear() on opti->output, that would
299                          * require strmap_clear to do another
300                          * strmap_for_each_entry() loop, so we just free it
301                          * while we're iterating anyway.
302                          */
303                         free(sb);
304                 }
305                 strmap_clear(&opti->output, 0);
306         }
307 }
308
309 static int err(struct merge_options *opt, const char *err, ...)
310 {
311         va_list params;
312         struct strbuf sb = STRBUF_INIT;
313
314         strbuf_addstr(&sb, "error: ");
315         va_start(params, err);
316         strbuf_vaddf(&sb, err, params);
317         va_end(params);
318
319         error("%s", sb.buf);
320         strbuf_release(&sb);
321
322         return -1;
323 }
324
325 __attribute__((format (printf, 4, 5)))
326 static void path_msg(struct merge_options *opt,
327                      const char *path,
328                      int omittable_hint, /* skippable under --remerge-diff */
329                      const char *fmt, ...)
330 {
331         va_list ap;
332         struct strbuf *sb = strmap_get(&opt->priv->output, path);
333         if (!sb) {
334                 sb = xmalloc(sizeof(*sb));
335                 strbuf_init(sb, 0);
336                 strmap_put(&opt->priv->output, path, sb);
337         }
338
339         va_start(ap, fmt);
340         strbuf_vaddf(sb, fmt, ap);
341         va_end(ap);
342
343         strbuf_addch(sb, '\n');
344 }
345
346 /* add a string to a strbuf, but converting "/" to "_" */
347 static void add_flattened_path(struct strbuf *out, const char *s)
348 {
349         size_t i = out->len;
350         strbuf_addstr(out, s);
351         for (; i < out->len; i++)
352                 if (out->buf[i] == '/')
353                         out->buf[i] = '_';
354 }
355
356 static char *unique_path(struct strmap *existing_paths,
357                          const char *path,
358                          const char *branch)
359 {
360         struct strbuf newpath = STRBUF_INIT;
361         int suffix = 0;
362         size_t base_len;
363
364         strbuf_addf(&newpath, "%s~", path);
365         add_flattened_path(&newpath, branch);
366
367         base_len = newpath.len;
368         while (strmap_contains(existing_paths, newpath.buf)) {
369                 strbuf_setlen(&newpath, base_len);
370                 strbuf_addf(&newpath, "_%d", suffix++);
371         }
372
373         return strbuf_detach(&newpath, NULL);
374 }
375
376 /*** Function Grouping: functions related to collect_merge_info() ***/
377
378 static void setup_path_info(struct merge_options *opt,
379                             struct string_list_item *result,
380                             const char *current_dir_name,
381                             int current_dir_name_len,
382                             char *fullpath, /* we'll take over ownership */
383                             struct name_entry *names,
384                             struct name_entry *merged_version,
385                             unsigned is_null,     /* boolean */
386                             unsigned df_conflict, /* boolean */
387                             unsigned filemask,
388                             unsigned dirmask,
389                             int resolved          /* boolean */)
390 {
391         /* result->util is void*, so mi is a convenience typed variable */
392         struct merged_info *mi;
393
394         assert(!is_null || resolved);
395         assert(!df_conflict || !resolved); /* df_conflict implies !resolved */
396         assert(resolved == (merged_version != NULL));
397
398         mi = xcalloc(1, resolved ? sizeof(struct merged_info) :
399                                    sizeof(struct conflict_info));
400         mi->directory_name = current_dir_name;
401         mi->basename_offset = current_dir_name_len;
402         mi->clean = !!resolved;
403         if (resolved) {
404                 mi->result.mode = merged_version->mode;
405                 oidcpy(&mi->result.oid, &merged_version->oid);
406                 mi->is_null = !!is_null;
407         } else {
408                 int i;
409                 struct conflict_info *ci;
410
411                 ASSIGN_AND_VERIFY_CI(ci, mi);
412                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
413                         ci->pathnames[i] = fullpath;
414                         ci->stages[i].mode = names[i].mode;
415                         oidcpy(&ci->stages[i].oid, &names[i].oid);
416                 }
417                 ci->filemask = filemask;
418                 ci->dirmask = dirmask;
419                 ci->df_conflict = !!df_conflict;
420                 if (dirmask)
421                         /*
422                          * Assume is_null for now, but if we have entries
423                          * under the directory then when it is complete in
424                          * write_completed_directory() it'll update this.
425                          * Also, for D/F conflicts, we have to handle the
426                          * directory first, then clear this bit and process
427                          * the file to see how it is handled -- that occurs
428                          * near the top of process_entry().
429                          */
430                         mi->is_null = 1;
431         }
432         strmap_put(&opt->priv->paths, fullpath, mi);
433         result->string = fullpath;
434         result->util = mi;
435 }
436
437 static int collect_merge_info_callback(int n,
438                                        unsigned long mask,
439                                        unsigned long dirmask,
440                                        struct name_entry *names,
441                                        struct traverse_info *info)
442 {
443         /*
444          * n is 3.  Always.
445          * common ancestor (mbase) has mask 1, and stored in index 0 of names
446          * head of side 1  (side1) has mask 2, and stored in index 1 of names
447          * head of side 2  (side2) has mask 4, and stored in index 2 of names
448          */
449         struct merge_options *opt = info->data;
450         struct merge_options_internal *opti = opt->priv;
451         struct string_list_item pi;  /* Path Info */
452         struct conflict_info *ci; /* typed alias to pi.util (which is void*) */
453         struct name_entry *p;
454         size_t len;
455         char *fullpath;
456         const char *dirname = opti->current_dir_name;
457         unsigned filemask = mask & ~dirmask;
458         unsigned match_mask = 0; /* will be updated below */
459         unsigned mbase_null = !(mask & 1);
460         unsigned side1_null = !(mask & 2);
461         unsigned side2_null = !(mask & 4);
462         unsigned side1_matches_mbase = (!side1_null && !mbase_null &&
463                                         names[0].mode == names[1].mode &&
464                                         oideq(&names[0].oid, &names[1].oid));
465         unsigned side2_matches_mbase = (!side2_null && !mbase_null &&
466                                         names[0].mode == names[2].mode &&
467                                         oideq(&names[0].oid, &names[2].oid));
468         unsigned sides_match = (!side1_null && !side2_null &&
469                                 names[1].mode == names[2].mode &&
470                                 oideq(&names[1].oid, &names[2].oid));
471
472         /*
473          * Note: When a path is a file on one side of history and a directory
474          * in another, we have a directory/file conflict.  In such cases, if
475          * the conflict doesn't resolve from renames and deletions, then we
476          * always leave directories where they are and move files out of the
477          * way.  Thus, while struct conflict_info has a df_conflict field to
478          * track such conflicts, we ignore that field for any directories at
479          * a path and only pay attention to it for files at the given path.
480          * The fact that we leave directories were they are also means that
481          * we do not need to worry about getting additional df_conflict
482          * information propagated from parent directories down to children
483          * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
484          * sets a newinfo.df_conflicts field specifically to propagate it).
485          */
486         unsigned df_conflict = (filemask != 0) && (dirmask != 0);
487
488         /* n = 3 is a fundamental assumption. */
489         if (n != 3)
490                 BUG("Called collect_merge_info_callback wrong");
491
492         /*
493          * A bunch of sanity checks verifying that traverse_trees() calls
494          * us the way I expect.  Could just remove these at some point,
495          * though maybe they are helpful to future code readers.
496          */
497         assert(mbase_null == is_null_oid(&names[0].oid));
498         assert(side1_null == is_null_oid(&names[1].oid));
499         assert(side2_null == is_null_oid(&names[2].oid));
500         assert(!mbase_null || !side1_null || !side2_null);
501         assert(mask > 0 && mask < 8);
502
503         /* Determine match_mask */
504         if (side1_matches_mbase)
505                 match_mask = (side2_matches_mbase ? 7 : 3);
506         else if (side2_matches_mbase)
507                 match_mask = 5;
508         else if (sides_match)
509                 match_mask = 6;
510
511         /*
512          * Get the name of the relevant filepath, which we'll pass to
513          * setup_path_info() for tracking.
514          */
515         p = names;
516         while (!p->mode)
517                 p++;
518         len = traverse_path_len(info, p->pathlen);
519
520         /* +1 in both of the following lines to include the NUL byte */
521         fullpath = xmalloc(len + 1);
522         make_traverse_path(fullpath, len + 1, info, p->path, p->pathlen);
523
524         /*
525          * If mbase, side1, and side2 all match, we can resolve early.  Even
526          * if these are trees, there will be no renames or anything
527          * underneath.
528          */
529         if (side1_matches_mbase && side2_matches_mbase) {
530                 /* mbase, side1, & side2 all match; use mbase as resolution */
531                 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
532                                 names, names+0, mbase_null, 0,
533                                 filemask, dirmask, 1);
534                 return mask;
535         }
536
537         /*
538          * Record information about the path so we can resolve later in
539          * process_entries.
540          */
541         setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
542                         names, NULL, 0, df_conflict, filemask, dirmask, 0);
543
544         ci = pi.util;
545         VERIFY_CI(ci);
546         ci->match_mask = match_mask;
547
548         /* If dirmask, recurse into subdirectories */
549         if (dirmask) {
550                 struct traverse_info newinfo;
551                 struct tree_desc t[3];
552                 void *buf[3] = {NULL, NULL, NULL};
553                 const char *original_dir_name;
554                 int i, ret;
555
556                 ci->match_mask &= filemask;
557                 newinfo = *info;
558                 newinfo.prev = info;
559                 newinfo.name = p->path;
560                 newinfo.namelen = p->pathlen;
561                 newinfo.pathlen = st_add3(newinfo.pathlen, p->pathlen, 1);
562                 /*
563                  * If this directory we are about to recurse into cared about
564                  * its parent directory (the current directory) having a D/F
565                  * conflict, then we'd propagate the masks in this way:
566                  *    newinfo.df_conflicts |= (mask & ~dirmask);
567                  * But we don't worry about propagating D/F conflicts.  (See
568                  * comment near setting of local df_conflict variable near
569                  * the beginning of this function).
570                  */
571
572                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
573                         if (i == 1 && side1_matches_mbase)
574                                 t[1] = t[0];
575                         else if (i == 2 && side2_matches_mbase)
576                                 t[2] = t[0];
577                         else if (i == 2 && sides_match)
578                                 t[2] = t[1];
579                         else {
580                                 const struct object_id *oid = NULL;
581                                 if (dirmask & 1)
582                                         oid = &names[i].oid;
583                                 buf[i] = fill_tree_descriptor(opt->repo,
584                                                               t + i, oid);
585                         }
586                         dirmask >>= 1;
587                 }
588
589                 original_dir_name = opti->current_dir_name;
590                 opti->current_dir_name = pi.string;
591                 ret = traverse_trees(NULL, 3, t, &newinfo);
592                 opti->current_dir_name = original_dir_name;
593
594                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
595                         free(buf[i]);
596
597                 if (ret < 0)
598                         return -1;
599         }
600
601         return mask;
602 }
603
604 static int collect_merge_info(struct merge_options *opt,
605                               struct tree *merge_base,
606                               struct tree *side1,
607                               struct tree *side2)
608 {
609         int ret;
610         struct tree_desc t[3];
611         struct traverse_info info;
612         const char *toplevel_dir_placeholder = "";
613
614         opt->priv->current_dir_name = toplevel_dir_placeholder;
615         setup_traverse_info(&info, toplevel_dir_placeholder);
616         info.fn = collect_merge_info_callback;
617         info.data = opt;
618         info.show_all_errors = 1;
619
620         parse_tree(merge_base);
621         parse_tree(side1);
622         parse_tree(side2);
623         init_tree_desc(t + 0, merge_base->buffer, merge_base->size);
624         init_tree_desc(t + 1, side1->buffer, side1->size);
625         init_tree_desc(t + 2, side2->buffer, side2->size);
626
627         ret = traverse_trees(NULL, 3, t, &info);
628
629         return ret;
630 }
631
632 /*** Function Grouping: functions related to threeway content merges ***/
633
634 static int merge_submodule(struct merge_options *opt,
635                            const char *path,
636                            const struct object_id *o,
637                            const struct object_id *a,
638                            const struct object_id *b,
639                            struct object_id *result)
640 {
641         die("Not yet implemented.");
642 }
643
644 static int merge_3way(struct merge_options *opt,
645                       const char *path,
646                       const struct object_id *o,
647                       const struct object_id *a,
648                       const struct object_id *b,
649                       const char *pathnames[3],
650                       const int extra_marker_size,
651                       mmbuffer_t *result_buf)
652 {
653         die("Not yet implemented.");
654 }
655
656 static int handle_content_merge(struct merge_options *opt,
657                                 const char *path,
658                                 const struct version_info *o,
659                                 const struct version_info *a,
660                                 const struct version_info *b,
661                                 const char *pathnames[3],
662                                 const int extra_marker_size,
663                                 struct version_info *result)
664 {
665         /*
666          * path is the target location where we want to put the file, and
667          * is used to determine any normalization rules in ll_merge.
668          *
669          * The normal case is that path and all entries in pathnames are
670          * identical, though renames can affect which path we got one of
671          * the three blobs to merge on various sides of history.
672          *
673          * extra_marker_size is the amount to extend conflict markers in
674          * ll_merge; this is neeed if we have content merges of content
675          * merges, which happens for example with rename/rename(2to1) and
676          * rename/add conflicts.
677          */
678         unsigned clean = 1;
679
680         /*
681          * handle_content_merge() needs both files to be of the same type, i.e.
682          * both files OR both submodules OR both symlinks.  Conflicting types
683          * needs to be handled elsewhere.
684          */
685         assert((S_IFMT & a->mode) == (S_IFMT & b->mode));
686
687         /* Merge modes */
688         if (a->mode == b->mode || a->mode == o->mode)
689                 result->mode = b->mode;
690         else {
691                 /* must be the 100644/100755 case */
692                 assert(S_ISREG(a->mode));
693                 result->mode = a->mode;
694                 clean = (b->mode == o->mode);
695                 /*
696                  * FIXME: If opt->priv->call_depth && !clean, then we really
697                  * should not make result->mode match either a->mode or
698                  * b->mode; that causes t6036 "check conflicting mode for
699                  * regular file" to fail.  It would be best to use some other
700                  * mode, but we'll confuse all kinds of stuff if we use one
701                  * where S_ISREG(result->mode) isn't true, and if we use
702                  * something like 0100666, then tree-walk.c's calls to
703                  * canon_mode() will just normalize that to 100644 for us and
704                  * thus not solve anything.
705                  *
706                  * Figure out if there's some kind of way we can work around
707                  * this...
708                  */
709         }
710
711         /*
712          * Trivial oid merge.
713          *
714          * Note: While one might assume that the next four lines would
715          * be unnecessary due to the fact that match_mask is often
716          * setup and already handled, renames don't always take care
717          * of that.
718          */
719         if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
720                 oidcpy(&result->oid, &b->oid);
721         else if (oideq(&b->oid, &o->oid))
722                 oidcpy(&result->oid, &a->oid);
723
724         /* Remaining rules depend on file vs. submodule vs. symlink. */
725         else if (S_ISREG(a->mode)) {
726                 mmbuffer_t result_buf;
727                 int ret = 0, merge_status;
728                 int two_way;
729
730                 /*
731                  * If 'o' is different type, treat it as null so we do a
732                  * two-way merge.
733                  */
734                 two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
735
736                 merge_status = merge_3way(opt, path,
737                                           two_way ? &null_oid : &o->oid,
738                                           &a->oid, &b->oid,
739                                           pathnames, extra_marker_size,
740                                           &result_buf);
741
742                 if ((merge_status < 0) || !result_buf.ptr)
743                         ret = err(opt, _("Failed to execute internal merge"));
744
745                 if (!ret &&
746                     write_object_file(result_buf.ptr, result_buf.size,
747                                       blob_type, &result->oid))
748                         ret = err(opt, _("Unable to add %s to database"),
749                                   path);
750
751                 free(result_buf.ptr);
752                 if (ret)
753                         return -1;
754                 clean &= (merge_status == 0);
755                 path_msg(opt, path, 1, _("Auto-merging %s"), path);
756         } else if (S_ISGITLINK(a->mode)) {
757                 int two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
758                 clean = merge_submodule(opt, pathnames[0],
759                                         two_way ? &null_oid : &o->oid,
760                                         &a->oid, &b->oid, &result->oid);
761                 if (opt->priv->call_depth && two_way && !clean) {
762                         result->mode = o->mode;
763                         oidcpy(&result->oid, &o->oid);
764                 }
765         } else if (S_ISLNK(a->mode)) {
766                 if (opt->priv->call_depth) {
767                         clean = 0;
768                         result->mode = o->mode;
769                         oidcpy(&result->oid, &o->oid);
770                 } else {
771                         switch (opt->recursive_variant) {
772                         case MERGE_VARIANT_NORMAL:
773                                 clean = 0;
774                                 oidcpy(&result->oid, &a->oid);
775                                 break;
776                         case MERGE_VARIANT_OURS:
777                                 oidcpy(&result->oid, &a->oid);
778                                 break;
779                         case MERGE_VARIANT_THEIRS:
780                                 oidcpy(&result->oid, &b->oid);
781                                 break;
782                         }
783                 }
784         } else
785                 BUG("unsupported object type in the tree: %06o for %s",
786                     a->mode, path);
787
788         return clean;
789 }
790
791 /*** Function Grouping: functions related to detect_and_process_renames(), ***
792  *** which are split into directory and regular rename detection sections. ***/
793
794 /*** Function Grouping: functions related to directory rename detection ***/
795
796 /*** Function Grouping: functions related to regular rename detection ***/
797
798 static int detect_and_process_renames(struct merge_options *opt,
799                                       struct tree *merge_base,
800                                       struct tree *side1,
801                                       struct tree *side2)
802 {
803         int clean = 1;
804
805         /*
806          * Rename detection works by detecting file similarity.  Here we use
807          * a really easy-to-implement scheme: files are similar IFF they have
808          * the same filename.  Therefore, by this scheme, there are no renames.
809          *
810          * TODO: Actually implement a real rename detection scheme.
811          */
812         return clean;
813 }
814
815 /*** Function Grouping: functions related to process_entries() ***/
816
817 static int string_list_df_name_compare(const char *one, const char *two)
818 {
819         int onelen = strlen(one);
820         int twolen = strlen(two);
821         /*
822          * Here we only care that entries for D/F conflicts are
823          * adjacent, in particular with the file of the D/F conflict
824          * appearing before files below the corresponding directory.
825          * The order of the rest of the list is irrelevant for us.
826          *
827          * To achieve this, we sort with df_name_compare and provide
828          * the mode S_IFDIR so that D/F conflicts will sort correctly.
829          * We use the mode S_IFDIR for everything else for simplicity,
830          * since in other cases any changes in their order due to
831          * sorting cause no problems for us.
832          */
833         int cmp = df_name_compare(one, onelen, S_IFDIR,
834                                   two, twolen, S_IFDIR);
835         /*
836          * Now that 'foo' and 'foo/bar' compare equal, we have to make sure
837          * that 'foo' comes before 'foo/bar'.
838          */
839         if (cmp)
840                 return cmp;
841         return onelen - twolen;
842 }
843
844 struct directory_versions {
845         /*
846          * versions: list of (basename -> version_info)
847          *
848          * The basenames are in reverse lexicographic order of full pathnames,
849          * as processed in process_entries().  This puts all entries within
850          * a directory together, and covers the directory itself after
851          * everything within it, allowing us to write subtrees before needing
852          * to record information for the tree itself.
853          */
854         struct string_list versions;
855
856         /*
857          * offsets: list of (full relative path directories -> integer offsets)
858          *
859          * Since versions contains basenames from files in multiple different
860          * directories, we need to know which entries in versions correspond
861          * to which directories.  Values of e.g.
862          *     ""             0
863          *     src            2
864          *     src/moduleA    5
865          * Would mean that entries 0-1 of versions are files in the toplevel
866          * directory, entries 2-4 are files under src/, and the remaining
867          * entries starting at index 5 are files under src/moduleA/.
868          */
869         struct string_list offsets;
870
871         /*
872          * last_directory: directory that previously processed file found in
873          *
874          * last_directory starts NULL, but records the directory in which the
875          * previous file was found within.  As soon as
876          *    directory(current_file) != last_directory
877          * then we need to start updating accounting in versions & offsets.
878          * Note that last_directory is always the last path in "offsets" (or
879          * NULL if "offsets" is empty) so this exists just for quick access.
880          */
881         const char *last_directory;
882
883         /* last_directory_len: cached computation of strlen(last_directory) */
884         unsigned last_directory_len;
885 };
886
887 static int tree_entry_order(const void *a_, const void *b_)
888 {
889         const struct string_list_item *a = a_;
890         const struct string_list_item *b = b_;
891
892         const struct merged_info *ami = a->util;
893         const struct merged_info *bmi = b->util;
894         return base_name_compare(a->string, strlen(a->string), ami->result.mode,
895                                  b->string, strlen(b->string), bmi->result.mode);
896 }
897
898 static void write_tree(struct object_id *result_oid,
899                        struct string_list *versions,
900                        unsigned int offset,
901                        size_t hash_size)
902 {
903         size_t maxlen = 0, extra;
904         unsigned int nr = versions->nr - offset;
905         struct strbuf buf = STRBUF_INIT;
906         struct string_list relevant_entries = STRING_LIST_INIT_NODUP;
907         int i;
908
909         /*
910          * We want to sort the last (versions->nr-offset) entries in versions.
911          * Do so by abusing the string_list API a bit: make another string_list
912          * that contains just those entries and then sort them.
913          *
914          * We won't use relevant_entries again and will let it just pop off the
915          * stack, so there won't be allocation worries or anything.
916          */
917         relevant_entries.items = versions->items + offset;
918         relevant_entries.nr = versions->nr - offset;
919         QSORT(relevant_entries.items, relevant_entries.nr, tree_entry_order);
920
921         /* Pre-allocate some space in buf */
922         extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
923         for (i = 0; i < nr; i++) {
924                 maxlen += strlen(versions->items[offset+i].string) + extra;
925         }
926         strbuf_grow(&buf, maxlen);
927
928         /* Write each entry out to buf */
929         for (i = 0; i < nr; i++) {
930                 struct merged_info *mi = versions->items[offset+i].util;
931                 struct version_info *ri = &mi->result;
932                 strbuf_addf(&buf, "%o %s%c",
933                             ri->mode,
934                             versions->items[offset+i].string, '\0');
935                 strbuf_add(&buf, ri->oid.hash, hash_size);
936         }
937
938         /* Write this object file out, and record in result_oid */
939         write_object_file(buf.buf, buf.len, tree_type, result_oid);
940         strbuf_release(&buf);
941 }
942
943 static void record_entry_for_tree(struct directory_versions *dir_metadata,
944                                   const char *path,
945                                   struct merged_info *mi)
946 {
947         const char *basename;
948
949         if (mi->is_null)
950                 /* nothing to record */
951                 return;
952
953         basename = path + mi->basename_offset;
954         assert(strchr(basename, '/') == NULL);
955         string_list_append(&dir_metadata->versions,
956                            basename)->util = &mi->result;
957 }
958
959 static void write_completed_directory(struct merge_options *opt,
960                                       const char *new_directory_name,
961                                       struct directory_versions *info)
962 {
963         const char *prev_dir;
964         struct merged_info *dir_info = NULL;
965         unsigned int offset;
966
967         /*
968          * Some explanation of info->versions and info->offsets...
969          *
970          * process_entries() iterates over all relevant files AND
971          * directories in reverse lexicographic order, and calls this
972          * function.  Thus, an example of the paths that process_entries()
973          * could operate on (along with the directories for those paths
974          * being shown) is:
975          *
976          *     xtract.c             ""
977          *     tokens.txt           ""
978          *     src/moduleB/umm.c    src/moduleB
979          *     src/moduleB/stuff.h  src/moduleB
980          *     src/moduleB/baz.c    src/moduleB
981          *     src/moduleB          src
982          *     src/moduleA/foo.c    src/moduleA
983          *     src/moduleA/bar.c    src/moduleA
984          *     src/moduleA          src
985          *     src                  ""
986          *     Makefile             ""
987          *
988          * info->versions:
989          *
990          *     always contains the unprocessed entries and their
991          *     version_info information.  For example, after the first five
992          *     entries above, info->versions would be:
993          *
994          *         xtract.c     <xtract.c's version_info>
995          *         token.txt    <token.txt's version_info>
996          *         umm.c        <src/moduleB/umm.c's version_info>
997          *         stuff.h      <src/moduleB/stuff.h's version_info>
998          *         baz.c        <src/moduleB/baz.c's version_info>
999          *
1000          *     Once a subdirectory is completed we remove the entries in
1001          *     that subdirectory from info->versions, writing it as a tree
1002          *     (write_tree()).  Thus, as soon as we get to src/moduleB,
1003          *     info->versions would be updated to
1004          *
1005          *         xtract.c     <xtract.c's version_info>
1006          *         token.txt    <token.txt's version_info>
1007          *         moduleB      <src/moduleB's version_info>
1008          *
1009          * info->offsets:
1010          *
1011          *     helps us track which entries in info->versions correspond to
1012          *     which directories.  When we are N directories deep (e.g. 4
1013          *     for src/modA/submod/subdir/), we have up to N+1 unprocessed
1014          *     directories (+1 because of toplevel dir).  Corresponding to
1015          *     the info->versions example above, after processing five entries
1016          *     info->offsets will be:
1017          *
1018          *         ""           0
1019          *         src/moduleB  2
1020          *
1021          *     which is used to know that xtract.c & token.txt are from the
1022          *     toplevel dirctory, while umm.c & stuff.h & baz.c are from the
1023          *     src/moduleB directory.  Again, following the example above,
1024          *     once we need to process src/moduleB, then info->offsets is
1025          *     updated to
1026          *
1027          *         ""           0
1028          *         src          2
1029          *
1030          *     which says that moduleB (and only moduleB so far) is in the
1031          *     src directory.
1032          *
1033          *     One unique thing to note about info->offsets here is that
1034          *     "src" was not added to info->offsets until there was a path
1035          *     (a file OR directory) immediately below src/ that got
1036          *     processed.
1037          *
1038          * Since process_entry() just appends new entries to info->versions,
1039          * write_completed_directory() only needs to do work if the next path
1040          * is in a directory that is different than the last directory found
1041          * in info->offsets.
1042          */
1043
1044         /*
1045          * If we are working with the same directory as the last entry, there
1046          * is no work to do.  (See comments above the directory_name member of
1047          * struct merged_info for why we can use pointer comparison instead of
1048          * strcmp here.)
1049          */
1050         if (new_directory_name == info->last_directory)
1051                 return;
1052
1053         /*
1054          * If we are just starting (last_directory is NULL), or last_directory
1055          * is a prefix of the current directory, then we can just update
1056          * info->offsets to record the offset where we started this directory
1057          * and update last_directory to have quick access to it.
1058          */
1059         if (info->last_directory == NULL ||
1060             !strncmp(new_directory_name, info->last_directory,
1061                      info->last_directory_len)) {
1062                 uintptr_t offset = info->versions.nr;
1063
1064                 info->last_directory = new_directory_name;
1065                 info->last_directory_len = strlen(info->last_directory);
1066                 /*
1067                  * Record the offset into info->versions where we will
1068                  * start recording basenames of paths found within
1069                  * new_directory_name.
1070                  */
1071                 string_list_append(&info->offsets,
1072                                    info->last_directory)->util = (void*)offset;
1073                 return;
1074         }
1075
1076         /*
1077          * The next entry that will be processed will be within
1078          * new_directory_name.  Since at this point we know that
1079          * new_directory_name is within a different directory than
1080          * info->last_directory, we have all entries for info->last_directory
1081          * in info->versions and we need to create a tree object for them.
1082          */
1083         dir_info = strmap_get(&opt->priv->paths, info->last_directory);
1084         assert(dir_info);
1085         offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
1086         if (offset == info->versions.nr) {
1087                 /*
1088                  * Actually, we don't need to create a tree object in this
1089                  * case.  Whenever all files within a directory disappear
1090                  * during the merge (e.g. unmodified on one side and
1091                  * deleted on the other, or files were renamed elsewhere),
1092                  * then we get here and the directory itself needs to be
1093                  * omitted from its parent tree as well.
1094                  */
1095                 dir_info->is_null = 1;
1096         } else {
1097                 /*
1098                  * Write out the tree to the git object directory, and also
1099                  * record the mode and oid in dir_info->result.
1100                  */
1101                 dir_info->is_null = 0;
1102                 dir_info->result.mode = S_IFDIR;
1103                 write_tree(&dir_info->result.oid, &info->versions, offset,
1104                            opt->repo->hash_algo->rawsz);
1105         }
1106
1107         /*
1108          * We've now used several entries from info->versions and one entry
1109          * from info->offsets, so we get rid of those values.
1110          */
1111         info->offsets.nr--;
1112         info->versions.nr = offset;
1113
1114         /*
1115          * Now we've taken care of the completed directory, but we need to
1116          * prepare things since future entries will be in
1117          * new_directory_name.  (In particular, process_entry() will be
1118          * appending new entries to info->versions.)  So, we need to make
1119          * sure new_directory_name is the last entry in info->offsets.
1120          */
1121         prev_dir = info->offsets.nr == 0 ? NULL :
1122                    info->offsets.items[info->offsets.nr-1].string;
1123         if (new_directory_name != prev_dir) {
1124                 uintptr_t c = info->versions.nr;
1125                 string_list_append(&info->offsets,
1126                                    new_directory_name)->util = (void*)c;
1127         }
1128
1129         /* And, of course, we need to update last_directory to match. */
1130         info->last_directory = new_directory_name;
1131         info->last_directory_len = strlen(info->last_directory);
1132 }
1133
1134 /* Per entry merge function */
1135 static void process_entry(struct merge_options *opt,
1136                           const char *path,
1137                           struct conflict_info *ci,
1138                           struct directory_versions *dir_metadata)
1139 {
1140         int df_file_index = 0;
1141
1142         VERIFY_CI(ci);
1143         assert(ci->filemask >= 0 && ci->filemask <= 7);
1144         /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
1145         assert(ci->match_mask == 0 || ci->match_mask == 3 ||
1146                ci->match_mask == 5 || ci->match_mask == 6);
1147
1148         if (ci->dirmask) {
1149                 record_entry_for_tree(dir_metadata, path, &ci->merged);
1150                 if (ci->filemask == 0)
1151                         /* nothing else to handle */
1152                         return;
1153                 assert(ci->df_conflict);
1154         }
1155
1156         if (ci->df_conflict && ci->merged.result.mode == 0) {
1157                 int i;
1158
1159                 /*
1160                  * directory no longer in the way, but we do have a file we
1161                  * need to place here so we need to clean away the "directory
1162                  * merges to nothing" result.
1163                  */
1164                 ci->df_conflict = 0;
1165                 assert(ci->filemask != 0);
1166                 ci->merged.clean = 0;
1167                 ci->merged.is_null = 0;
1168                 /* and we want to zero out any directory-related entries */
1169                 ci->match_mask = (ci->match_mask & ~ci->dirmask);
1170                 ci->dirmask = 0;
1171                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1172                         if (ci->filemask & (1 << i))
1173                                 continue;
1174                         ci->stages[i].mode = 0;
1175                         oidcpy(&ci->stages[i].oid, &null_oid);
1176                 }
1177         } else if (ci->df_conflict && ci->merged.result.mode != 0) {
1178                 /*
1179                  * This started out as a D/F conflict, and the entries in
1180                  * the competing directory were not removed by the merge as
1181                  * evidenced by write_completed_directory() writing a value
1182                  * to ci->merged.result.mode.
1183                  */
1184                 struct conflict_info *new_ci;
1185                 const char *branch;
1186                 const char *old_path = path;
1187                 int i;
1188
1189                 assert(ci->merged.result.mode == S_IFDIR);
1190
1191                 /*
1192                  * If filemask is 1, we can just ignore the file as having
1193                  * been deleted on both sides.  We do not want to overwrite
1194                  * ci->merged.result, since it stores the tree for all the
1195                  * files under it.
1196                  */
1197                 if (ci->filemask == 1) {
1198                         ci->filemask = 0;
1199                         return;
1200                 }
1201
1202                 /*
1203                  * This file still exists on at least one side, and we want
1204                  * the directory to remain here, so we need to move this
1205                  * path to some new location.
1206                  */
1207                 new_ci = xcalloc(1, sizeof(*new_ci));
1208                 /* We don't really want new_ci->merged.result copied, but it'll
1209                  * be overwritten below so it doesn't matter.  We also don't
1210                  * want any directory mode/oid values copied, but we'll zero
1211                  * those out immediately.  We do want the rest of ci copied.
1212                  */
1213                 memcpy(new_ci, ci, sizeof(*ci));
1214                 new_ci->match_mask = (new_ci->match_mask & ~new_ci->dirmask);
1215                 new_ci->dirmask = 0;
1216                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1217                         if (new_ci->filemask & (1 << i))
1218                                 continue;
1219                         /* zero out any entries related to directories */
1220                         new_ci->stages[i].mode = 0;
1221                         oidcpy(&new_ci->stages[i].oid, &null_oid);
1222                 }
1223
1224                 /*
1225                  * Find out which side this file came from; note that we
1226                  * cannot just use ci->filemask, because renames could cause
1227                  * the filemask to go back to 7.  So we use dirmask, then
1228                  * pick the opposite side's index.
1229                  */
1230                 df_file_index = (ci->dirmask & (1 << 1)) ? 2 : 1;
1231                 branch = (df_file_index == 1) ? opt->branch1 : opt->branch2;
1232                 path = unique_path(&opt->priv->paths, path, branch);
1233                 strmap_put(&opt->priv->paths, path, new_ci);
1234
1235                 path_msg(opt, path, 0,
1236                          _("CONFLICT (file/directory): directory in the way "
1237                            "of %s from %s; moving it to %s instead."),
1238                          old_path, branch, path);
1239
1240                 /*
1241                  * Zero out the filemask for the old ci.  At this point, ci
1242                  * was just an entry for a directory, so we don't need to
1243                  * do anything more with it.
1244                  */
1245                 ci->filemask = 0;
1246
1247                 /*
1248                  * Now note that we're working on the new entry (path was
1249                  * updated above.
1250                  */
1251                 ci = new_ci;
1252         }
1253
1254         /*
1255          * NOTE: Below there is a long switch-like if-elseif-elseif... block
1256          *       which the code goes through even for the df_conflict cases
1257          *       above.
1258          */
1259         if (ci->match_mask) {
1260                 ci->merged.clean = 1;
1261                 if (ci->match_mask == 6) {
1262                         /* stages[1] == stages[2] */
1263                         ci->merged.result.mode = ci->stages[1].mode;
1264                         oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
1265                 } else {
1266                         /* determine the mask of the side that didn't match */
1267                         unsigned int othermask = 7 & ~ci->match_mask;
1268                         int side = (othermask == 4) ? 2 : 1;
1269
1270                         ci->merged.result.mode = ci->stages[side].mode;
1271                         ci->merged.is_null = !ci->merged.result.mode;
1272                         oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1273
1274                         assert(othermask == 2 || othermask == 4);
1275                         assert(ci->merged.is_null ==
1276                                (ci->filemask == ci->match_mask));
1277                 }
1278         } else if (ci->filemask >= 6 &&
1279                    (S_IFMT & ci->stages[1].mode) !=
1280                    (S_IFMT & ci->stages[2].mode)) {
1281                 /*
1282                  * Two different items from (file/submodule/symlink)
1283                  */
1284                 die("Not yet implemented.");
1285         } else if (ci->filemask >= 6) {
1286                 /* Need a two-way or three-way content merge */
1287                 struct version_info merged_file;
1288                 unsigned clean_merge;
1289                 struct version_info *o = &ci->stages[0];
1290                 struct version_info *a = &ci->stages[1];
1291                 struct version_info *b = &ci->stages[2];
1292
1293                 clean_merge = handle_content_merge(opt, path, o, a, b,
1294                                                    ci->pathnames,
1295                                                    opt->priv->call_depth * 2,
1296                                                    &merged_file);
1297                 ci->merged.clean = clean_merge &&
1298                                    !ci->df_conflict && !ci->path_conflict;
1299                 ci->merged.result.mode = merged_file.mode;
1300                 ci->merged.is_null = (merged_file.mode == 0);
1301                 oidcpy(&ci->merged.result.oid, &merged_file.oid);
1302                 if (clean_merge && ci->df_conflict) {
1303                         assert(df_file_index == 1 || df_file_index == 2);
1304                         ci->filemask = 1 << df_file_index;
1305                         ci->stages[df_file_index].mode = merged_file.mode;
1306                         oidcpy(&ci->stages[df_file_index].oid, &merged_file.oid);
1307                 }
1308                 if (!clean_merge) {
1309                         const char *reason = _("content");
1310                         if (ci->filemask == 6)
1311                                 reason = _("add/add");
1312                         if (S_ISGITLINK(merged_file.mode))
1313                                 reason = _("submodule");
1314                         path_msg(opt, path, 0,
1315                                  _("CONFLICT (%s): Merge conflict in %s"),
1316                                  reason, path);
1317                 }
1318         } else if (ci->filemask == 3 || ci->filemask == 5) {
1319                 /* Modify/delete */
1320                 const char *modify_branch, *delete_branch;
1321                 int side = (ci->filemask == 5) ? 2 : 1;
1322                 int index = opt->priv->call_depth ? 0 : side;
1323
1324                 ci->merged.result.mode = ci->stages[index].mode;
1325                 oidcpy(&ci->merged.result.oid, &ci->stages[index].oid);
1326                 ci->merged.clean = 0;
1327
1328                 modify_branch = (side == 1) ? opt->branch1 : opt->branch2;
1329                 delete_branch = (side == 1) ? opt->branch2 : opt->branch1;
1330
1331                 path_msg(opt, path, 0,
1332                          _("CONFLICT (modify/delete): %s deleted in %s "
1333                            "and modified in %s.  Version %s of %s left "
1334                            "in tree."),
1335                          path, delete_branch, modify_branch,
1336                          modify_branch, path);
1337         } else if (ci->filemask == 2 || ci->filemask == 4) {
1338                 /* Added on one side */
1339                 int side = (ci->filemask == 4) ? 2 : 1;
1340                 ci->merged.result.mode = ci->stages[side].mode;
1341                 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
1342                 ci->merged.clean = !ci->df_conflict;
1343         } else if (ci->filemask == 1) {
1344                 /* Deleted on both sides */
1345                 ci->merged.is_null = 1;
1346                 ci->merged.result.mode = 0;
1347                 oidcpy(&ci->merged.result.oid, &null_oid);
1348                 ci->merged.clean = 1;
1349         }
1350
1351         /*
1352          * If still conflicted, record it separately.  This allows us to later
1353          * iterate over just conflicted entries when updating the index instead
1354          * of iterating over all entries.
1355          */
1356         if (!ci->merged.clean)
1357                 strmap_put(&opt->priv->conflicted, path, ci);
1358         record_entry_for_tree(dir_metadata, path, &ci->merged);
1359 }
1360
1361 static void process_entries(struct merge_options *opt,
1362                             struct object_id *result_oid)
1363 {
1364         struct hashmap_iter iter;
1365         struct strmap_entry *e;
1366         struct string_list plist = STRING_LIST_INIT_NODUP;
1367         struct string_list_item *entry;
1368         struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
1369                                                    STRING_LIST_INIT_NODUP,
1370                                                    NULL, 0 };
1371
1372         if (strmap_empty(&opt->priv->paths)) {
1373                 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
1374                 return;
1375         }
1376
1377         /* Hack to pre-allocate plist to the desired size */
1378         ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
1379
1380         /* Put every entry from paths into plist, then sort */
1381         strmap_for_each_entry(&opt->priv->paths, &iter, e) {
1382                 string_list_append(&plist, e->key)->util = e->value;
1383         }
1384         plist.cmp = string_list_df_name_compare;
1385         string_list_sort(&plist);
1386
1387         /*
1388          * Iterate over the items in reverse order, so we can handle paths
1389          * below a directory before needing to handle the directory itself.
1390          *
1391          * This allows us to write subtrees before we need to write trees,
1392          * and it also enables sane handling of directory/file conflicts
1393          * (because it allows us to know whether the directory is still in
1394          * the way when it is time to process the file at the same path).
1395          */
1396         for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
1397                 char *path = entry->string;
1398                 /*
1399                  * NOTE: mi may actually be a pointer to a conflict_info, but
1400                  * we have to check mi->clean first to see if it's safe to
1401                  * reassign to such a pointer type.
1402                  */
1403                 struct merged_info *mi = entry->util;
1404
1405                 write_completed_directory(opt, mi->directory_name,
1406                                           &dir_metadata);
1407                 if (mi->clean)
1408                         record_entry_for_tree(&dir_metadata, path, mi);
1409                 else {
1410                         struct conflict_info *ci = (struct conflict_info *)mi;
1411                         process_entry(opt, path, ci, &dir_metadata);
1412                 }
1413         }
1414
1415         if (dir_metadata.offsets.nr != 1 ||
1416             (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
1417                 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
1418                        dir_metadata.offsets.nr);
1419                 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
1420                        (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
1421                 fflush(stdout);
1422                 BUG("dir_metadata accounting completely off; shouldn't happen");
1423         }
1424         write_tree(result_oid, &dir_metadata.versions, 0,
1425                    opt->repo->hash_algo->rawsz);
1426         string_list_clear(&plist, 0);
1427         string_list_clear(&dir_metadata.versions, 0);
1428         string_list_clear(&dir_metadata.offsets, 0);
1429 }
1430
1431 /*** Function Grouping: functions related to merge_switch_to_result() ***/
1432
1433 static int checkout(struct merge_options *opt,
1434                     struct tree *prev,
1435                     struct tree *next)
1436 {
1437         /* Switch the index/working copy from old to new */
1438         int ret;
1439         struct tree_desc trees[2];
1440         struct unpack_trees_options unpack_opts;
1441
1442         memset(&unpack_opts, 0, sizeof(unpack_opts));
1443         unpack_opts.head_idx = -1;
1444         unpack_opts.src_index = opt->repo->index;
1445         unpack_opts.dst_index = opt->repo->index;
1446
1447         setup_unpack_trees_porcelain(&unpack_opts, "merge");
1448
1449         /*
1450          * NOTE: if this were just "git checkout" code, we would probably
1451          * read or refresh the cache and check for a conflicted index, but
1452          * builtin/merge.c or sequencer.c really needs to read the index
1453          * and check for conflicted entries before starting merging for a
1454          * good user experience (no sense waiting for merges/rebases before
1455          * erroring out), so there's no reason to duplicate that work here.
1456          */
1457
1458         /* 2-way merge to the new branch */
1459         unpack_opts.update = 1;
1460         unpack_opts.merge = 1;
1461         unpack_opts.quiet = 0; /* FIXME: sequencer might want quiet? */
1462         unpack_opts.verbose_update = (opt->verbosity > 2);
1463         unpack_opts.fn = twoway_merge;
1464         if (1/* FIXME: opts->overwrite_ignore*/) {
1465                 unpack_opts.dir = xcalloc(1, sizeof(*unpack_opts.dir));
1466                 unpack_opts.dir->flags |= DIR_SHOW_IGNORED;
1467                 setup_standard_excludes(unpack_opts.dir);
1468         }
1469         parse_tree(prev);
1470         init_tree_desc(&trees[0], prev->buffer, prev->size);
1471         parse_tree(next);
1472         init_tree_desc(&trees[1], next->buffer, next->size);
1473
1474         ret = unpack_trees(2, trees, &unpack_opts);
1475         clear_unpack_trees_porcelain(&unpack_opts);
1476         dir_clear(unpack_opts.dir);
1477         FREE_AND_NULL(unpack_opts.dir);
1478         return ret;
1479 }
1480
1481 static int record_conflicted_index_entries(struct merge_options *opt,
1482                                            struct index_state *index,
1483                                            struct strmap *paths,
1484                                            struct strmap *conflicted)
1485 {
1486         struct hashmap_iter iter;
1487         struct strmap_entry *e;
1488         int errs = 0;
1489         int original_cache_nr;
1490
1491         if (strmap_empty(conflicted))
1492                 return 0;
1493
1494         original_cache_nr = index->cache_nr;
1495
1496         /* Put every entry from paths into plist, then sort */
1497         strmap_for_each_entry(conflicted, &iter, e) {
1498                 const char *path = e->key;
1499                 struct conflict_info *ci = e->value;
1500                 int pos;
1501                 struct cache_entry *ce;
1502                 int i;
1503
1504                 VERIFY_CI(ci);
1505
1506                 /*
1507                  * The index will already have a stage=0 entry for this path,
1508                  * because we created an as-merged-as-possible version of the
1509                  * file and checkout() moved the working copy and index over
1510                  * to that version.
1511                  *
1512                  * However, previous iterations through this loop will have
1513                  * added unstaged entries to the end of the cache which
1514                  * ignore the standard alphabetical ordering of cache
1515                  * entries and break invariants needed for index_name_pos()
1516                  * to work.  However, we know the entry we want is before
1517                  * those appended cache entries, so do a temporary swap on
1518                  * cache_nr to only look through entries of interest.
1519                  */
1520                 SWAP(index->cache_nr, original_cache_nr);
1521                 pos = index_name_pos(index, path, strlen(path));
1522                 SWAP(index->cache_nr, original_cache_nr);
1523                 if (pos < 0) {
1524                         if (ci->filemask != 1)
1525                                 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path);
1526                         cache_tree_invalidate_path(index, path);
1527                 } else {
1528                         ce = index->cache[pos];
1529
1530                         /*
1531                          * Clean paths with CE_SKIP_WORKTREE set will not be
1532                          * written to the working tree by the unpack_trees()
1533                          * call in checkout().  Our conflicted entries would
1534                          * have appeared clean to that code since we ignored
1535                          * the higher order stages.  Thus, we need override
1536                          * the CE_SKIP_WORKTREE bit and manually write those
1537                          * files to the working disk here.
1538                          *
1539                          * TODO: Implement this CE_SKIP_WORKTREE fixup.
1540                          */
1541
1542                         /*
1543                          * Mark this cache entry for removal and instead add
1544                          * new stage>0 entries corresponding to the
1545                          * conflicts.  If there are many conflicted entries, we
1546                          * want to avoid memmove'ing O(NM) entries by
1547                          * inserting the new entries one at a time.  So,
1548                          * instead, we just add the new cache entries to the
1549                          * end (ignoring normal index requirements on sort
1550                          * order) and sort the index once we're all done.
1551                          */
1552                         ce->ce_flags |= CE_REMOVE;
1553                 }
1554
1555                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1556                         struct version_info *vi;
1557                         if (!(ci->filemask & (1ul << i)))
1558                                 continue;
1559                         vi = &ci->stages[i];
1560                         ce = make_cache_entry(index, vi->mode, &vi->oid,
1561                                               path, i+1, 0);
1562                         add_index_entry(index, ce, ADD_CACHE_JUST_APPEND);
1563                 }
1564         }
1565
1566         /*
1567          * Remove the unused cache entries (and invalidate the relevant
1568          * cache-trees), then sort the index entries to get the conflicted
1569          * entries we added to the end into their right locations.
1570          */
1571         remove_marked_cache_entries(index, 1);
1572         QSORT(index->cache, index->cache_nr, cmp_cache_name_compare);
1573
1574         return errs;
1575 }
1576
1577 void merge_switch_to_result(struct merge_options *opt,
1578                             struct tree *head,
1579                             struct merge_result *result,
1580                             int update_worktree_and_index,
1581                             int display_update_msgs)
1582 {
1583         assert(opt->priv == NULL);
1584         if (result->clean >= 0 && update_worktree_and_index) {
1585                 struct merge_options_internal *opti = result->priv;
1586
1587                 if (checkout(opt, head, result->tree)) {
1588                         /* failure to function */
1589                         result->clean = -1;
1590                         return;
1591                 }
1592
1593                 if (record_conflicted_index_entries(opt, opt->repo->index,
1594                                                     &opti->paths,
1595                                                     &opti->conflicted)) {
1596                         /* failure to function */
1597                         result->clean = -1;
1598                         return;
1599                 }
1600         }
1601
1602         if (display_update_msgs) {
1603                 struct merge_options_internal *opti = result->priv;
1604                 struct hashmap_iter iter;
1605                 struct strmap_entry *e;
1606                 struct string_list olist = STRING_LIST_INIT_NODUP;
1607                 int i;
1608
1609                 /* Hack to pre-allocate olist to the desired size */
1610                 ALLOC_GROW(olist.items, strmap_get_size(&opti->output),
1611                            olist.alloc);
1612
1613                 /* Put every entry from output into olist, then sort */
1614                 strmap_for_each_entry(&opti->output, &iter, e) {
1615                         string_list_append(&olist, e->key)->util = e->value;
1616                 }
1617                 string_list_sort(&olist);
1618
1619                 /* Iterate over the items, printing them */
1620                 for (i = 0; i < olist.nr; ++i) {
1621                         struct strbuf *sb = olist.items[i].util;
1622
1623                         printf("%s", sb->buf);
1624                 }
1625                 string_list_clear(&olist, 0);
1626         }
1627
1628         merge_finalize(opt, result);
1629 }
1630
1631 void merge_finalize(struct merge_options *opt,
1632                     struct merge_result *result)
1633 {
1634         struct merge_options_internal *opti = result->priv;
1635
1636         assert(opt->priv == NULL);
1637
1638         clear_internal_opts(opti, 0);
1639         FREE_AND_NULL(opti);
1640 }
1641
1642 /*** Function Grouping: helper functions for merge_incore_*() ***/
1643
1644 static void merge_start(struct merge_options *opt, struct merge_result *result)
1645 {
1646         /* Sanity checks on opt */
1647         assert(opt->repo);
1648
1649         assert(opt->branch1 && opt->branch2);
1650
1651         assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
1652                opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
1653         assert(opt->rename_limit >= -1);
1654         assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
1655         assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
1656
1657         assert(opt->xdl_opts >= 0);
1658         assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
1659                opt->recursive_variant <= MERGE_VARIANT_THEIRS);
1660
1661         /*
1662          * detect_renames, verbosity, buffer_output, and obuf are ignored
1663          * fields that were used by "recursive" rather than "ort" -- but
1664          * sanity check them anyway.
1665          */
1666         assert(opt->detect_renames >= -1 &&
1667                opt->detect_renames <= DIFF_DETECT_COPY);
1668         assert(opt->verbosity >= 0 && opt->verbosity <= 5);
1669         assert(opt->buffer_output <= 2);
1670         assert(opt->obuf.len == 0);
1671
1672         assert(opt->priv == NULL);
1673
1674         /* Default to histogram diff.  Actually, just hardcode it...for now. */
1675         opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
1676
1677         /* Initialization of opt->priv, our internal merge data */
1678         opt->priv = xcalloc(1, sizeof(*opt->priv));
1679
1680         /*
1681          * Although we initialize opt->priv->paths with strdup_strings=0,
1682          * that's just to avoid making yet another copy of an allocated
1683          * string.  Putting the entry into paths means we are taking
1684          * ownership, so we will later free it.  paths_to_free is similar.
1685          *
1686          * In contrast, conflicted just has a subset of keys from paths, so
1687          * we don't want to free those (it'd be a duplicate free).
1688          */
1689         strmap_init_with_options(&opt->priv->paths, NULL, 0);
1690         strmap_init_with_options(&opt->priv->conflicted, NULL, 0);
1691         string_list_init(&opt->priv->paths_to_free, 0);
1692
1693         /*
1694          * keys & strbufs in output will sometimes need to outlive "paths",
1695          * so it will have a copy of relevant keys.  It's probably a small
1696          * subset of the overall paths that have special output.
1697          */
1698         strmap_init(&opt->priv->output);
1699 }
1700
1701 /*** Function Grouping: merge_incore_*() and their internal variants ***/
1702
1703 /*
1704  * Originally from merge_trees_internal(); heavily adapted, though.
1705  */
1706 static void merge_ort_nonrecursive_internal(struct merge_options *opt,
1707                                             struct tree *merge_base,
1708                                             struct tree *side1,
1709                                             struct tree *side2,
1710                                             struct merge_result *result)
1711 {
1712         struct object_id working_tree_oid;
1713
1714         if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
1715                 /*
1716                  * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
1717                  * base, and 2-3) the trees for the two trees we're merging.
1718                  */
1719                 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
1720                     oid_to_hex(&merge_base->object.oid),
1721                     oid_to_hex(&side1->object.oid),
1722                     oid_to_hex(&side2->object.oid));
1723                 result->clean = -1;
1724                 return;
1725         }
1726
1727         result->clean = detect_and_process_renames(opt, merge_base,
1728                                                    side1, side2);
1729         process_entries(opt, &working_tree_oid);
1730
1731         /* Set return values */
1732         result->tree = parse_tree_indirect(&working_tree_oid);
1733         /* existence of conflicted entries implies unclean */
1734         result->clean &= strmap_empty(&opt->priv->conflicted);
1735         if (!opt->priv->call_depth) {
1736                 result->priv = opt->priv;
1737                 opt->priv = NULL;
1738         }
1739 }
1740
1741 void merge_incore_nonrecursive(struct merge_options *opt,
1742                                struct tree *merge_base,
1743                                struct tree *side1,
1744                                struct tree *side2,
1745                                struct merge_result *result)
1746 {
1747         assert(opt->ancestor != NULL);
1748         merge_start(opt, result);
1749         merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
1750 }
1751
1752 void merge_incore_recursive(struct merge_options *opt,
1753                             struct commit_list *merge_bases,
1754                             struct commit *side1,
1755                             struct commit *side2,
1756                             struct merge_result *result)
1757 {
1758         die("Not yet implemented");
1759 }