unpack_trees(): minor memory leak fix in unused destination index
[git] / unpack-trees.c
1 #define NO_THE_INDEX_COMPATIBILITY_MACROS
2 #include "cache.h"
3 #include "dir.h"
4 #include "tree.h"
5 #include "tree-walk.h"
6 #include "cache-tree.h"
7 #include "unpack-trees.h"
8 #include "progress.h"
9 #include "refs.h"
10
11 static void add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
12         unsigned int set, unsigned int clear)
13 {
14         unsigned int size = ce_size(ce);
15         struct cache_entry *new = xmalloc(size);
16
17         clear |= CE_HASHED | CE_UNHASHED;
18
19         memcpy(new, ce, size);
20         new->next = NULL;
21         new->ce_flags = (new->ce_flags & ~clear) | set;
22         add_index_entry(&o->result, new, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE|ADD_CACHE_SKIP_DFCHECK);
23 }
24
25 /* Unlink the last component and attempt to remove leading
26  * directories, in case this unlink is the removal of the
27  * last entry in the directory -- empty directories are removed.
28  */
29 static void unlink_entry(char *name, char *last_symlink)
30 {
31         char *cp, *prev;
32
33         if (has_symlink_leading_path(name, last_symlink))
34                 return;
35         if (unlink(name))
36                 return;
37         prev = NULL;
38         while (1) {
39                 int status;
40                 cp = strrchr(name, '/');
41                 if (prev)
42                         *prev = '/';
43                 if (!cp)
44                         break;
45
46                 *cp = 0;
47                 status = rmdir(name);
48                 if (status) {
49                         *cp = '/';
50                         break;
51                 }
52                 prev = cp;
53         }
54 }
55
56 static struct checkout state;
57 static void check_updates(struct unpack_trees_options *o)
58 {
59         unsigned cnt = 0, total = 0;
60         struct progress *progress = NULL;
61         char last_symlink[PATH_MAX];
62         struct index_state *index = &o->result;
63         int i;
64
65         if (o->update && o->verbose_update) {
66                 for (total = cnt = 0; cnt < index->cache_nr; cnt++) {
67                         struct cache_entry *ce = index->cache[cnt];
68                         if (ce->ce_flags & (CE_UPDATE | CE_REMOVE))
69                                 total++;
70                 }
71
72                 progress = start_progress_delay("Checking out files",
73                                                 total, 50, 1);
74                 cnt = 0;
75         }
76
77         *last_symlink = '\0';
78         for (i = 0; i < index->cache_nr; i++) {
79                 struct cache_entry *ce = index->cache[i];
80
81                 if (ce->ce_flags & (CE_UPDATE | CE_REMOVE))
82                         display_progress(progress, ++cnt);
83                 if (ce->ce_flags & CE_REMOVE) {
84                         if (o->update)
85                                 unlink_entry(ce->name, last_symlink);
86                         remove_index_entry_at(&o->result, i);
87                         i--;
88                         continue;
89                 }
90                 if (ce->ce_flags & CE_UPDATE) {
91                         ce->ce_flags &= ~CE_UPDATE;
92                         if (o->update) {
93                                 checkout_entry(ce, &state, NULL);
94                                 *last_symlink = '\0';
95                         }
96                 }
97         }
98         stop_progress(&progress);
99 }
100
101 static inline int call_unpack_fn(struct cache_entry **src, struct unpack_trees_options *o)
102 {
103         int ret = o->fn(src, o);
104         if (ret > 0)
105                 ret = 0;
106         return ret;
107 }
108
109 static int unpack_index_entry(struct cache_entry *ce, struct unpack_trees_options *o)
110 {
111         struct cache_entry *src[5] = { ce, };
112
113         o->pos++;
114         if (ce_stage(ce)) {
115                 if (o->skip_unmerged) {
116                         add_entry(o, ce, 0, 0);
117                         return 0;
118                 }
119                 return 0;
120         }
121         return call_unpack_fn(src, o);
122 }
123
124 int traverse_trees_recursive(int n, unsigned long dirmask, unsigned long df_conflicts, struct name_entry *names, struct traverse_info *info)
125 {
126         int i;
127         struct tree_desc t[3];
128         struct traverse_info newinfo;
129         struct name_entry *p;
130
131         p = names;
132         while (!p->mode)
133                 p++;
134
135         newinfo = *info;
136         newinfo.prev = info;
137         newinfo.name = *p;
138         newinfo.pathlen += tree_entry_len(p->path, p->sha1) + 1;
139         newinfo.conflicts |= df_conflicts;
140
141         for (i = 0; i < n; i++, dirmask >>= 1) {
142                 const unsigned char *sha1 = NULL;
143                 if (dirmask & 1)
144                         sha1 = names[i].sha1;
145                 fill_tree_descriptor(t+i, sha1);
146         }
147         traverse_trees(n, t, &newinfo);
148         return 0;
149 }
150
151 /*
152  * Compare the traverse-path to the cache entry without actually
153  * having to generate the textual representation of the traverse
154  * path.
155  *
156  * NOTE! This *only* compares up to the size of the traverse path
157  * itself - the caller needs to do the final check for the cache
158  * entry having more data at the end!
159  */
160 static int do_compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
161 {
162         int len, pathlen, ce_len;
163         const char *ce_name;
164
165         if (info->prev) {
166                 int cmp = do_compare_entry(ce, info->prev, &info->name);
167                 if (cmp)
168                         return cmp;
169         }
170         pathlen = info->pathlen;
171         ce_len = ce_namelen(ce);
172
173         /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
174         if (ce_len < pathlen)
175                 return -1;
176
177         ce_len -= pathlen;
178         ce_name = ce->name + pathlen;
179
180         len = tree_entry_len(n->path, n->sha1);
181         return df_name_compare(ce_name, ce_len, S_IFREG, n->path, len, n->mode);
182 }
183
184 static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
185 {
186         int cmp = do_compare_entry(ce, info, n);
187         if (cmp)
188                 return cmp;
189
190         /*
191          * Even if the beginning compared identically, the ce should
192          * compare as bigger than a directory leading up to it!
193          */
194         return ce_namelen(ce) > traverse_path_len(info, n);
195 }
196
197 static struct cache_entry *create_ce_entry(const struct traverse_info *info, const struct name_entry *n, int stage)
198 {
199         int len = traverse_path_len(info, n);
200         struct cache_entry *ce = xcalloc(1, cache_entry_size(len));
201
202         ce->ce_mode = create_ce_mode(n->mode);
203         ce->ce_flags = create_ce_flags(len, stage);
204         hashcpy(ce->sha1, n->sha1);
205         make_traverse_path(ce->name, info, n);
206
207         return ce;
208 }
209
210 static int unpack_nondirectories(int n, unsigned long mask, unsigned long dirmask, struct cache_entry *src[5],
211         const struct name_entry *names, const struct traverse_info *info)
212 {
213         int i;
214         struct unpack_trees_options *o = info->data;
215         unsigned long conflicts;
216
217         /* Do we have *only* directories? Nothing to do */
218         if (mask == dirmask && !src[0])
219                 return 0;
220
221         conflicts = info->conflicts;
222         if (o->merge)
223                 conflicts >>= 1;
224         conflicts |= dirmask;
225
226         /*
227          * Ok, we've filled in up to any potential index entry in src[0],
228          * now do the rest.
229          */
230         for (i = 0; i < n; i++) {
231                 int stage;
232                 unsigned int bit = 1ul << i;
233                 if (conflicts & bit) {
234                         src[i + o->merge] = o->df_conflict_entry;
235                         continue;
236                 }
237                 if (!(mask & bit))
238                         continue;
239                 if (!o->merge)
240                         stage = 0;
241                 else if (i + 1 < o->head_idx)
242                         stage = 1;
243                 else if (i + 1 > o->head_idx)
244                         stage = 3;
245                 else
246                         stage = 2;
247                 src[i + o->merge] = create_ce_entry(info, names + i, stage);
248         }
249
250         if (o->merge)
251                 return call_unpack_fn(src, o);
252
253         n += o->merge;
254         for (i = 0; i < n; i++)
255                 add_entry(o, src[i], 0, 0);
256         return 0;
257 }
258
259 static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
260 {
261         struct cache_entry *src[5] = { NULL, };
262         struct unpack_trees_options *o = info->data;
263         const struct name_entry *p = names;
264
265         /* Find first entry with a real name (we could use "mask" too) */
266         while (!p->mode)
267                 p++;
268
269         /* Are we supposed to look at the index too? */
270         if (o->merge) {
271                 while (o->pos < o->src_index->cache_nr) {
272                         struct cache_entry *ce = o->src_index->cache[o->pos];
273                         int cmp = compare_entry(ce, info, p);
274                         if (cmp < 0) {
275                                 if (unpack_index_entry(ce, o) < 0)
276                                         return -1;
277                                 continue;
278                         }
279                         if (!cmp) {
280                                 o->pos++;
281                                 if (ce_stage(ce)) {
282                                         /*
283                                          * If we skip unmerged index entries, we'll skip this
284                                          * entry *and* the tree entries associated with it!
285                                          */
286                                         if (o->skip_unmerged) {
287                                                 add_entry(o, ce, 0, 0);
288                                                 return mask;
289                                         }
290                                         continue;
291                                 }
292                                 src[0] = ce;
293                         }
294                         break;
295                 }
296         }
297
298         if (unpack_nondirectories(n, mask, dirmask, src, names, info) < 0)
299                 return -1;
300
301         /* Now handle any directories.. */
302         if (dirmask) {
303                 unsigned long conflicts = mask & ~dirmask;
304                 if (o->merge) {
305                         conflicts <<= 1;
306                         if (src[0])
307                                 conflicts |= 1;
308                 }
309                 traverse_trees_recursive(n, dirmask, conflicts, names, info);
310                 return mask;
311         }
312
313         return mask;
314 }
315
316 static int unpack_failed(struct unpack_trees_options *o, const char *message)
317 {
318         discard_index(&o->result);
319         if (!o->gently) {
320                 if (message)
321                         return error(message);
322                 return -1;
323         }
324         return -1;
325 }
326
327 int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
328 {
329         static struct cache_entry *dfc;
330
331         if (len > 4)
332                 die("unpack_trees takes at most four trees");
333         memset(&state, 0, sizeof(state));
334         state.base_dir = "";
335         state.force = 1;
336         state.quiet = 1;
337         state.refresh_cache = 1;
338
339         memset(&o->result, 0, sizeof(o->result));
340         o->merge_size = len;
341
342         if (!dfc)
343                 dfc = xcalloc(1, sizeof(struct cache_entry) + 1);
344         o->df_conflict_entry = dfc;
345
346         if (len) {
347                 const char *prefix = o->prefix ? o->prefix : "";
348                 struct traverse_info info;
349
350                 setup_traverse_info(&info, prefix);
351                 info.fn = unpack_callback;
352                 info.data = o;
353
354                 if (traverse_trees(len, t, &info) < 0)
355                         return unpack_failed(o, NULL);
356         }
357
358         /* Any left-over entries in the index? */
359         if (o->merge) {
360                 while (o->pos < o->src_index->cache_nr) {
361                         struct cache_entry *ce = o->src_index->cache[o->pos];
362                         if (unpack_index_entry(ce, o) < 0)
363                                 return unpack_failed(o, NULL);
364                 }
365         }
366
367         if (o->trivial_merges_only && o->nontrivial_merge)
368                 return unpack_failed(o, "Merge requires file-level merging");
369
370         o->src_index = NULL;
371         check_updates(o);
372         if (o->dst_index)
373                 *o->dst_index = o->result;
374         return 0;
375 }
376
377 /* Here come the merge functions */
378
379 static int reject_merge(struct cache_entry *ce)
380 {
381         return error("Entry '%s' would be overwritten by merge. Cannot merge.",
382                      ce->name);
383 }
384
385 static int same(struct cache_entry *a, struct cache_entry *b)
386 {
387         if (!!a != !!b)
388                 return 0;
389         if (!a && !b)
390                 return 1;
391         return a->ce_mode == b->ce_mode &&
392                !hashcmp(a->sha1, b->sha1);
393 }
394
395
396 /*
397  * When a CE gets turned into an unmerged entry, we
398  * want it to be up-to-date
399  */
400 static int verify_uptodate(struct cache_entry *ce,
401                 struct unpack_trees_options *o)
402 {
403         struct stat st;
404
405         if (o->index_only || o->reset)
406                 return 0;
407
408         if (!lstat(ce->name, &st)) {
409                 unsigned changed = ie_match_stat(o->src_index, ce, &st, CE_MATCH_IGNORE_VALID);
410                 if (!changed)
411                         return 0;
412                 /*
413                  * NEEDSWORK: the current default policy is to allow
414                  * submodule to be out of sync wrt the supermodule
415                  * index.  This needs to be tightened later for
416                  * submodules that are marked to be automatically
417                  * checked out.
418                  */
419                 if (S_ISGITLINK(ce->ce_mode))
420                         return 0;
421                 errno = 0;
422         }
423         if (errno == ENOENT)
424                 return 0;
425         return o->gently ? -1 :
426                 error("Entry '%s' not uptodate. Cannot merge.", ce->name);
427 }
428
429 static void invalidate_ce_path(struct cache_entry *ce, struct unpack_trees_options *o)
430 {
431         if (ce)
432                 cache_tree_invalidate_path(o->src_index->cache_tree, ce->name);
433 }
434
435 /*
436  * Check that checking out ce->sha1 in subdir ce->name is not
437  * going to overwrite any working files.
438  *
439  * Currently, git does not checkout subprojects during a superproject
440  * checkout, so it is not going to overwrite anything.
441  */
442 static int verify_clean_submodule(struct cache_entry *ce, const char *action,
443                                       struct unpack_trees_options *o)
444 {
445         return 0;
446 }
447
448 static int verify_clean_subdirectory(struct cache_entry *ce, const char *action,
449                                       struct unpack_trees_options *o)
450 {
451         /*
452          * we are about to extract "ce->name"; we would not want to lose
453          * anything in the existing directory there.
454          */
455         int namelen;
456         int pos, i;
457         struct dir_struct d;
458         char *pathbuf;
459         int cnt = 0;
460         unsigned char sha1[20];
461
462         if (S_ISGITLINK(ce->ce_mode) &&
463             resolve_gitlink_ref(ce->name, "HEAD", sha1) == 0) {
464                 /* If we are not going to update the submodule, then
465                  * we don't care.
466                  */
467                 if (!hashcmp(sha1, ce->sha1))
468                         return 0;
469                 return verify_clean_submodule(ce, action, o);
470         }
471
472         /*
473          * First let's make sure we do not have a local modification
474          * in that directory.
475          */
476         namelen = strlen(ce->name);
477         pos = index_name_pos(o->src_index, ce->name, namelen);
478         if (0 <= pos)
479                 return cnt; /* we have it as nondirectory */
480         pos = -pos - 1;
481         for (i = pos; i < o->src_index->cache_nr; i++) {
482                 struct cache_entry *ce = o->src_index->cache[i];
483                 int len = ce_namelen(ce);
484                 if (len < namelen ||
485                     strncmp(ce->name, ce->name, namelen) ||
486                     ce->name[namelen] != '/')
487                         break;
488                 /*
489                  * ce->name is an entry in the subdirectory.
490                  */
491                 if (!ce_stage(ce)) {
492                         if (verify_uptodate(ce, o))
493                                 return -1;
494                         add_entry(o, ce, CE_REMOVE, 0);
495                 }
496                 cnt++;
497         }
498
499         /*
500          * Then we need to make sure that we do not lose a locally
501          * present file that is not ignored.
502          */
503         pathbuf = xmalloc(namelen + 2);
504         memcpy(pathbuf, ce->name, namelen);
505         strcpy(pathbuf+namelen, "/");
506
507         memset(&d, 0, sizeof(d));
508         if (o->dir)
509                 d.exclude_per_dir = o->dir->exclude_per_dir;
510         i = read_directory(&d, ce->name, pathbuf, namelen+1, NULL);
511         if (i)
512                 return o->gently ? -1 :
513                         error("Updating '%s' would lose untracked files in it",
514                               ce->name);
515         free(pathbuf);
516         return cnt;
517 }
518
519 /*
520  * We do not want to remove or overwrite a working tree file that
521  * is not tracked, unless it is ignored.
522  */
523 static int verify_absent(struct cache_entry *ce, const char *action,
524                          struct unpack_trees_options *o)
525 {
526         struct stat st;
527
528         if (o->index_only || o->reset || !o->update)
529                 return 0;
530
531         if (has_symlink_leading_path(ce->name, NULL))
532                 return 0;
533
534         if (!lstat(ce->name, &st)) {
535                 int cnt;
536                 int dtype = ce_to_dtype(ce);
537
538                 if (o->dir && excluded(o->dir, ce->name, &dtype))
539                         /*
540                          * ce->name is explicitly excluded, so it is Ok to
541                          * overwrite it.
542                          */
543                         return 0;
544                 if (S_ISDIR(st.st_mode)) {
545                         /*
546                          * We are checking out path "foo" and
547                          * found "foo/." in the working tree.
548                          * This is tricky -- if we have modified
549                          * files that are in "foo/" we would lose
550                          * it.
551                          */
552                         cnt = verify_clean_subdirectory(ce, action, o);
553
554                         /*
555                          * If this removed entries from the index,
556                          * what that means is:
557                          *
558                          * (1) the caller unpack_trees_rec() saw path/foo
559                          * in the index, and it has not removed it because
560                          * it thinks it is handling 'path' as blob with
561                          * D/F conflict;
562                          * (2) we will return "ok, we placed a merged entry
563                          * in the index" which would cause o->pos to be
564                          * incremented by one;
565                          * (3) however, original o->pos now has 'path/foo'
566                          * marked with "to be removed".
567                          *
568                          * We need to increment it by the number of
569                          * deleted entries here.
570                          */
571                         o->pos += cnt;
572                         return 0;
573                 }
574
575                 /*
576                  * The previous round may already have decided to
577                  * delete this path, which is in a subdirectory that
578                  * is being replaced with a blob.
579                  */
580                 cnt = index_name_pos(&o->result, ce->name, strlen(ce->name));
581                 if (0 <= cnt) {
582                         struct cache_entry *ce = o->result.cache[cnt];
583                         if (ce->ce_flags & CE_REMOVE)
584                                 return 0;
585                 }
586
587                 return o->gently ? -1 :
588                         error("Untracked working tree file '%s' "
589                               "would be %s by merge.", ce->name, action);
590         }
591         return 0;
592 }
593
594 static int merged_entry(struct cache_entry *merge, struct cache_entry *old,
595                 struct unpack_trees_options *o)
596 {
597         if (old) {
598                 /*
599                  * See if we can re-use the old CE directly?
600                  * That way we get the uptodate stat info.
601                  *
602                  * This also removes the UPDATE flag on
603                  * a match.
604                  */
605                 if (same(old, merge)) {
606                         copy_cache_entry(merge, old);
607                 } else {
608                         if (verify_uptodate(old, o))
609                                 return -1;
610                         invalidate_ce_path(old, o);
611                 }
612         }
613         else {
614                 if (verify_absent(merge, "overwritten", o))
615                         return -1;
616                 invalidate_ce_path(merge, o);
617         }
618
619         add_entry(o, merge, CE_UPDATE, CE_STAGEMASK);
620         return 1;
621 }
622
623 static int deleted_entry(struct cache_entry *ce, struct cache_entry *old,
624                 struct unpack_trees_options *o)
625 {
626         /* Did it exist in the index? */
627         if (!old) {
628                 if (verify_absent(ce, "removed", o))
629                         return -1;
630                 return 0;
631         }
632         if (verify_uptodate(old, o))
633                 return -1;
634         add_entry(o, ce, CE_REMOVE, 0);
635         invalidate_ce_path(ce, o);
636         return 1;
637 }
638
639 static int keep_entry(struct cache_entry *ce, struct unpack_trees_options *o)
640 {
641         add_entry(o, ce, 0, 0);
642         return 1;
643 }
644
645 #if DBRT_DEBUG
646 static void show_stage_entry(FILE *o,
647                              const char *label, const struct cache_entry *ce)
648 {
649         if (!ce)
650                 fprintf(o, "%s (missing)\n", label);
651         else
652                 fprintf(o, "%s%06o %s %d\t%s\n",
653                         label,
654                         ce->ce_mode,
655                         sha1_to_hex(ce->sha1),
656                         ce_stage(ce),
657                         ce->name);
658 }
659 #endif
660
661 int threeway_merge(struct cache_entry **stages, struct unpack_trees_options *o)
662 {
663         struct cache_entry *index;
664         struct cache_entry *head;
665         struct cache_entry *remote = stages[o->head_idx + 1];
666         int count;
667         int head_match = 0;
668         int remote_match = 0;
669
670         int df_conflict_head = 0;
671         int df_conflict_remote = 0;
672
673         int any_anc_missing = 0;
674         int no_anc_exists = 1;
675         int i;
676
677         for (i = 1; i < o->head_idx; i++) {
678                 if (!stages[i] || stages[i] == o->df_conflict_entry)
679                         any_anc_missing = 1;
680                 else
681                         no_anc_exists = 0;
682         }
683
684         index = stages[0];
685         head = stages[o->head_idx];
686
687         if (head == o->df_conflict_entry) {
688                 df_conflict_head = 1;
689                 head = NULL;
690         }
691
692         if (remote == o->df_conflict_entry) {
693                 df_conflict_remote = 1;
694                 remote = NULL;
695         }
696
697         /* First, if there's a #16 situation, note that to prevent #13
698          * and #14.
699          */
700         if (!same(remote, head)) {
701                 for (i = 1; i < o->head_idx; i++) {
702                         if (same(stages[i], head)) {
703                                 head_match = i;
704                         }
705                         if (same(stages[i], remote)) {
706                                 remote_match = i;
707                         }
708                 }
709         }
710
711         /* We start with cases where the index is allowed to match
712          * something other than the head: #14(ALT) and #2ALT, where it
713          * is permitted to match the result instead.
714          */
715         /* #14, #14ALT, #2ALT */
716         if (remote && !df_conflict_head && head_match && !remote_match) {
717                 if (index && !same(index, remote) && !same(index, head))
718                         return o->gently ? -1 : reject_merge(index);
719                 return merged_entry(remote, index, o);
720         }
721         /*
722          * If we have an entry in the index cache, then we want to
723          * make sure that it matches head.
724          */
725         if (index && !same(index, head))
726                 return o->gently ? -1 : reject_merge(index);
727
728         if (head) {
729                 /* #5ALT, #15 */
730                 if (same(head, remote))
731                         return merged_entry(head, index, o);
732                 /* #13, #3ALT */
733                 if (!df_conflict_remote && remote_match && !head_match)
734                         return merged_entry(head, index, o);
735         }
736
737         /* #1 */
738         if (!head && !remote && any_anc_missing)
739                 return 0;
740
741         /* Under the new "aggressive" rule, we resolve mostly trivial
742          * cases that we historically had git-merge-one-file resolve.
743          */
744         if (o->aggressive) {
745                 int head_deleted = !head && !df_conflict_head;
746                 int remote_deleted = !remote && !df_conflict_remote;
747                 struct cache_entry *ce = NULL;
748
749                 if (index)
750                         ce = index;
751                 else if (head)
752                         ce = head;
753                 else if (remote)
754                         ce = remote;
755                 else {
756                         for (i = 1; i < o->head_idx; i++) {
757                                 if (stages[i] && stages[i] != o->df_conflict_entry) {
758                                         ce = stages[i];
759                                         break;
760                                 }
761                         }
762                 }
763
764                 /*
765                  * Deleted in both.
766                  * Deleted in one and unchanged in the other.
767                  */
768                 if ((head_deleted && remote_deleted) ||
769                     (head_deleted && remote && remote_match) ||
770                     (remote_deleted && head && head_match)) {
771                         if (index)
772                                 return deleted_entry(index, index, o);
773                         if (ce && !head_deleted) {
774                                 if (verify_absent(ce, "removed", o))
775                                         return -1;
776                         }
777                         return 0;
778                 }
779                 /*
780                  * Added in both, identically.
781                  */
782                 if (no_anc_exists && head && remote && same(head, remote))
783                         return merged_entry(head, index, o);
784
785         }
786
787         /* Below are "no merge" cases, which require that the index be
788          * up-to-date to avoid the files getting overwritten with
789          * conflict resolution files.
790          */
791         if (index) {
792                 if (verify_uptodate(index, o))
793                         return -1;
794         }
795
796         o->nontrivial_merge = 1;
797
798         /* #2, #3, #4, #6, #7, #9, #10, #11. */
799         count = 0;
800         if (!head_match || !remote_match) {
801                 for (i = 1; i < o->head_idx; i++) {
802                         if (stages[i] && stages[i] != o->df_conflict_entry) {
803                                 keep_entry(stages[i], o);
804                                 count++;
805                                 break;
806                         }
807                 }
808         }
809 #if DBRT_DEBUG
810         else {
811                 fprintf(stderr, "read-tree: warning #16 detected\n");
812                 show_stage_entry(stderr, "head   ", stages[head_match]);
813                 show_stage_entry(stderr, "remote ", stages[remote_match]);
814         }
815 #endif
816         if (head) { count += keep_entry(head, o); }
817         if (remote) { count += keep_entry(remote, o); }
818         return count;
819 }
820
821 /*
822  * Two-way merge.
823  *
824  * The rule is to "carry forward" what is in the index without losing
825  * information across a "fast forward", favoring a successful merge
826  * over a merge failure when it makes sense.  For details of the
827  * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
828  *
829  */
830 int twoway_merge(struct cache_entry **src, struct unpack_trees_options *o)
831 {
832         struct cache_entry *current = src[0];
833         struct cache_entry *oldtree = src[1];
834         struct cache_entry *newtree = src[2];
835
836         if (o->merge_size != 2)
837                 return error("Cannot do a twoway merge of %d trees",
838                              o->merge_size);
839
840         if (oldtree == o->df_conflict_entry)
841                 oldtree = NULL;
842         if (newtree == o->df_conflict_entry)
843                 newtree = NULL;
844
845         if (current) {
846                 if ((!oldtree && !newtree) || /* 4 and 5 */
847                     (!oldtree && newtree &&
848                      same(current, newtree)) || /* 6 and 7 */
849                     (oldtree && newtree &&
850                      same(oldtree, newtree)) || /* 14 and 15 */
851                     (oldtree && newtree &&
852                      !same(oldtree, newtree) && /* 18 and 19 */
853                      same(current, newtree))) {
854                         return keep_entry(current, o);
855                 }
856                 else if (oldtree && !newtree && same(current, oldtree)) {
857                         /* 10 or 11 */
858                         return deleted_entry(oldtree, current, o);
859                 }
860                 else if (oldtree && newtree &&
861                          same(current, oldtree) && !same(current, newtree)) {
862                         /* 20 or 21 */
863                         return merged_entry(newtree, current, o);
864                 }
865                 else {
866                         /* all other failures */
867                         if (oldtree)
868                                 return o->gently ? -1 : reject_merge(oldtree);
869                         if (current)
870                                 return o->gently ? -1 : reject_merge(current);
871                         if (newtree)
872                                 return o->gently ? -1 : reject_merge(newtree);
873                         return -1;
874                 }
875         }
876         else if (newtree)
877                 return merged_entry(newtree, current, o);
878         return deleted_entry(oldtree, current, o);
879 }
880
881 /*
882  * Bind merge.
883  *
884  * Keep the index entries at stage0, collapse stage1 but make sure
885  * stage0 does not have anything there.
886  */
887 int bind_merge(struct cache_entry **src,
888                 struct unpack_trees_options *o)
889 {
890         struct cache_entry *old = src[0];
891         struct cache_entry *a = src[1];
892
893         if (o->merge_size != 1)
894                 return error("Cannot do a bind merge of %d trees\n",
895                              o->merge_size);
896         if (a && old)
897                 return o->gently ? -1 :
898                         error("Entry '%s' overlaps with '%s'.  Cannot bind.", a->name, old->name);
899         if (!a)
900                 return keep_entry(old, o);
901         else
902                 return merged_entry(a, NULL, o);
903 }
904
905 /*
906  * One-way merge.
907  *
908  * The rule is:
909  * - take the stat information from stage0, take the data from stage1
910  */
911 int oneway_merge(struct cache_entry **src, struct unpack_trees_options *o)
912 {
913         struct cache_entry *old = src[0];
914         struct cache_entry *a = src[1];
915
916         if (o->merge_size != 1)
917                 return error("Cannot do a oneway merge of %d trees",
918                              o->merge_size);
919
920         if (!a)
921                 return deleted_entry(old, old, o);
922
923         if (old && same(old, a)) {
924                 int update = 0;
925                 if (o->reset) {
926                         struct stat st;
927                         if (lstat(old->name, &st) ||
928                             ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID))
929                                 update |= CE_UPDATE;
930                 }
931                 add_entry(o, old, update, 0);
932                 return 0;
933         }
934         return merged_entry(a, old, o);
935 }