read-tree --debug-unpack
[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 #include "attr.h"
11
12 /*
13  * Error messages expected by scripts out of plumbing commands such as
14  * read-tree.  Non-scripted Porcelain is not required to use these messages
15  * and in fact are encouraged to reword them to better suit their particular
16  * situation better.  See how "git checkout" replaces not_uptodate_file to
17  * explain why it does not allow switching between branches when you have
18  * local changes, for example.
19  */
20 static struct unpack_trees_error_msgs unpack_plumbing_errors = {
21         /* would_overwrite */
22         "Entry '%s' would be overwritten by merge. Cannot merge.",
23
24         /* not_uptodate_file */
25         "Entry '%s' not uptodate. Cannot merge.",
26
27         /* not_uptodate_dir */
28         "Updating '%s' would lose untracked files in it",
29
30         /* would_lose_untracked */
31         "Untracked working tree file '%s' would be %s by merge.",
32
33         /* bind_overlap */
34         "Entry '%s' overlaps with '%s'.  Cannot bind.",
35 };
36
37 #define ERRORMSG(o,fld) \
38         ( ((o) && (o)->msgs.fld) \
39         ? ((o)->msgs.fld) \
40         : (unpack_plumbing_errors.fld) )
41
42 static void add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
43         unsigned int set, unsigned int clear)
44 {
45         unsigned int size = ce_size(ce);
46         struct cache_entry *new = xmalloc(size);
47
48         clear |= CE_HASHED | CE_UNHASHED;
49
50         memcpy(new, ce, size);
51         new->next = NULL;
52         new->ce_flags = (new->ce_flags & ~clear) | set;
53         add_index_entry(&o->result, new, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
54 }
55
56 /*
57  * Unlink the last component and schedule the leading directories for
58  * removal, such that empty directories get removed.
59  */
60 static void unlink_entry(struct cache_entry *ce)
61 {
62         if (has_symlink_or_noent_leading_path(ce->name, ce_namelen(ce)))
63                 return;
64         if (unlink_or_warn(ce->name))
65                 return;
66         schedule_dir_for_removal(ce->name, ce_namelen(ce));
67 }
68
69 static struct checkout state;
70 static int check_updates(struct unpack_trees_options *o)
71 {
72         unsigned cnt = 0, total = 0;
73         struct progress *progress = NULL;
74         struct index_state *index = &o->result;
75         int i;
76         int errs = 0;
77
78         if (o->update && o->verbose_update) {
79                 for (total = cnt = 0; cnt < index->cache_nr; cnt++) {
80                         struct cache_entry *ce = index->cache[cnt];
81                         if (ce->ce_flags & (CE_UPDATE | CE_REMOVE))
82                                 total++;
83                 }
84
85                 progress = start_progress_delay("Checking out files",
86                                                 total, 50, 1);
87                 cnt = 0;
88         }
89
90         if (o->update)
91                 git_attr_set_direction(GIT_ATTR_CHECKOUT, &o->result);
92         for (i = 0; i < index->cache_nr; i++) {
93                 struct cache_entry *ce = index->cache[i];
94
95                 if (ce->ce_flags & CE_REMOVE) {
96                         display_progress(progress, ++cnt);
97                         if (o->update)
98                                 unlink_entry(ce);
99                 }
100         }
101         remove_marked_cache_entries(&o->result);
102         remove_scheduled_dirs();
103
104         for (i = 0; i < index->cache_nr; i++) {
105                 struct cache_entry *ce = index->cache[i];
106
107                 if (ce->ce_flags & CE_UPDATE) {
108                         display_progress(progress, ++cnt);
109                         ce->ce_flags &= ~CE_UPDATE;
110                         if (o->update) {
111                                 errs |= checkout_entry(ce, &state, NULL);
112                         }
113                 }
114         }
115         stop_progress(&progress);
116         if (o->update)
117                 git_attr_set_direction(GIT_ATTR_CHECKIN, NULL);
118         return errs != 0;
119 }
120
121 static inline int call_unpack_fn(struct cache_entry **src, struct unpack_trees_options *o)
122 {
123         int ret = o->fn(src, o);
124         if (ret > 0)
125                 ret = 0;
126         return ret;
127 }
128
129 static void mark_ce_used(struct cache_entry *ce, struct unpack_trees_options *o)
130 {
131         ce->ce_flags |= CE_UNPACKED;
132
133         if (o->cache_bottom < o->src_index->cache_nr &&
134             o->src_index->cache[o->cache_bottom] == ce) {
135                 int bottom = o->cache_bottom;
136                 while (bottom < o->src_index->cache_nr &&
137                        o->src_index->cache[bottom]->ce_flags & CE_UNPACKED)
138                         bottom++;
139                 o->cache_bottom = bottom;
140         }
141 }
142
143 static void mark_all_ce_unused(struct index_state *index)
144 {
145         int i;
146         for (i = 0; i < index->cache_nr; i++)
147                 index->cache[i]->ce_flags &= ~CE_UNPACKED;
148 }
149
150 static int locate_in_src_index(struct cache_entry *ce,
151                                struct unpack_trees_options *o)
152 {
153         struct index_state *index = o->src_index;
154         int len = ce_namelen(ce);
155         int pos = index_name_pos(index, ce->name, len);
156         if (pos < 0)
157                 pos = -1 - pos;
158         return pos;
159 }
160
161 /*
162  * We call unpack_index_entry() with an unmerged cache entry
163  * only in diff-index, and it wants a single callback.  Skip
164  * the other unmerged entry with the same name.
165  */
166 static void mark_ce_used_same_name(struct cache_entry *ce,
167                                    struct unpack_trees_options *o)
168 {
169         struct index_state *index = o->src_index;
170         int len = ce_namelen(ce);
171         int pos;
172
173         for (pos = locate_in_src_index(ce, o); pos < index->cache_nr; pos++) {
174                 struct cache_entry *next = index->cache[pos];
175                 if (len != ce_namelen(next) ||
176                     memcmp(ce->name, next->name, len))
177                         break;
178                 mark_ce_used(next, o);
179         }
180 }
181
182 static struct cache_entry *next_cache_entry(struct unpack_trees_options *o)
183 {
184         const struct index_state *index = o->src_index;
185         int pos = o->cache_bottom;
186
187         while (pos < index->cache_nr) {
188                 struct cache_entry *ce = index->cache[pos];
189                 if (!(ce->ce_flags & CE_UNPACKED))
190                         return ce;
191                 pos++;
192         }
193         return NULL;
194 }
195
196 static void add_same_unmerged(struct cache_entry *ce,
197                               struct unpack_trees_options *o)
198 {
199         struct index_state *index = o->src_index;
200         int len = ce_namelen(ce);
201         int pos = index_name_pos(index, ce->name, len);
202
203         if (0 <= pos)
204                 die("programming error in a caller of mark_ce_used_same_name");
205         for (pos = -pos - 1; pos < index->cache_nr; pos++) {
206                 struct cache_entry *next = index->cache[pos];
207                 if (len != ce_namelen(next) ||
208                     memcmp(ce->name, next->name, len))
209                         break;
210                 add_entry(o, next, 0, 0);
211                 mark_ce_used(next, o);
212         }
213 }
214
215 static int unpack_index_entry(struct cache_entry *ce,
216                               struct unpack_trees_options *o)
217 {
218         struct cache_entry *src[5] = { ce, NULL, };
219         int ret;
220
221         mark_ce_used(ce, o);
222         if (ce_stage(ce)) {
223                 if (o->skip_unmerged) {
224                         add_entry(o, ce, 0, 0);
225                         return 0;
226                 }
227         }
228         ret = call_unpack_fn(src, o);
229         if (ce_stage(ce))
230                 mark_ce_used_same_name(ce, o);
231         return ret;
232 }
233
234 static int find_cache_pos(struct traverse_info *, const struct name_entry *);
235
236 static void restore_cache_bottom(struct traverse_info *info, int bottom)
237 {
238         struct unpack_trees_options *o = info->data;
239
240         if (o->diff_index_cached)
241                 return;
242         o->cache_bottom = bottom;
243 }
244
245 static int switch_cache_bottom(struct traverse_info *info)
246 {
247         struct unpack_trees_options *o = info->data;
248         int ret, pos;
249
250         if (o->diff_index_cached)
251                 return 0;
252         ret = o->cache_bottom;
253         pos = find_cache_pos(info->prev, &info->name);
254
255         if (pos < -1)
256                 o->cache_bottom = -2 - pos;
257         else if (pos < 0)
258                 o->cache_bottom = o->src_index->cache_nr;
259         return ret;
260 }
261
262 static int traverse_trees_recursive(int n, unsigned long dirmask, unsigned long df_conflicts, struct name_entry *names, struct traverse_info *info)
263 {
264         int i, ret, bottom;
265         struct tree_desc t[MAX_UNPACK_TREES];
266         struct traverse_info newinfo;
267         struct name_entry *p;
268
269         p = names;
270         while (!p->mode)
271                 p++;
272
273         newinfo = *info;
274         newinfo.prev = info;
275         newinfo.name = *p;
276         newinfo.pathlen += tree_entry_len(p->path, p->sha1) + 1;
277         newinfo.conflicts |= df_conflicts;
278
279         for (i = 0; i < n; i++, dirmask >>= 1) {
280                 const unsigned char *sha1 = NULL;
281                 if (dirmask & 1)
282                         sha1 = names[i].sha1;
283                 fill_tree_descriptor(t+i, sha1);
284         }
285
286         bottom = switch_cache_bottom(&newinfo);
287         ret = traverse_trees(n, t, &newinfo);
288         restore_cache_bottom(&newinfo, bottom);
289         return ret;
290 }
291
292 /*
293  * Compare the traverse-path to the cache entry without actually
294  * having to generate the textual representation of the traverse
295  * path.
296  *
297  * NOTE! This *only* compares up to the size of the traverse path
298  * itself - the caller needs to do the final check for the cache
299  * entry having more data at the end!
300  */
301 static int do_compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
302 {
303         int len, pathlen, ce_len;
304         const char *ce_name;
305
306         if (info->prev) {
307                 int cmp = do_compare_entry(ce, info->prev, &info->name);
308                 if (cmp)
309                         return cmp;
310         }
311         pathlen = info->pathlen;
312         ce_len = ce_namelen(ce);
313
314         /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
315         if (ce_len < pathlen)
316                 return -1;
317
318         ce_len -= pathlen;
319         ce_name = ce->name + pathlen;
320
321         len = tree_entry_len(n->path, n->sha1);
322         return df_name_compare(ce_name, ce_len, S_IFREG, n->path, len, n->mode);
323 }
324
325 static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
326 {
327         int cmp = do_compare_entry(ce, info, n);
328         if (cmp)
329                 return cmp;
330
331         /*
332          * Even if the beginning compared identically, the ce should
333          * compare as bigger than a directory leading up to it!
334          */
335         return ce_namelen(ce) > traverse_path_len(info, n);
336 }
337
338 static int ce_in_traverse_path(const struct cache_entry *ce,
339                                const struct traverse_info *info)
340 {
341         if (!info->prev)
342                 return 1;
343         if (do_compare_entry(ce, info->prev, &info->name))
344                 return 0;
345         /*
346          * If ce (blob) is the same name as the path (which is a tree
347          * we will be descending into), it won't be inside it.
348          */
349         return (info->pathlen < ce_namelen(ce));
350 }
351
352 static struct cache_entry *create_ce_entry(const struct traverse_info *info, const struct name_entry *n, int stage)
353 {
354         int len = traverse_path_len(info, n);
355         struct cache_entry *ce = xcalloc(1, cache_entry_size(len));
356
357         ce->ce_mode = create_ce_mode(n->mode);
358         ce->ce_flags = create_ce_flags(len, stage);
359         hashcpy(ce->sha1, n->sha1);
360         make_traverse_path(ce->name, info, n);
361
362         return ce;
363 }
364
365 static int unpack_nondirectories(int n, unsigned long mask,
366                                  unsigned long dirmask,
367                                  struct cache_entry **src,
368                                  const struct name_entry *names,
369                                  const struct traverse_info *info)
370 {
371         int i;
372         struct unpack_trees_options *o = info->data;
373         unsigned long conflicts;
374
375         /* Do we have *only* directories? Nothing to do */
376         if (mask == dirmask && !src[0])
377                 return 0;
378
379         conflicts = info->conflicts;
380         if (o->merge)
381                 conflicts >>= 1;
382         conflicts |= dirmask;
383
384         /*
385          * Ok, we've filled in up to any potential index entry in src[0],
386          * now do the rest.
387          */
388         for (i = 0; i < n; i++) {
389                 int stage;
390                 unsigned int bit = 1ul << i;
391                 if (conflicts & bit) {
392                         src[i + o->merge] = o->df_conflict_entry;
393                         continue;
394                 }
395                 if (!(mask & bit))
396                         continue;
397                 if (!o->merge)
398                         stage = 0;
399                 else if (i + 1 < o->head_idx)
400                         stage = 1;
401                 else if (i + 1 > o->head_idx)
402                         stage = 3;
403                 else
404                         stage = 2;
405                 src[i + o->merge] = create_ce_entry(info, names + i, stage);
406         }
407
408         if (o->merge)
409                 return call_unpack_fn(src, o);
410
411         for (i = 0; i < n; i++)
412                 if (src[i] && src[i] != o->df_conflict_entry)
413                         add_entry(o, src[i], 0, 0);
414         return 0;
415 }
416
417 static int unpack_failed(struct unpack_trees_options *o, const char *message)
418 {
419         discard_index(&o->result);
420         if (!o->gently) {
421                 if (message)
422                         return error("%s", message);
423                 return -1;
424         }
425         return -1;
426 }
427
428 /* NEEDSWORK: give this a better name and share with tree-walk.c */
429 static int name_compare(const char *a, int a_len,
430                         const char *b, int b_len)
431 {
432         int len = (a_len < b_len) ? a_len : b_len;
433         int cmp = memcmp(a, b, len);
434         if (cmp)
435                 return cmp;
436         return (a_len - b_len);
437 }
438
439 /*
440  * The tree traversal is looking at name p.  If we have a matching entry,
441  * return it.  If name p is a directory in the index, do not return
442  * anything, as we will want to match it when the traversal descends into
443  * the directory.
444  */
445 static int find_cache_pos(struct traverse_info *info,
446                           const struct name_entry *p)
447 {
448         int pos;
449         struct unpack_trees_options *o = info->data;
450         struct index_state *index = o->src_index;
451         int pfxlen = info->pathlen;
452         int p_len = tree_entry_len(p->path, p->sha1);
453
454         for (pos = o->cache_bottom; pos < index->cache_nr; pos++) {
455                 struct cache_entry *ce = index->cache[pos];
456                 const char *ce_name, *ce_slash;
457                 int cmp, ce_len;
458
459                 if (!ce_in_traverse_path(ce, info))
460                         continue;
461                 if (ce->ce_flags & CE_UNPACKED)
462                         continue;
463                 ce_name = ce->name + pfxlen;
464                 ce_slash = strchr(ce_name, '/');
465                 if (ce_slash)
466                         ce_len = ce_slash - ce_name;
467                 else
468                         ce_len = ce_namelen(ce) - pfxlen;
469                 cmp = name_compare(p->path, p_len, ce_name, ce_len);
470                 /*
471                  * Exact match; if we have a directory we need to
472                  * delay returning it.
473                  */
474                 if (!cmp)
475                         return ce_slash ? -2 - pos : pos;
476                 if (0 < cmp)
477                         continue; /* keep looking */
478                 /*
479                  * ce_name sorts after p->path; could it be that we
480                  * have files under p->path directory in the index?
481                  * E.g.  ce_name == "t-i", and p->path == "t"; we may
482                  * have "t/a" in the index.
483                  */
484                 if (p_len < ce_len && !memcmp(ce_name, p->path, p_len) &&
485                     ce_name[p_len] < '/')
486                         continue; /* keep looking */
487                 break;
488         }
489         return -1;
490 }
491
492 static struct cache_entry *find_cache_entry(struct traverse_info *info,
493                                             const struct name_entry *p)
494 {
495         int pos = find_cache_pos(info, p);
496         struct unpack_trees_options *o = info->data;
497
498         if (pos == -1)
499                 return next_cache_entry(o);
500         else if (0 <= pos)
501                 return o->src_index->cache[pos];
502         else
503                 return NULL;
504 }
505
506 static void debug_path(struct traverse_info *info)
507 {
508         if (info->prev) {
509                 debug_path(info->prev);
510                 if (*info->prev->name.path)
511                         putchar('/');
512         }
513         printf("%s", info->name.path);
514 }
515
516 static void debug_name_entry(int i, struct name_entry *n)
517 {
518         printf("ent#%d %06o %s\n", i,
519                n->path ? n->mode : 0,
520                n->path ? n->path : "(missing)");
521 }
522
523 static void debug_unpack_callback(int n,
524                                   unsigned long mask,
525                                   unsigned long dirmask,
526                                   struct name_entry *names,
527                                   struct traverse_info *info)
528 {
529         int i;
530         printf("* unpack mask %lu, dirmask %lu, cnt %d ",
531                mask, dirmask, n);
532         debug_path(info);
533         putchar('\n');
534         for (i = 0; i < n; i++)
535                 debug_name_entry(i, names + i);
536 }
537
538 static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
539 {
540         struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
541         struct unpack_trees_options *o = info->data;
542         const struct name_entry *p = names;
543
544         /* Find first entry with a real name (we could use "mask" too) */
545         while (!p->mode)
546                 p++;
547
548         if (o->debug_unpack)
549                 debug_unpack_callback(n, mask, dirmask, names, info);
550
551         /* Are we supposed to look at the index too? */
552         if (o->merge) {
553                 while (1) {
554                         int cmp;
555                         struct cache_entry *ce;
556
557                         if (o->diff_index_cached)
558                                 ce = next_cache_entry(o);
559                         else
560                                 ce = find_cache_entry(info, p);
561
562                         if (!ce)
563                                 break;
564                         cmp = compare_entry(ce, info, p);
565                         if (cmp < 0) {
566                                 if (unpack_index_entry(ce, o) < 0)
567                                         return unpack_failed(o, NULL);
568                                 continue;
569                         }
570                         if (!cmp) {
571                                 if (ce_stage(ce)) {
572                                         /*
573                                          * If we skip unmerged index
574                                          * entries, we'll skip this
575                                          * entry *and* the tree
576                                          * entries associated with it!
577                                          */
578                                         if (o->skip_unmerged) {
579                                                 add_same_unmerged(ce, o);
580                                                 return mask;
581                                         }
582                                 }
583                                 src[0] = ce;
584                         }
585                         break;
586                 }
587         }
588
589         if (unpack_nondirectories(n, mask, dirmask, src, names, info) < 0)
590                 return -1;
591
592         if (src[0]) {
593                 if (ce_stage(src[0]))
594                         mark_ce_used_same_name(src[0], o);
595                 else
596                         mark_ce_used(src[0], o);
597         }
598
599         /* Now handle any directories.. */
600         if (dirmask) {
601                 unsigned long conflicts = mask & ~dirmask;
602                 if (o->merge) {
603                         conflicts <<= 1;
604                         if (src[0])
605                                 conflicts |= 1;
606                 }
607
608                 /* special case: "diff-index --cached" looking at a tree */
609                 if (o->diff_index_cached &&
610                     n == 1 && dirmask == 1 && S_ISDIR(names->mode)) {
611                         int matches;
612                         matches = cache_tree_matches_traversal(o->src_index->cache_tree,
613                                                                names, info);
614                         /*
615                          * Everything under the name matches; skip the
616                          * entire hierarchy.  diff_index_cached codepath
617                          * special cases D/F conflicts in such a way that
618                          * it does not do any look-ahead, so this is safe.
619                          */
620                         if (matches) {
621                                 o->cache_bottom += matches;
622                                 return mask;
623                         }
624                 }
625
626                 if (traverse_trees_recursive(n, dirmask, conflicts,
627                                              names, info) < 0)
628                         return -1;
629                 return mask;
630         }
631
632         return mask;
633 }
634
635 /*
636  * N-way merge "len" trees.  Returns 0 on success, -1 on failure to manipulate the
637  * resulting index, -2 on failure to reflect the changes to the work tree.
638  */
639 int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
640 {
641         int ret;
642         static struct cache_entry *dfc;
643
644         if (len > MAX_UNPACK_TREES)
645                 die("unpack_trees takes at most %d trees", MAX_UNPACK_TREES);
646         memset(&state, 0, sizeof(state));
647         state.base_dir = "";
648         state.force = 1;
649         state.quiet = 1;
650         state.refresh_cache = 1;
651
652         memset(&o->result, 0, sizeof(o->result));
653         o->result.initialized = 1;
654         if (o->src_index) {
655                 o->result.timestamp.sec = o->src_index->timestamp.sec;
656                 o->result.timestamp.nsec = o->src_index->timestamp.nsec;
657         }
658         o->merge_size = len;
659
660         if (!dfc)
661                 dfc = xcalloc(1, cache_entry_size(0));
662         o->df_conflict_entry = dfc;
663
664         if (len) {
665                 const char *prefix = o->prefix ? o->prefix : "";
666                 struct traverse_info info;
667
668                 setup_traverse_info(&info, prefix);
669                 info.fn = unpack_callback;
670                 info.data = o;
671
672                 if (o->prefix) {
673                         /*
674                          * Unpack existing index entries that sort before the
675                          * prefix the tree is spliced into.  Note that o->merge
676                          * is always true in this case.
677                          */
678                         while (1) {
679                                 struct cache_entry *ce = next_cache_entry(o);
680                                 if (!ce)
681                                         break;
682                                 if (ce_in_traverse_path(ce, &info))
683                                         break;
684                                 if (unpack_index_entry(ce, o) < 0)
685                                         return unpack_failed(o, NULL);
686                         }
687                 }
688
689                 if (traverse_trees(len, t, &info) < 0)
690                         return unpack_failed(o, NULL);
691         }
692
693         /* Any left-over entries in the index? */
694         if (o->merge) {
695                 while (1) {
696                         struct cache_entry *ce = next_cache_entry(o);
697                         if (!ce)
698                                 break;
699                         if (unpack_index_entry(ce, o) < 0)
700                                 return unpack_failed(o, NULL);
701                 }
702         }
703
704         if (o->trivial_merges_only && o->nontrivial_merge)
705                 return unpack_failed(o, "Merge requires file-level merging");
706
707         /*
708          * some callers, most notably "git status -v" runs unpack_trees()
709          * multiple times; clean everything up after us.
710          */
711         mark_all_ce_unused(o->src_index);
712
713         o->src_index = NULL;
714         ret = check_updates(o) ? (-2) : 0;
715         if (o->dst_index)
716                 *o->dst_index = o->result;
717         return ret;
718 }
719
720 /* Here come the merge functions */
721
722 static int reject_merge(struct cache_entry *ce, struct unpack_trees_options *o)
723 {
724         return error(ERRORMSG(o, would_overwrite), ce->name);
725 }
726
727 static int same(struct cache_entry *a, struct cache_entry *b)
728 {
729         if (!!a != !!b)
730                 return 0;
731         if (!a && !b)
732                 return 1;
733         return a->ce_mode == b->ce_mode &&
734                !hashcmp(a->sha1, b->sha1);
735 }
736
737
738 /*
739  * When a CE gets turned into an unmerged entry, we
740  * want it to be up-to-date
741  */
742 static int verify_uptodate(struct cache_entry *ce,
743                 struct unpack_trees_options *o)
744 {
745         struct stat st;
746
747         if (o->index_only || o->reset || ce_uptodate(ce))
748                 return 0;
749
750         if (!lstat(ce->name, &st)) {
751                 unsigned changed = ie_match_stat(o->src_index, ce, &st, CE_MATCH_IGNORE_VALID);
752                 if (!changed)
753                         return 0;
754                 /*
755                  * NEEDSWORK: the current default policy is to allow
756                  * submodule to be out of sync wrt the supermodule
757                  * index.  This needs to be tightened later for
758                  * submodules that are marked to be automatically
759                  * checked out.
760                  */
761                 if (S_ISGITLINK(ce->ce_mode))
762                         return 0;
763                 errno = 0;
764         }
765         if (errno == ENOENT)
766                 return 0;
767         return o->gently ? -1 :
768                 error(ERRORMSG(o, not_uptodate_file), ce->name);
769 }
770
771 static void invalidate_ce_path(struct cache_entry *ce, struct unpack_trees_options *o)
772 {
773         if (ce)
774                 cache_tree_invalidate_path(o->src_index->cache_tree, ce->name);
775 }
776
777 /*
778  * Check that checking out ce->sha1 in subdir ce->name is not
779  * going to overwrite any working files.
780  *
781  * Currently, git does not checkout subprojects during a superproject
782  * checkout, so it is not going to overwrite anything.
783  */
784 static int verify_clean_submodule(struct cache_entry *ce, const char *action,
785                                       struct unpack_trees_options *o)
786 {
787         return 0;
788 }
789
790 static int verify_clean_subdirectory(struct cache_entry *ce, const char *action,
791                                       struct unpack_trees_options *o)
792 {
793         /*
794          * we are about to extract "ce->name"; we would not want to lose
795          * anything in the existing directory there.
796          */
797         int namelen;
798         int i;
799         struct dir_struct d;
800         char *pathbuf;
801         int cnt = 0;
802         unsigned char sha1[20];
803
804         if (S_ISGITLINK(ce->ce_mode) &&
805             resolve_gitlink_ref(ce->name, "HEAD", sha1) == 0) {
806                 /* If we are not going to update the submodule, then
807                  * we don't care.
808                  */
809                 if (!hashcmp(sha1, ce->sha1))
810                         return 0;
811                 return verify_clean_submodule(ce, action, o);
812         }
813
814         /*
815          * First let's make sure we do not have a local modification
816          * in that directory.
817          */
818         namelen = strlen(ce->name);
819         for (i = locate_in_src_index(ce, o);
820              i < o->src_index->cache_nr;
821              i++) {
822                 struct cache_entry *ce2 = o->src_index->cache[i];
823                 int len = ce_namelen(ce2);
824                 if (len < namelen ||
825                     strncmp(ce->name, ce2->name, namelen) ||
826                     ce2->name[namelen] != '/')
827                         break;
828                 /*
829                  * ce2->name is an entry in the subdirectory to be
830                  * removed.
831                  */
832                 if (!ce_stage(ce2)) {
833                         if (verify_uptodate(ce2, o))
834                                 return -1;
835                         add_entry(o, ce2, CE_REMOVE, 0);
836                         mark_ce_used(ce2, o);
837                 }
838                 cnt++;
839         }
840
841         /*
842          * Then we need to make sure that we do not lose a locally
843          * present file that is not ignored.
844          */
845         pathbuf = xmalloc(namelen + 2);
846         memcpy(pathbuf, ce->name, namelen);
847         strcpy(pathbuf+namelen, "/");
848
849         memset(&d, 0, sizeof(d));
850         if (o->dir)
851                 d.exclude_per_dir = o->dir->exclude_per_dir;
852         i = read_directory(&d, pathbuf, namelen+1, NULL);
853         if (i)
854                 return o->gently ? -1 :
855                         error(ERRORMSG(o, not_uptodate_dir), ce->name);
856         free(pathbuf);
857         return cnt;
858 }
859
860 /*
861  * This gets called when there was no index entry for the tree entry 'dst',
862  * but we found a file in the working tree that 'lstat()' said was fine,
863  * and we're on a case-insensitive filesystem.
864  *
865  * See if we can find a case-insensitive match in the index that also
866  * matches the stat information, and assume it's that other file!
867  */
868 static int icase_exists(struct unpack_trees_options *o, struct cache_entry *dst, struct stat *st)
869 {
870         struct cache_entry *src;
871
872         src = index_name_exists(o->src_index, dst->name, ce_namelen(dst), 1);
873         return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID);
874 }
875
876 /*
877  * We do not want to remove or overwrite a working tree file that
878  * is not tracked, unless it is ignored.
879  */
880 static int verify_absent(struct cache_entry *ce, const char *action,
881                          struct unpack_trees_options *o)
882 {
883         struct stat st;
884
885         if (o->index_only || o->reset || !o->update)
886                 return 0;
887
888         if (has_symlink_or_noent_leading_path(ce->name, ce_namelen(ce)))
889                 return 0;
890
891         if (!lstat(ce->name, &st)) {
892                 int dtype = ce_to_dtype(ce);
893                 struct cache_entry *result;
894
895                 /*
896                  * It may be that the 'lstat()' succeeded even though
897                  * target 'ce' was absent, because there is an old
898                  * entry that is different only in case..
899                  *
900                  * Ignore that lstat() if it matches.
901                  */
902                 if (ignore_case && icase_exists(o, ce, &st))
903                         return 0;
904
905                 if (o->dir && excluded(o->dir, ce->name, &dtype))
906                         /*
907                          * ce->name is explicitly excluded, so it is Ok to
908                          * overwrite it.
909                          */
910                         return 0;
911                 if (S_ISDIR(st.st_mode)) {
912                         /*
913                          * We are checking out path "foo" and
914                          * found "foo/." in the working tree.
915                          * This is tricky -- if we have modified
916                          * files that are in "foo/" we would lose
917                          * them.
918                          */
919                         if (verify_clean_subdirectory(ce, action, o) < 0)
920                                 return -1;
921                         return 0;
922                 }
923
924                 /*
925                  * The previous round may already have decided to
926                  * delete this path, which is in a subdirectory that
927                  * is being replaced with a blob.
928                  */
929                 result = index_name_exists(&o->result, ce->name, ce_namelen(ce), 0);
930                 if (result) {
931                         if (result->ce_flags & CE_REMOVE)
932                                 return 0;
933                 }
934
935                 return o->gently ? -1 :
936                         error(ERRORMSG(o, would_lose_untracked), ce->name, action);
937         }
938         return 0;
939 }
940
941 static int merged_entry(struct cache_entry *merge, struct cache_entry *old,
942                 struct unpack_trees_options *o)
943 {
944         int update = CE_UPDATE;
945
946         if (old) {
947                 /*
948                  * See if we can re-use the old CE directly?
949                  * That way we get the uptodate stat info.
950                  *
951                  * This also removes the UPDATE flag on a match; otherwise
952                  * we will end up overwriting local changes in the work tree.
953                  */
954                 if (same(old, merge)) {
955                         copy_cache_entry(merge, old);
956                         update = 0;
957                 } else {
958                         if (verify_uptodate(old, o))
959                                 return -1;
960                         invalidate_ce_path(old, o);
961                 }
962         }
963         else {
964                 if (verify_absent(merge, "overwritten", o))
965                         return -1;
966                 invalidate_ce_path(merge, o);
967         }
968
969         add_entry(o, merge, update, CE_STAGEMASK);
970         return 1;
971 }
972
973 static int deleted_entry(struct cache_entry *ce, struct cache_entry *old,
974                 struct unpack_trees_options *o)
975 {
976         /* Did it exist in the index? */
977         if (!old) {
978                 if (verify_absent(ce, "removed", o))
979                         return -1;
980                 return 0;
981         }
982         if (verify_uptodate(old, o))
983                 return -1;
984         add_entry(o, ce, CE_REMOVE, 0);
985         invalidate_ce_path(ce, o);
986         return 1;
987 }
988
989 static int keep_entry(struct cache_entry *ce, struct unpack_trees_options *o)
990 {
991         add_entry(o, ce, 0, 0);
992         return 1;
993 }
994
995 #if DBRT_DEBUG
996 static void show_stage_entry(FILE *o,
997                              const char *label, const struct cache_entry *ce)
998 {
999         if (!ce)
1000                 fprintf(o, "%s (missing)\n", label);
1001         else
1002                 fprintf(o, "%s%06o %s %d\t%s\n",
1003                         label,
1004                         ce->ce_mode,
1005                         sha1_to_hex(ce->sha1),
1006                         ce_stage(ce),
1007                         ce->name);
1008 }
1009 #endif
1010
1011 int threeway_merge(struct cache_entry **stages, struct unpack_trees_options *o)
1012 {
1013         struct cache_entry *index;
1014         struct cache_entry *head;
1015         struct cache_entry *remote = stages[o->head_idx + 1];
1016         int count;
1017         int head_match = 0;
1018         int remote_match = 0;
1019
1020         int df_conflict_head = 0;
1021         int df_conflict_remote = 0;
1022
1023         int any_anc_missing = 0;
1024         int no_anc_exists = 1;
1025         int i;
1026
1027         for (i = 1; i < o->head_idx; i++) {
1028                 if (!stages[i] || stages[i] == o->df_conflict_entry)
1029                         any_anc_missing = 1;
1030                 else
1031                         no_anc_exists = 0;
1032         }
1033
1034         index = stages[0];
1035         head = stages[o->head_idx];
1036
1037         if (head == o->df_conflict_entry) {
1038                 df_conflict_head = 1;
1039                 head = NULL;
1040         }
1041
1042         if (remote == o->df_conflict_entry) {
1043                 df_conflict_remote = 1;
1044                 remote = NULL;
1045         }
1046
1047         /* First, if there's a #16 situation, note that to prevent #13
1048          * and #14.
1049          */
1050         if (!same(remote, head)) {
1051                 for (i = 1; i < o->head_idx; i++) {
1052                         if (same(stages[i], head)) {
1053                                 head_match = i;
1054                         }
1055                         if (same(stages[i], remote)) {
1056                                 remote_match = i;
1057                         }
1058                 }
1059         }
1060
1061         /* We start with cases where the index is allowed to match
1062          * something other than the head: #14(ALT) and #2ALT, where it
1063          * is permitted to match the result instead.
1064          */
1065         /* #14, #14ALT, #2ALT */
1066         if (remote && !df_conflict_head && head_match && !remote_match) {
1067                 if (index && !same(index, remote) && !same(index, head))
1068                         return o->gently ? -1 : reject_merge(index, o);
1069                 return merged_entry(remote, index, o);
1070         }
1071         /*
1072          * If we have an entry in the index cache, then we want to
1073          * make sure that it matches head.
1074          */
1075         if (index && !same(index, head))
1076                 return o->gently ? -1 : reject_merge(index, o);
1077
1078         if (head) {
1079                 /* #5ALT, #15 */
1080                 if (same(head, remote))
1081                         return merged_entry(head, index, o);
1082                 /* #13, #3ALT */
1083                 if (!df_conflict_remote && remote_match && !head_match)
1084                         return merged_entry(head, index, o);
1085         }
1086
1087         /* #1 */
1088         if (!head && !remote && any_anc_missing)
1089                 return 0;
1090
1091         /* Under the new "aggressive" rule, we resolve mostly trivial
1092          * cases that we historically had git-merge-one-file resolve.
1093          */
1094         if (o->aggressive) {
1095                 int head_deleted = !head && !df_conflict_head;
1096                 int remote_deleted = !remote && !df_conflict_remote;
1097                 struct cache_entry *ce = NULL;
1098
1099                 if (index)
1100                         ce = index;
1101                 else if (head)
1102                         ce = head;
1103                 else if (remote)
1104                         ce = remote;
1105                 else {
1106                         for (i = 1; i < o->head_idx; i++) {
1107                                 if (stages[i] && stages[i] != o->df_conflict_entry) {
1108                                         ce = stages[i];
1109                                         break;
1110                                 }
1111                         }
1112                 }
1113
1114                 /*
1115                  * Deleted in both.
1116                  * Deleted in one and unchanged in the other.
1117                  */
1118                 if ((head_deleted && remote_deleted) ||
1119                     (head_deleted && remote && remote_match) ||
1120                     (remote_deleted && head && head_match)) {
1121                         if (index)
1122                                 return deleted_entry(index, index, o);
1123                         if (ce && !head_deleted) {
1124                                 if (verify_absent(ce, "removed", o))
1125                                         return -1;
1126                         }
1127                         return 0;
1128                 }
1129                 /*
1130                  * Added in both, identically.
1131                  */
1132                 if (no_anc_exists && head && remote && same(head, remote))
1133                         return merged_entry(head, index, o);
1134
1135         }
1136
1137         /* Below are "no merge" cases, which require that the index be
1138          * up-to-date to avoid the files getting overwritten with
1139          * conflict resolution files.
1140          */
1141         if (index) {
1142                 if (verify_uptodate(index, o))
1143                         return -1;
1144         }
1145
1146         o->nontrivial_merge = 1;
1147
1148         /* #2, #3, #4, #6, #7, #9, #10, #11. */
1149         count = 0;
1150         if (!head_match || !remote_match) {
1151                 for (i = 1; i < o->head_idx; i++) {
1152                         if (stages[i] && stages[i] != o->df_conflict_entry) {
1153                                 keep_entry(stages[i], o);
1154                                 count++;
1155                                 break;
1156                         }
1157                 }
1158         }
1159 #if DBRT_DEBUG
1160         else {
1161                 fprintf(stderr, "read-tree: warning #16 detected\n");
1162                 show_stage_entry(stderr, "head   ", stages[head_match]);
1163                 show_stage_entry(stderr, "remote ", stages[remote_match]);
1164         }
1165 #endif
1166         if (head) { count += keep_entry(head, o); }
1167         if (remote) { count += keep_entry(remote, o); }
1168         return count;
1169 }
1170
1171 /*
1172  * Two-way merge.
1173  *
1174  * The rule is to "carry forward" what is in the index without losing
1175  * information across a "fast forward", favoring a successful merge
1176  * over a merge failure when it makes sense.  For details of the
1177  * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
1178  *
1179  */
1180 int twoway_merge(struct cache_entry **src, struct unpack_trees_options *o)
1181 {
1182         struct cache_entry *current = src[0];
1183         struct cache_entry *oldtree = src[1];
1184         struct cache_entry *newtree = src[2];
1185
1186         if (o->merge_size != 2)
1187                 return error("Cannot do a twoway merge of %d trees",
1188                              o->merge_size);
1189
1190         if (oldtree == o->df_conflict_entry)
1191                 oldtree = NULL;
1192         if (newtree == o->df_conflict_entry)
1193                 newtree = NULL;
1194
1195         if (current) {
1196                 if ((!oldtree && !newtree) || /* 4 and 5 */
1197                     (!oldtree && newtree &&
1198                      same(current, newtree)) || /* 6 and 7 */
1199                     (oldtree && newtree &&
1200                      same(oldtree, newtree)) || /* 14 and 15 */
1201                     (oldtree && newtree &&
1202                      !same(oldtree, newtree) && /* 18 and 19 */
1203                      same(current, newtree))) {
1204                         return keep_entry(current, o);
1205                 }
1206                 else if (oldtree && !newtree && same(current, oldtree)) {
1207                         /* 10 or 11 */
1208                         return deleted_entry(oldtree, current, o);
1209                 }
1210                 else if (oldtree && newtree &&
1211                          same(current, oldtree) && !same(current, newtree)) {
1212                         /* 20 or 21 */
1213                         return merged_entry(newtree, current, o);
1214                 }
1215                 else {
1216                         /* all other failures */
1217                         if (oldtree)
1218                                 return o->gently ? -1 : reject_merge(oldtree, o);
1219                         if (current)
1220                                 return o->gently ? -1 : reject_merge(current, o);
1221                         if (newtree)
1222                                 return o->gently ? -1 : reject_merge(newtree, o);
1223                         return -1;
1224                 }
1225         }
1226         else if (newtree) {
1227                 if (oldtree && !o->initial_checkout) {
1228                         /*
1229                          * deletion of the path was staged;
1230                          */
1231                         if (same(oldtree, newtree))
1232                                 return 1;
1233                         return reject_merge(oldtree, o);
1234                 }
1235                 return merged_entry(newtree, current, o);
1236         }
1237         return deleted_entry(oldtree, current, o);
1238 }
1239
1240 /*
1241  * Bind merge.
1242  *
1243  * Keep the index entries at stage0, collapse stage1 but make sure
1244  * stage0 does not have anything there.
1245  */
1246 int bind_merge(struct cache_entry **src,
1247                 struct unpack_trees_options *o)
1248 {
1249         struct cache_entry *old = src[0];
1250         struct cache_entry *a = src[1];
1251
1252         if (o->merge_size != 1)
1253                 return error("Cannot do a bind merge of %d trees\n",
1254                              o->merge_size);
1255         if (a && old)
1256                 return o->gently ? -1 :
1257                         error(ERRORMSG(o, bind_overlap), a->name, old->name);
1258         if (!a)
1259                 return keep_entry(old, o);
1260         else
1261                 return merged_entry(a, NULL, o);
1262 }
1263
1264 /*
1265  * One-way merge.
1266  *
1267  * The rule is:
1268  * - take the stat information from stage0, take the data from stage1
1269  */
1270 int oneway_merge(struct cache_entry **src, struct unpack_trees_options *o)
1271 {
1272         struct cache_entry *old = src[0];
1273         struct cache_entry *a = src[1];
1274
1275         if (o->merge_size != 1)
1276                 return error("Cannot do a oneway merge of %d trees",
1277                              o->merge_size);
1278
1279         if (!a || a == o->df_conflict_entry)
1280                 return deleted_entry(old, old, o);
1281
1282         if (old && same(old, a)) {
1283                 int update = 0;
1284                 if (o->reset && !ce_uptodate(old)) {
1285                         struct stat st;
1286                         if (lstat(old->name, &st) ||
1287                             ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID))
1288                                 update |= CE_UPDATE;
1289                 }
1290                 add_entry(o, old, update, 0);
1291                 return 0;
1292         }
1293         return merged_entry(a, old, o);
1294 }