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