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