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