Merge branch 'rs/fix-alt-odb-path-comparison'
[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" and "git merge" replaces
17  * them using setup_unpack_trees_porcelain(), for example.
18  */
19 static const char *unpack_plumbing_errors[NB_UNPACK_TREES_ERROR_TYPES] = {
20         /* ERROR_WOULD_OVERWRITE */
21         "Entry '%s' would be overwritten by merge. Cannot merge.",
22
23         /* ERROR_NOT_UPTODATE_FILE */
24         "Entry '%s' not uptodate. Cannot merge.",
25
26         /* ERROR_NOT_UPTODATE_DIR */
27         "Updating '%s' would lose untracked files in it",
28
29         /* ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN */
30         "Untracked working tree file '%s' would be overwritten by merge.",
31
32         /* ERROR_WOULD_LOSE_UNTRACKED_REMOVED */
33         "Untracked working tree file '%s' would be removed by merge.",
34
35         /* ERROR_BIND_OVERLAP */
36         "Entry '%s' overlaps with '%s'.  Cannot bind.",
37
38         /* ERROR_SPARSE_NOT_UPTODATE_FILE */
39         "Entry '%s' not uptodate. Cannot update sparse checkout.",
40
41         /* ERROR_WOULD_LOSE_ORPHANED_OVERWRITTEN */
42         "Working tree file '%s' would be overwritten by sparse checkout update.",
43
44         /* ERROR_WOULD_LOSE_ORPHANED_REMOVED */
45         "Working tree file '%s' would be removed by sparse checkout update.",
46 };
47
48 #define ERRORMSG(o,type) \
49         ( ((o) && (o)->msgs[(type)]) \
50           ? ((o)->msgs[(type)])      \
51           : (unpack_plumbing_errors[(type)]) )
52
53 void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,
54                                   const char *cmd)
55 {
56         int i;
57         const char **msgs = opts->msgs;
58         const char *msg;
59         const char *cmd2 = strcmp(cmd, "checkout") ? cmd : "switch branches";
60
61         if (advice_commit_before_merge)
62                 msg = "Your local changes to the following files would be overwritten by %s:\n%%s"
63                         "Please, commit your changes or stash them before you can %s.";
64         else
65                 msg = "Your local changes to the following files would be overwritten by %s:\n%%s";
66         msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOT_UPTODATE_FILE] =
67                 xstrfmt(msg, cmd, cmd2);
68
69         msgs[ERROR_NOT_UPTODATE_DIR] =
70                 "Updating the following directories would lose untracked files in it:\n%s";
71
72         if (advice_commit_before_merge)
73                 msg = "The following untracked working tree files would be %s by %s:\n%%s"
74                         "Please move or remove them before you can %s.";
75         else
76                 msg = "The following untracked working tree files would be %s by %s:\n%%s";
77
78         msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED] = xstrfmt(msg, "removed", cmd, cmd2);
79         msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN] = xstrfmt(msg, "overwritten", cmd, cmd2);
80
81         /*
82          * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
83          * cannot easily display it as a list.
84          */
85         msgs[ERROR_BIND_OVERLAP] = "Entry '%s' overlaps with '%s'.  Cannot bind.";
86
87         msgs[ERROR_SPARSE_NOT_UPTODATE_FILE] =
88                 "Cannot update sparse checkout: the following entries are not up-to-date:\n%s";
89         msgs[ERROR_WOULD_LOSE_ORPHANED_OVERWRITTEN] =
90                 "The following Working tree files would be overwritten by sparse checkout update:\n%s";
91         msgs[ERROR_WOULD_LOSE_ORPHANED_REMOVED] =
92                 "The following Working tree files would be removed by sparse checkout update:\n%s";
93
94         opts->show_all_errors = 1;
95         /* rejected paths may not have a static buffer */
96         for (i = 0; i < ARRAY_SIZE(opts->unpack_rejects); i++)
97                 opts->unpack_rejects[i].strdup_strings = 1;
98 }
99
100 static void do_add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
101                          unsigned int set, unsigned int clear)
102 {
103         clear |= CE_HASHED;
104
105         if (set & CE_REMOVE)
106                 set |= CE_WT_REMOVE;
107
108         ce->ce_flags = (ce->ce_flags & ~clear) | set;
109         add_index_entry(&o->result, ce,
110                         ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
111 }
112
113 static struct cache_entry *dup_entry(const struct cache_entry *ce)
114 {
115         unsigned int size = ce_size(ce);
116         struct cache_entry *new = xmalloc(size);
117
118         memcpy(new, ce, size);
119         return new;
120 }
121
122 static void add_entry(struct unpack_trees_options *o,
123                       const struct cache_entry *ce,
124                       unsigned int set, unsigned int clear)
125 {
126         do_add_entry(o, dup_entry(ce), set, clear);
127 }
128
129 /*
130  * add error messages on path <path>
131  * corresponding to the type <e> with the message <msg>
132  * indicating if it should be display in porcelain or not
133  */
134 static int add_rejected_path(struct unpack_trees_options *o,
135                              enum unpack_trees_error_types e,
136                              const char *path)
137 {
138         if (!o->show_all_errors)
139                 return error(ERRORMSG(o, e), path);
140
141         /*
142          * Otherwise, insert in a list for future display by
143          * display_error_msgs()
144          */
145         string_list_append(&o->unpack_rejects[e], path);
146         return -1;
147 }
148
149 /*
150  * display all the error messages stored in a nice way
151  */
152 static void display_error_msgs(struct unpack_trees_options *o)
153 {
154         int e, i;
155         int something_displayed = 0;
156         for (e = 0; e < NB_UNPACK_TREES_ERROR_TYPES; e++) {
157                 struct string_list *rejects = &o->unpack_rejects[e];
158                 if (rejects->nr > 0) {
159                         struct strbuf path = STRBUF_INIT;
160                         something_displayed = 1;
161                         for (i = 0; i < rejects->nr; i++)
162                                 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
163                         error(ERRORMSG(o, e), path.buf);
164                         strbuf_release(&path);
165                 }
166                 string_list_clear(rejects, 0);
167         }
168         if (something_displayed)
169                 fprintf(stderr, "Aborting\n");
170 }
171
172 /*
173  * Unlink the last component and schedule the leading directories for
174  * removal, such that empty directories get removed.
175  */
176 static void unlink_entry(const struct cache_entry *ce)
177 {
178         if (!check_leading_path(ce->name, ce_namelen(ce)))
179                 return;
180         if (remove_or_warn(ce->ce_mode, ce->name))
181                 return;
182         schedule_dir_for_removal(ce->name, ce_namelen(ce));
183 }
184
185 static struct checkout state;
186 static int check_updates(struct unpack_trees_options *o)
187 {
188         unsigned cnt = 0, total = 0;
189         struct progress *progress = NULL;
190         struct index_state *index = &o->result;
191         int i;
192         int errs = 0;
193
194         if (o->update && o->verbose_update) {
195                 for (total = cnt = 0; cnt < index->cache_nr; cnt++) {
196                         const struct cache_entry *ce = index->cache[cnt];
197                         if (ce->ce_flags & (CE_UPDATE | CE_WT_REMOVE))
198                                 total++;
199                 }
200
201                 progress = start_progress_delay(_("Checking out files"),
202                                                 total, 50, 1);
203                 cnt = 0;
204         }
205
206         if (o->update)
207                 git_attr_set_direction(GIT_ATTR_CHECKOUT, &o->result);
208         for (i = 0; i < index->cache_nr; i++) {
209                 const struct cache_entry *ce = index->cache[i];
210
211                 if (ce->ce_flags & CE_WT_REMOVE) {
212                         display_progress(progress, ++cnt);
213                         if (o->update && !o->dry_run)
214                                 unlink_entry(ce);
215                         continue;
216                 }
217         }
218         remove_marked_cache_entries(&o->result);
219         remove_scheduled_dirs();
220
221         for (i = 0; i < index->cache_nr; i++) {
222                 struct cache_entry *ce = index->cache[i];
223
224                 if (ce->ce_flags & CE_UPDATE) {
225                         display_progress(progress, ++cnt);
226                         ce->ce_flags &= ~CE_UPDATE;
227                         if (o->update && !o->dry_run) {
228                                 errs |= checkout_entry(ce, &state, NULL);
229                         }
230                 }
231         }
232         stop_progress(&progress);
233         if (o->update)
234                 git_attr_set_direction(GIT_ATTR_CHECKIN, NULL);
235         return errs != 0;
236 }
237
238 static int verify_uptodate_sparse(const struct cache_entry *ce,
239                                   struct unpack_trees_options *o);
240 static int verify_absent_sparse(const struct cache_entry *ce,
241                                 enum unpack_trees_error_types,
242                                 struct unpack_trees_options *o);
243
244 static int apply_sparse_checkout(struct cache_entry *ce, struct unpack_trees_options *o)
245 {
246         int was_skip_worktree = ce_skip_worktree(ce);
247
248         if (ce->ce_flags & CE_NEW_SKIP_WORKTREE)
249                 ce->ce_flags |= CE_SKIP_WORKTREE;
250         else
251                 ce->ce_flags &= ~CE_SKIP_WORKTREE;
252
253         /*
254          * if (!was_skip_worktree && !ce_skip_worktree()) {
255          *      This is perfectly normal. Move on;
256          * }
257          */
258
259         /*
260          * Merge strategies may set CE_UPDATE|CE_REMOVE outside checkout
261          * area as a result of ce_skip_worktree() shortcuts in
262          * verify_absent() and verify_uptodate().
263          * Make sure they don't modify worktree if they are already
264          * outside checkout area
265          */
266         if (was_skip_worktree && ce_skip_worktree(ce)) {
267                 ce->ce_flags &= ~CE_UPDATE;
268
269                 /*
270                  * By default, when CE_REMOVE is on, CE_WT_REMOVE is also
271                  * on to get that file removed from both index and worktree.
272                  * If that file is already outside worktree area, don't
273                  * bother remove it.
274                  */
275                 if (ce->ce_flags & CE_REMOVE)
276                         ce->ce_flags &= ~CE_WT_REMOVE;
277         }
278
279         if (!was_skip_worktree && ce_skip_worktree(ce)) {
280                 /*
281                  * If CE_UPDATE is set, verify_uptodate() must be called already
282                  * also stat info may have lost after merged_entry() so calling
283                  * verify_uptodate() again may fail
284                  */
285                 if (!(ce->ce_flags & CE_UPDATE) && verify_uptodate_sparse(ce, o))
286                         return -1;
287                 ce->ce_flags |= CE_WT_REMOVE;
288         }
289         if (was_skip_worktree && !ce_skip_worktree(ce)) {
290                 if (verify_absent_sparse(ce, ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o))
291                         return -1;
292                 ce->ce_flags |= CE_UPDATE;
293         }
294         return 0;
295 }
296
297 static inline int call_unpack_fn(const struct cache_entry * const *src,
298                                  struct unpack_trees_options *o)
299 {
300         int ret = o->fn(src, o);
301         if (ret > 0)
302                 ret = 0;
303         return ret;
304 }
305
306 static void mark_ce_used(struct cache_entry *ce, struct unpack_trees_options *o)
307 {
308         ce->ce_flags |= CE_UNPACKED;
309
310         if (o->cache_bottom < o->src_index->cache_nr &&
311             o->src_index->cache[o->cache_bottom] == ce) {
312                 int bottom = o->cache_bottom;
313                 while (bottom < o->src_index->cache_nr &&
314                        o->src_index->cache[bottom]->ce_flags & CE_UNPACKED)
315                         bottom++;
316                 o->cache_bottom = bottom;
317         }
318 }
319
320 static void mark_all_ce_unused(struct index_state *index)
321 {
322         int i;
323         for (i = 0; i < index->cache_nr; i++)
324                 index->cache[i]->ce_flags &= ~(CE_UNPACKED | CE_ADDED | CE_NEW_SKIP_WORKTREE);
325 }
326
327 static int locate_in_src_index(const struct cache_entry *ce,
328                                struct unpack_trees_options *o)
329 {
330         struct index_state *index = o->src_index;
331         int len = ce_namelen(ce);
332         int pos = index_name_pos(index, ce->name, len);
333         if (pos < 0)
334                 pos = -1 - pos;
335         return pos;
336 }
337
338 /*
339  * We call unpack_index_entry() with an unmerged cache entry
340  * only in diff-index, and it wants a single callback.  Skip
341  * the other unmerged entry with the same name.
342  */
343 static void mark_ce_used_same_name(struct cache_entry *ce,
344                                    struct unpack_trees_options *o)
345 {
346         struct index_state *index = o->src_index;
347         int len = ce_namelen(ce);
348         int pos;
349
350         for (pos = locate_in_src_index(ce, o); pos < index->cache_nr; pos++) {
351                 struct cache_entry *next = index->cache[pos];
352                 if (len != ce_namelen(next) ||
353                     memcmp(ce->name, next->name, len))
354                         break;
355                 mark_ce_used(next, o);
356         }
357 }
358
359 static struct cache_entry *next_cache_entry(struct unpack_trees_options *o)
360 {
361         const struct index_state *index = o->src_index;
362         int pos = o->cache_bottom;
363
364         while (pos < index->cache_nr) {
365                 struct cache_entry *ce = index->cache[pos];
366                 if (!(ce->ce_flags & CE_UNPACKED))
367                         return ce;
368                 pos++;
369         }
370         return NULL;
371 }
372
373 static void add_same_unmerged(const struct cache_entry *ce,
374                               struct unpack_trees_options *o)
375 {
376         struct index_state *index = o->src_index;
377         int len = ce_namelen(ce);
378         int pos = index_name_pos(index, ce->name, len);
379
380         if (0 <= pos)
381                 die("programming error in a caller of mark_ce_used_same_name");
382         for (pos = -pos - 1; pos < index->cache_nr; pos++) {
383                 struct cache_entry *next = index->cache[pos];
384                 if (len != ce_namelen(next) ||
385                     memcmp(ce->name, next->name, len))
386                         break;
387                 add_entry(o, next, 0, 0);
388                 mark_ce_used(next, o);
389         }
390 }
391
392 static int unpack_index_entry(struct cache_entry *ce,
393                               struct unpack_trees_options *o)
394 {
395         const struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
396         int ret;
397
398         src[0] = ce;
399
400         mark_ce_used(ce, o);
401         if (ce_stage(ce)) {
402                 if (o->skip_unmerged) {
403                         add_entry(o, ce, 0, 0);
404                         return 0;
405                 }
406         }
407         ret = call_unpack_fn(src, o);
408         if (ce_stage(ce))
409                 mark_ce_used_same_name(ce, o);
410         return ret;
411 }
412
413 static int find_cache_pos(struct traverse_info *, const struct name_entry *);
414
415 static void restore_cache_bottom(struct traverse_info *info, int bottom)
416 {
417         struct unpack_trees_options *o = info->data;
418
419         if (o->diff_index_cached)
420                 return;
421         o->cache_bottom = bottom;
422 }
423
424 static int switch_cache_bottom(struct traverse_info *info)
425 {
426         struct unpack_trees_options *o = info->data;
427         int ret, pos;
428
429         if (o->diff_index_cached)
430                 return 0;
431         ret = o->cache_bottom;
432         pos = find_cache_pos(info->prev, &info->name);
433
434         if (pos < -1)
435                 o->cache_bottom = -2 - pos;
436         else if (pos < 0)
437                 o->cache_bottom = o->src_index->cache_nr;
438         return ret;
439 }
440
441 static int traverse_trees_recursive(int n, unsigned long dirmask,
442                                     unsigned long df_conflicts,
443                                     struct name_entry *names,
444                                     struct traverse_info *info)
445 {
446         int i, ret, bottom;
447         struct tree_desc t[MAX_UNPACK_TREES];
448         void *buf[MAX_UNPACK_TREES];
449         struct traverse_info newinfo;
450         struct name_entry *p;
451
452         p = names;
453         while (!p->mode)
454                 p++;
455
456         newinfo = *info;
457         newinfo.prev = info;
458         newinfo.pathspec = info->pathspec;
459         newinfo.name = *p;
460         newinfo.pathlen += tree_entry_len(p) + 1;
461         newinfo.df_conflicts |= df_conflicts;
462
463         for (i = 0; i < n; i++, dirmask >>= 1) {
464                 const unsigned char *sha1 = NULL;
465                 if (dirmask & 1)
466                         sha1 = names[i].sha1;
467                 buf[i] = fill_tree_descriptor(t+i, sha1);
468         }
469
470         bottom = switch_cache_bottom(&newinfo);
471         ret = traverse_trees(n, t, &newinfo);
472         restore_cache_bottom(&newinfo, bottom);
473
474         for (i = 0; i < n; i++)
475                 free(buf[i]);
476
477         return ret;
478 }
479
480 /*
481  * Compare the traverse-path to the cache entry without actually
482  * having to generate the textual representation of the traverse
483  * path.
484  *
485  * NOTE! This *only* compares up to the size of the traverse path
486  * itself - the caller needs to do the final check for the cache
487  * entry having more data at the end!
488  */
489 static int do_compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
490 {
491         int len, pathlen, ce_len;
492         const char *ce_name;
493
494         if (info->prev) {
495                 int cmp = do_compare_entry(ce, info->prev, &info->name);
496                 if (cmp)
497                         return cmp;
498         }
499         pathlen = info->pathlen;
500         ce_len = ce_namelen(ce);
501
502         /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
503         if (ce_len < pathlen)
504                 return -1;
505
506         ce_len -= pathlen;
507         ce_name = ce->name + pathlen;
508
509         len = tree_entry_len(n);
510         return df_name_compare(ce_name, ce_len, S_IFREG, n->path, len, n->mode);
511 }
512
513 static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
514 {
515         int cmp = do_compare_entry(ce, info, n);
516         if (cmp)
517                 return cmp;
518
519         /*
520          * Even if the beginning compared identically, the ce should
521          * compare as bigger than a directory leading up to it!
522          */
523         return ce_namelen(ce) > traverse_path_len(info, n);
524 }
525
526 static int ce_in_traverse_path(const struct cache_entry *ce,
527                                const struct traverse_info *info)
528 {
529         if (!info->prev)
530                 return 1;
531         if (do_compare_entry(ce, info->prev, &info->name))
532                 return 0;
533         /*
534          * If ce (blob) is the same name as the path (which is a tree
535          * we will be descending into), it won't be inside it.
536          */
537         return (info->pathlen < ce_namelen(ce));
538 }
539
540 static struct cache_entry *create_ce_entry(const struct traverse_info *info, const struct name_entry *n, int stage)
541 {
542         int len = traverse_path_len(info, n);
543         struct cache_entry *ce = xcalloc(1, cache_entry_size(len));
544
545         ce->ce_mode = create_ce_mode(n->mode);
546         ce->ce_flags = create_ce_flags(stage);
547         ce->ce_namelen = len;
548         hashcpy(ce->sha1, n->sha1);
549         make_traverse_path(ce->name, info, n);
550
551         return ce;
552 }
553
554 static int unpack_nondirectories(int n, unsigned long mask,
555                                  unsigned long dirmask,
556                                  struct cache_entry **src,
557                                  const struct name_entry *names,
558                                  const struct traverse_info *info)
559 {
560         int i;
561         struct unpack_trees_options *o = info->data;
562         unsigned long conflicts = info->df_conflicts | dirmask;
563
564         /* Do we have *only* directories? Nothing to do */
565         if (mask == dirmask && !src[0])
566                 return 0;
567
568         /*
569          * Ok, we've filled in up to any potential index entry in src[0],
570          * now do the rest.
571          */
572         for (i = 0; i < n; i++) {
573                 int stage;
574                 unsigned int bit = 1ul << i;
575                 if (conflicts & bit) {
576                         src[i + o->merge] = o->df_conflict_entry;
577                         continue;
578                 }
579                 if (!(mask & bit))
580                         continue;
581                 if (!o->merge)
582                         stage = 0;
583                 else if (i + 1 < o->head_idx)
584                         stage = 1;
585                 else if (i + 1 > o->head_idx)
586                         stage = 3;
587                 else
588                         stage = 2;
589                 src[i + o->merge] = create_ce_entry(info, names + i, stage);
590         }
591
592         if (o->merge) {
593                 int rc = call_unpack_fn((const struct cache_entry * const *)src,
594                                         o);
595                 for (i = 0; i < n; i++) {
596                         struct cache_entry *ce = src[i + o->merge];
597                         if (ce != o->df_conflict_entry)
598                                 free(ce);
599                 }
600                 return rc;
601         }
602
603         for (i = 0; i < n; i++)
604                 if (src[i] && src[i] != o->df_conflict_entry)
605                         do_add_entry(o, src[i], 0, 0);
606         return 0;
607 }
608
609 static int unpack_failed(struct unpack_trees_options *o, const char *message)
610 {
611         discard_index(&o->result);
612         if (!o->gently && !o->exiting_early) {
613                 if (message)
614                         return error("%s", message);
615                 return -1;
616         }
617         return -1;
618 }
619
620 /*
621  * The tree traversal is looking at name p.  If we have a matching entry,
622  * return it.  If name p is a directory in the index, do not return
623  * anything, as we will want to match it when the traversal descends into
624  * the directory.
625  */
626 static int find_cache_pos(struct traverse_info *info,
627                           const struct name_entry *p)
628 {
629         int pos;
630         struct unpack_trees_options *o = info->data;
631         struct index_state *index = o->src_index;
632         int pfxlen = info->pathlen;
633         int p_len = tree_entry_len(p);
634
635         for (pos = o->cache_bottom; pos < index->cache_nr; pos++) {
636                 const struct cache_entry *ce = index->cache[pos];
637                 const char *ce_name, *ce_slash;
638                 int cmp, ce_len;
639
640                 if (ce->ce_flags & CE_UNPACKED) {
641                         /*
642                          * cache_bottom entry is already unpacked, so
643                          * we can never match it; don't check it
644                          * again.
645                          */
646                         if (pos == o->cache_bottom)
647                                 ++o->cache_bottom;
648                         continue;
649                 }
650                 if (!ce_in_traverse_path(ce, info))
651                         continue;
652                 ce_name = ce->name + pfxlen;
653                 ce_slash = strchr(ce_name, '/');
654                 if (ce_slash)
655                         ce_len = ce_slash - ce_name;
656                 else
657                         ce_len = ce_namelen(ce) - pfxlen;
658                 cmp = name_compare(p->path, p_len, ce_name, ce_len);
659                 /*
660                  * Exact match; if we have a directory we need to
661                  * delay returning it.
662                  */
663                 if (!cmp)
664                         return ce_slash ? -2 - pos : pos;
665                 if (0 < cmp)
666                         continue; /* keep looking */
667                 /*
668                  * ce_name sorts after p->path; could it be that we
669                  * have files under p->path directory in the index?
670                  * E.g.  ce_name == "t-i", and p->path == "t"; we may
671                  * have "t/a" in the index.
672                  */
673                 if (p_len < ce_len && !memcmp(ce_name, p->path, p_len) &&
674                     ce_name[p_len] < '/')
675                         continue; /* keep looking */
676                 break;
677         }
678         return -1;
679 }
680
681 static struct cache_entry *find_cache_entry(struct traverse_info *info,
682                                             const struct name_entry *p)
683 {
684         int pos = find_cache_pos(info, p);
685         struct unpack_trees_options *o = info->data;
686
687         if (0 <= pos)
688                 return o->src_index->cache[pos];
689         else
690                 return NULL;
691 }
692
693 static void debug_path(struct traverse_info *info)
694 {
695         if (info->prev) {
696                 debug_path(info->prev);
697                 if (*info->prev->name.path)
698                         putchar('/');
699         }
700         printf("%s", info->name.path);
701 }
702
703 static void debug_name_entry(int i, struct name_entry *n)
704 {
705         printf("ent#%d %06o %s\n", i,
706                n->path ? n->mode : 0,
707                n->path ? n->path : "(missing)");
708 }
709
710 static void debug_unpack_callback(int n,
711                                   unsigned long mask,
712                                   unsigned long dirmask,
713                                   struct name_entry *names,
714                                   struct traverse_info *info)
715 {
716         int i;
717         printf("* unpack mask %lu, dirmask %lu, cnt %d ",
718                mask, dirmask, n);
719         debug_path(info);
720         putchar('\n');
721         for (i = 0; i < n; i++)
722                 debug_name_entry(i, names + i);
723 }
724
725 static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
726 {
727         struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
728         struct unpack_trees_options *o = info->data;
729         const struct name_entry *p = names;
730
731         /* Find first entry with a real name (we could use "mask" too) */
732         while (!p->mode)
733                 p++;
734
735         if (o->debug_unpack)
736                 debug_unpack_callback(n, mask, dirmask, names, info);
737
738         /* Are we supposed to look at the index too? */
739         if (o->merge) {
740                 while (1) {
741                         int cmp;
742                         struct cache_entry *ce;
743
744                         if (o->diff_index_cached)
745                                 ce = next_cache_entry(o);
746                         else
747                                 ce = find_cache_entry(info, p);
748
749                         if (!ce)
750                                 break;
751                         cmp = compare_entry(ce, info, p);
752                         if (cmp < 0) {
753                                 if (unpack_index_entry(ce, o) < 0)
754                                         return unpack_failed(o, NULL);
755                                 continue;
756                         }
757                         if (!cmp) {
758                                 if (ce_stage(ce)) {
759                                         /*
760                                          * If we skip unmerged index
761                                          * entries, we'll skip this
762                                          * entry *and* the tree
763                                          * entries associated with it!
764                                          */
765                                         if (o->skip_unmerged) {
766                                                 add_same_unmerged(ce, o);
767                                                 return mask;
768                                         }
769                                 }
770                                 src[0] = ce;
771                         }
772                         break;
773                 }
774         }
775
776         if (unpack_nondirectories(n, mask, dirmask, src, names, info) < 0)
777                 return -1;
778
779         if (o->merge && src[0]) {
780                 if (ce_stage(src[0]))
781                         mark_ce_used_same_name(src[0], o);
782                 else
783                         mark_ce_used(src[0], o);
784         }
785
786         /* Now handle any directories.. */
787         if (dirmask) {
788                 /* special case: "diff-index --cached" looking at a tree */
789                 if (o->diff_index_cached &&
790                     n == 1 && dirmask == 1 && S_ISDIR(names->mode)) {
791                         int matches;
792                         matches = cache_tree_matches_traversal(o->src_index->cache_tree,
793                                                                names, info);
794                         /*
795                          * Everything under the name matches; skip the
796                          * entire hierarchy.  diff_index_cached codepath
797                          * special cases D/F conflicts in such a way that
798                          * it does not do any look-ahead, so this is safe.
799                          */
800                         if (matches) {
801                                 o->cache_bottom += matches;
802                                 return mask;
803                         }
804                 }
805
806                 if (traverse_trees_recursive(n, dirmask, mask & ~dirmask,
807                                              names, info) < 0)
808                         return -1;
809                 return mask;
810         }
811
812         return mask;
813 }
814
815 static int clear_ce_flags_1(struct cache_entry **cache, int nr,
816                             struct strbuf *prefix,
817                             int select_mask, int clear_mask,
818                             struct exclude_list *el, int defval);
819
820 /* Whole directory matching */
821 static int clear_ce_flags_dir(struct cache_entry **cache, int nr,
822                               struct strbuf *prefix,
823                               char *basename,
824                               int select_mask, int clear_mask,
825                               struct exclude_list *el, int defval)
826 {
827         struct cache_entry **cache_end;
828         int dtype = DT_DIR;
829         int ret = is_excluded_from_list(prefix->buf, prefix->len,
830                                         basename, &dtype, el);
831         int rc;
832
833         strbuf_addch(prefix, '/');
834
835         /* If undecided, use matching result of parent dir in defval */
836         if (ret < 0)
837                 ret = defval;
838
839         for (cache_end = cache; cache_end != cache + nr; cache_end++) {
840                 struct cache_entry *ce = *cache_end;
841                 if (strncmp(ce->name, prefix->buf, prefix->len))
842                         break;
843         }
844
845         /*
846          * TODO: check el, if there are no patterns that may conflict
847          * with ret (iow, we know in advance the incl/excl
848          * decision for the entire directory), clear flag here without
849          * calling clear_ce_flags_1(). That function will call
850          * the expensive is_excluded_from_list() on every entry.
851          */
852         rc = clear_ce_flags_1(cache, cache_end - cache,
853                               prefix,
854                               select_mask, clear_mask,
855                               el, ret);
856         strbuf_setlen(prefix, prefix->len - 1);
857         return rc;
858 }
859
860 /*
861  * Traverse the index, find every entry that matches according to
862  * o->el. Do "ce_flags &= ~clear_mask" on those entries. Return the
863  * number of traversed entries.
864  *
865  * If select_mask is non-zero, only entries whose ce_flags has on of
866  * those bits enabled are traversed.
867  *
868  * cache        : pointer to an index entry
869  * prefix_len   : an offset to its path
870  *
871  * The current path ("prefix") including the trailing '/' is
872  *   cache[0]->name[0..(prefix_len-1)]
873  * Top level path has prefix_len zero.
874  */
875 static int clear_ce_flags_1(struct cache_entry **cache, int nr,
876                             struct strbuf *prefix,
877                             int select_mask, int clear_mask,
878                             struct exclude_list *el, int defval)
879 {
880         struct cache_entry **cache_end = cache + nr;
881
882         /*
883          * Process all entries that have the given prefix and meet
884          * select_mask condition
885          */
886         while(cache != cache_end) {
887                 struct cache_entry *ce = *cache;
888                 const char *name, *slash;
889                 int len, dtype, ret;
890
891                 if (select_mask && !(ce->ce_flags & select_mask)) {
892                         cache++;
893                         continue;
894                 }
895
896                 if (prefix->len && strncmp(ce->name, prefix->buf, prefix->len))
897                         break;
898
899                 name = ce->name + prefix->len;
900                 slash = strchr(name, '/');
901
902                 /* If it's a directory, try whole directory match first */
903                 if (slash) {
904                         int processed;
905
906                         len = slash - name;
907                         strbuf_add(prefix, name, len);
908
909                         processed = clear_ce_flags_dir(cache, cache_end - cache,
910                                                        prefix,
911                                                        prefix->buf + prefix->len - len,
912                                                        select_mask, clear_mask,
913                                                        el, defval);
914
915                         /* clear_c_f_dir eats a whole dir already? */
916                         if (processed) {
917                                 cache += processed;
918                                 strbuf_setlen(prefix, prefix->len - len);
919                                 continue;
920                         }
921
922                         strbuf_addch(prefix, '/');
923                         cache += clear_ce_flags_1(cache, cache_end - cache,
924                                                   prefix,
925                                                   select_mask, clear_mask, el, defval);
926                         strbuf_setlen(prefix, prefix->len - len - 1);
927                         continue;
928                 }
929
930                 /* Non-directory */
931                 dtype = ce_to_dtype(ce);
932                 ret = is_excluded_from_list(ce->name, ce_namelen(ce),
933                                             name, &dtype, el);
934                 if (ret < 0)
935                         ret = defval;
936                 if (ret > 0)
937                         ce->ce_flags &= ~clear_mask;
938                 cache++;
939         }
940         return nr - (cache_end - cache);
941 }
942
943 static int clear_ce_flags(struct cache_entry **cache, int nr,
944                             int select_mask, int clear_mask,
945                             struct exclude_list *el)
946 {
947         static struct strbuf prefix = STRBUF_INIT;
948
949         strbuf_reset(&prefix);
950
951         return clear_ce_flags_1(cache, nr,
952                                 &prefix,
953                                 select_mask, clear_mask,
954                                 el, 0);
955 }
956
957 /*
958  * Set/Clear CE_NEW_SKIP_WORKTREE according to $GIT_DIR/info/sparse-checkout
959  */
960 static void mark_new_skip_worktree(struct exclude_list *el,
961                                    struct index_state *the_index,
962                                    int select_flag, int skip_wt_flag)
963 {
964         int i;
965
966         /*
967          * 1. Pretend the narrowest worktree: only unmerged entries
968          * are checked out
969          */
970         for (i = 0; i < the_index->cache_nr; i++) {
971                 struct cache_entry *ce = the_index->cache[i];
972
973                 if (select_flag && !(ce->ce_flags & select_flag))
974                         continue;
975
976                 if (!ce_stage(ce))
977                         ce->ce_flags |= skip_wt_flag;
978                 else
979                         ce->ce_flags &= ~skip_wt_flag;
980         }
981
982         /*
983          * 2. Widen worktree according to sparse-checkout file.
984          * Matched entries will have skip_wt_flag cleared (i.e. "in")
985          */
986         clear_ce_flags(the_index->cache, the_index->cache_nr,
987                        select_flag, skip_wt_flag, el);
988 }
989
990 static int verify_absent(const struct cache_entry *,
991                          enum unpack_trees_error_types,
992                          struct unpack_trees_options *);
993 /*
994  * N-way merge "len" trees.  Returns 0 on success, -1 on failure to manipulate the
995  * resulting index, -2 on failure to reflect the changes to the work tree.
996  *
997  * CE_ADDED, CE_UNPACKED and CE_NEW_SKIP_WORKTREE are used internally
998  */
999 int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
1000 {
1001         int i, ret;
1002         static struct cache_entry *dfc;
1003         struct exclude_list el;
1004
1005         if (len > MAX_UNPACK_TREES)
1006                 die("unpack_trees takes at most %d trees", MAX_UNPACK_TREES);
1007         memset(&state, 0, sizeof(state));
1008         state.base_dir = "";
1009         state.force = 1;
1010         state.quiet = 1;
1011         state.refresh_cache = 1;
1012
1013         memset(&el, 0, sizeof(el));
1014         if (!core_apply_sparse_checkout || !o->update)
1015                 o->skip_sparse_checkout = 1;
1016         if (!o->skip_sparse_checkout) {
1017                 if (add_excludes_from_file_to_list(git_path("info/sparse-checkout"), "", 0, &el, 0) < 0)
1018                         o->skip_sparse_checkout = 1;
1019                 else
1020                         o->el = &el;
1021         }
1022
1023         memset(&o->result, 0, sizeof(o->result));
1024         o->result.initialized = 1;
1025         o->result.timestamp.sec = o->src_index->timestamp.sec;
1026         o->result.timestamp.nsec = o->src_index->timestamp.nsec;
1027         o->result.version = o->src_index->version;
1028         o->merge_size = len;
1029         mark_all_ce_unused(o->src_index);
1030
1031         /*
1032          * Sparse checkout loop #1: set NEW_SKIP_WORKTREE on existing entries
1033          */
1034         if (!o->skip_sparse_checkout)
1035                 mark_new_skip_worktree(o->el, o->src_index, 0, CE_NEW_SKIP_WORKTREE);
1036
1037         if (!dfc)
1038                 dfc = xcalloc(1, cache_entry_size(0));
1039         o->df_conflict_entry = dfc;
1040
1041         if (len) {
1042                 const char *prefix = o->prefix ? o->prefix : "";
1043                 struct traverse_info info;
1044
1045                 setup_traverse_info(&info, prefix);
1046                 info.fn = unpack_callback;
1047                 info.data = o;
1048                 info.show_all_errors = o->show_all_errors;
1049                 info.pathspec = o->pathspec;
1050
1051                 if (o->prefix) {
1052                         /*
1053                          * Unpack existing index entries that sort before the
1054                          * prefix the tree is spliced into.  Note that o->merge
1055                          * is always true in this case.
1056                          */
1057                         while (1) {
1058                                 struct cache_entry *ce = next_cache_entry(o);
1059                                 if (!ce)
1060                                         break;
1061                                 if (ce_in_traverse_path(ce, &info))
1062                                         break;
1063                                 if (unpack_index_entry(ce, o) < 0)
1064                                         goto return_failed;
1065                         }
1066                 }
1067
1068                 if (traverse_trees(len, t, &info) < 0)
1069                         goto return_failed;
1070         }
1071
1072         /* Any left-over entries in the index? */
1073         if (o->merge) {
1074                 while (1) {
1075                         struct cache_entry *ce = next_cache_entry(o);
1076                         if (!ce)
1077                                 break;
1078                         if (unpack_index_entry(ce, o) < 0)
1079                                 goto return_failed;
1080                 }
1081         }
1082         mark_all_ce_unused(o->src_index);
1083
1084         if (o->trivial_merges_only && o->nontrivial_merge) {
1085                 ret = unpack_failed(o, "Merge requires file-level merging");
1086                 goto done;
1087         }
1088
1089         if (!o->skip_sparse_checkout) {
1090                 int empty_worktree = 1;
1091
1092                 /*
1093                  * Sparse checkout loop #2: set NEW_SKIP_WORKTREE on entries not in loop #1
1094                  * If the will have NEW_SKIP_WORKTREE, also set CE_SKIP_WORKTREE
1095                  * so apply_sparse_checkout() won't attempt to remove it from worktree
1096                  */
1097                 mark_new_skip_worktree(o->el, &o->result, CE_ADDED, CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1098
1099                 ret = 0;
1100                 for (i = 0; i < o->result.cache_nr; i++) {
1101                         struct cache_entry *ce = o->result.cache[i];
1102
1103                         /*
1104                          * Entries marked with CE_ADDED in merged_entry() do not have
1105                          * verify_absent() check (the check is effectively disabled
1106                          * because CE_NEW_SKIP_WORKTREE is set unconditionally).
1107                          *
1108                          * Do the real check now because we have had
1109                          * correct CE_NEW_SKIP_WORKTREE
1110                          */
1111                         if (ce->ce_flags & CE_ADDED &&
1112                             verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
1113                                 if (!o->show_all_errors)
1114                                         goto return_failed;
1115                                 ret = -1;
1116                         }
1117
1118                         if (apply_sparse_checkout(ce, o)) {
1119                                 if (!o->show_all_errors)
1120                                         goto return_failed;
1121                                 ret = -1;
1122                         }
1123                         if (!ce_skip_worktree(ce))
1124                                 empty_worktree = 0;
1125
1126                 }
1127                 if (ret < 0)
1128                         goto return_failed;
1129                 /*
1130                  * Sparse checkout is meant to narrow down checkout area
1131                  * but it does not make sense to narrow down to empty working
1132                  * tree. This is usually a mistake in sparse checkout rules.
1133                  * Do not allow users to do that.
1134                  */
1135                 if (o->result.cache_nr && empty_worktree) {
1136                         ret = unpack_failed(o, "Sparse checkout leaves no entry on working directory");
1137                         goto done;
1138                 }
1139         }
1140
1141         o->src_index = NULL;
1142         ret = check_updates(o) ? (-2) : 0;
1143         if (o->dst_index) {
1144                 discard_index(o->dst_index);
1145                 *o->dst_index = o->result;
1146         }
1147
1148 done:
1149         clear_exclude_list(&el);
1150         return ret;
1151
1152 return_failed:
1153         if (o->show_all_errors)
1154                 display_error_msgs(o);
1155         mark_all_ce_unused(o->src_index);
1156         ret = unpack_failed(o, NULL);
1157         if (o->exiting_early)
1158                 ret = 0;
1159         goto done;
1160 }
1161
1162 /* Here come the merge functions */
1163
1164 static int reject_merge(const struct cache_entry *ce,
1165                         struct unpack_trees_options *o)
1166 {
1167         return add_rejected_path(o, ERROR_WOULD_OVERWRITE, ce->name);
1168 }
1169
1170 static int same(const struct cache_entry *a, const struct cache_entry *b)
1171 {
1172         if (!!a != !!b)
1173                 return 0;
1174         if (!a && !b)
1175                 return 1;
1176         if ((a->ce_flags | b->ce_flags) & CE_CONFLICTED)
1177                 return 0;
1178         return a->ce_mode == b->ce_mode &&
1179                !hashcmp(a->sha1, b->sha1);
1180 }
1181
1182
1183 /*
1184  * When a CE gets turned into an unmerged entry, we
1185  * want it to be up-to-date
1186  */
1187 static int verify_uptodate_1(const struct cache_entry *ce,
1188                              struct unpack_trees_options *o,
1189                              enum unpack_trees_error_types error_type)
1190 {
1191         struct stat st;
1192
1193         if (o->index_only)
1194                 return 0;
1195
1196         /*
1197          * CE_VALID and CE_SKIP_WORKTREE cheat, we better check again
1198          * if this entry is truly up-to-date because this file may be
1199          * overwritten.
1200          */
1201         if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
1202                 ; /* keep checking */
1203         else if (o->reset || ce_uptodate(ce))
1204                 return 0;
1205
1206         if (!lstat(ce->name, &st)) {
1207                 int flags = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE;
1208                 unsigned changed = ie_match_stat(o->src_index, ce, &st, flags);
1209                 if (!changed)
1210                         return 0;
1211                 /*
1212                  * NEEDSWORK: the current default policy is to allow
1213                  * submodule to be out of sync wrt the superproject
1214                  * index.  This needs to be tightened later for
1215                  * submodules that are marked to be automatically
1216                  * checked out.
1217                  */
1218                 if (S_ISGITLINK(ce->ce_mode))
1219                         return 0;
1220                 errno = 0;
1221         }
1222         if (errno == ENOENT)
1223                 return 0;
1224         return o->gently ? -1 :
1225                 add_rejected_path(o, error_type, ce->name);
1226 }
1227
1228 static int verify_uptodate(const struct cache_entry *ce,
1229                            struct unpack_trees_options *o)
1230 {
1231         if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
1232                 return 0;
1233         return verify_uptodate_1(ce, o, ERROR_NOT_UPTODATE_FILE);
1234 }
1235
1236 static int verify_uptodate_sparse(const struct cache_entry *ce,
1237                                   struct unpack_trees_options *o)
1238 {
1239         return verify_uptodate_1(ce, o, ERROR_SPARSE_NOT_UPTODATE_FILE);
1240 }
1241
1242 static void invalidate_ce_path(const struct cache_entry *ce,
1243                                struct unpack_trees_options *o)
1244 {
1245         if (ce)
1246                 cache_tree_invalidate_path(o->src_index->cache_tree, ce->name);
1247 }
1248
1249 /*
1250  * Check that checking out ce->sha1 in subdir ce->name is not
1251  * going to overwrite any working files.
1252  *
1253  * Currently, git does not checkout subprojects during a superproject
1254  * checkout, so it is not going to overwrite anything.
1255  */
1256 static int verify_clean_submodule(const struct cache_entry *ce,
1257                                   enum unpack_trees_error_types error_type,
1258                                   struct unpack_trees_options *o)
1259 {
1260         return 0;
1261 }
1262
1263 static int verify_clean_subdirectory(const struct cache_entry *ce,
1264                                      enum unpack_trees_error_types error_type,
1265                                      struct unpack_trees_options *o)
1266 {
1267         /*
1268          * we are about to extract "ce->name"; we would not want to lose
1269          * anything in the existing directory there.
1270          */
1271         int namelen;
1272         int i;
1273         struct dir_struct d;
1274         char *pathbuf;
1275         int cnt = 0;
1276         unsigned char sha1[20];
1277
1278         if (S_ISGITLINK(ce->ce_mode) &&
1279             resolve_gitlink_ref(ce->name, "HEAD", sha1) == 0) {
1280                 /* If we are not going to update the submodule, then
1281                  * we don't care.
1282                  */
1283                 if (!hashcmp(sha1, ce->sha1))
1284                         return 0;
1285                 return verify_clean_submodule(ce, error_type, o);
1286         }
1287
1288         /*
1289          * First let's make sure we do not have a local modification
1290          * in that directory.
1291          */
1292         namelen = ce_namelen(ce);
1293         for (i = locate_in_src_index(ce, o);
1294              i < o->src_index->cache_nr;
1295              i++) {
1296                 struct cache_entry *ce2 = o->src_index->cache[i];
1297                 int len = ce_namelen(ce2);
1298                 if (len < namelen ||
1299                     strncmp(ce->name, ce2->name, namelen) ||
1300                     ce2->name[namelen] != '/')
1301                         break;
1302                 /*
1303                  * ce2->name is an entry in the subdirectory to be
1304                  * removed.
1305                  */
1306                 if (!ce_stage(ce2)) {
1307                         if (verify_uptodate(ce2, o))
1308                                 return -1;
1309                         add_entry(o, ce2, CE_REMOVE, 0);
1310                         mark_ce_used(ce2, o);
1311                 }
1312                 cnt++;
1313         }
1314
1315         /*
1316          * Then we need to make sure that we do not lose a locally
1317          * present file that is not ignored.
1318          */
1319         pathbuf = xmalloc(namelen + 2);
1320         memcpy(pathbuf, ce->name, namelen);
1321         strcpy(pathbuf+namelen, "/");
1322
1323         memset(&d, 0, sizeof(d));
1324         if (o->dir)
1325                 d.exclude_per_dir = o->dir->exclude_per_dir;
1326         i = read_directory(&d, pathbuf, namelen+1, NULL);
1327         if (i)
1328                 return o->gently ? -1 :
1329                         add_rejected_path(o, ERROR_NOT_UPTODATE_DIR, ce->name);
1330         free(pathbuf);
1331         return cnt;
1332 }
1333
1334 /*
1335  * This gets called when there was no index entry for the tree entry 'dst',
1336  * but we found a file in the working tree that 'lstat()' said was fine,
1337  * and we're on a case-insensitive filesystem.
1338  *
1339  * See if we can find a case-insensitive match in the index that also
1340  * matches the stat information, and assume it's that other file!
1341  */
1342 static int icase_exists(struct unpack_trees_options *o, const char *name, int len, struct stat *st)
1343 {
1344         const struct cache_entry *src;
1345
1346         src = index_file_exists(o->src_index, name, len, 1);
1347         return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
1348 }
1349
1350 static int check_ok_to_remove(const char *name, int len, int dtype,
1351                               const struct cache_entry *ce, struct stat *st,
1352                               enum unpack_trees_error_types error_type,
1353                               struct unpack_trees_options *o)
1354 {
1355         const struct cache_entry *result;
1356
1357         /*
1358          * It may be that the 'lstat()' succeeded even though
1359          * target 'ce' was absent, because there is an old
1360          * entry that is different only in case..
1361          *
1362          * Ignore that lstat() if it matches.
1363          */
1364         if (ignore_case && icase_exists(o, name, len, st))
1365                 return 0;
1366
1367         if (o->dir &&
1368             is_excluded(o->dir, name, &dtype))
1369                 /*
1370                  * ce->name is explicitly excluded, so it is Ok to
1371                  * overwrite it.
1372                  */
1373                 return 0;
1374         if (S_ISDIR(st->st_mode)) {
1375                 /*
1376                  * We are checking out path "foo" and
1377                  * found "foo/." in the working tree.
1378                  * This is tricky -- if we have modified
1379                  * files that are in "foo/" we would lose
1380                  * them.
1381                  */
1382                 if (verify_clean_subdirectory(ce, error_type, o) < 0)
1383                         return -1;
1384                 return 0;
1385         }
1386
1387         /*
1388          * The previous round may already have decided to
1389          * delete this path, which is in a subdirectory that
1390          * is being replaced with a blob.
1391          */
1392         result = index_file_exists(&o->result, name, len, 0);
1393         if (result) {
1394                 if (result->ce_flags & CE_REMOVE)
1395                         return 0;
1396         }
1397
1398         return o->gently ? -1 :
1399                 add_rejected_path(o, error_type, name);
1400 }
1401
1402 /*
1403  * We do not want to remove or overwrite a working tree file that
1404  * is not tracked, unless it is ignored.
1405  */
1406 static int verify_absent_1(const struct cache_entry *ce,
1407                            enum unpack_trees_error_types error_type,
1408                            struct unpack_trees_options *o)
1409 {
1410         int len;
1411         struct stat st;
1412
1413         if (o->index_only || o->reset || !o->update)
1414                 return 0;
1415
1416         len = check_leading_path(ce->name, ce_namelen(ce));
1417         if (!len)
1418                 return 0;
1419         else if (len > 0) {
1420                 char path[PATH_MAX + 1];
1421                 memcpy(path, ce->name, len);
1422                 path[len] = 0;
1423                 if (lstat(path, &st))
1424                         return error("cannot stat '%s': %s", path,
1425                                         strerror(errno));
1426
1427                 return check_ok_to_remove(path, len, DT_UNKNOWN, NULL, &st,
1428                                 error_type, o);
1429         } else if (lstat(ce->name, &st)) {
1430                 if (errno != ENOENT)
1431                         return error("cannot stat '%s': %s", ce->name,
1432                                      strerror(errno));
1433                 return 0;
1434         } else {
1435                 return check_ok_to_remove(ce->name, ce_namelen(ce),
1436                                           ce_to_dtype(ce), ce, &st,
1437                                           error_type, o);
1438         }
1439 }
1440
1441 static int verify_absent(const struct cache_entry *ce,
1442                          enum unpack_trees_error_types error_type,
1443                          struct unpack_trees_options *o)
1444 {
1445         if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
1446                 return 0;
1447         return verify_absent_1(ce, error_type, o);
1448 }
1449
1450 static int verify_absent_sparse(const struct cache_entry *ce,
1451                                 enum unpack_trees_error_types error_type,
1452                                 struct unpack_trees_options *o)
1453 {
1454         enum unpack_trees_error_types orphaned_error = error_type;
1455         if (orphaned_error == ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN)
1456                 orphaned_error = ERROR_WOULD_LOSE_ORPHANED_OVERWRITTEN;
1457
1458         return verify_absent_1(ce, orphaned_error, o);
1459 }
1460
1461 static int merged_entry(const struct cache_entry *ce,
1462                         const struct cache_entry *old,
1463                         struct unpack_trees_options *o)
1464 {
1465         int update = CE_UPDATE;
1466         struct cache_entry *merge = dup_entry(ce);
1467
1468         if (!old) {
1469                 /*
1470                  * New index entries. In sparse checkout, the following
1471                  * verify_absent() will be delayed until after
1472                  * traverse_trees() finishes in unpack_trees(), then:
1473                  *
1474                  *  - CE_NEW_SKIP_WORKTREE will be computed correctly
1475                  *  - verify_absent() be called again, this time with
1476                  *    correct CE_NEW_SKIP_WORKTREE
1477                  *
1478                  * verify_absent() call here does nothing in sparse
1479                  * checkout (i.e. o->skip_sparse_checkout == 0)
1480                  */
1481                 update |= CE_ADDED;
1482                 merge->ce_flags |= CE_NEW_SKIP_WORKTREE;
1483
1484                 if (verify_absent(merge,
1485                                   ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
1486                         free(merge);
1487                         return -1;
1488                 }
1489                 invalidate_ce_path(merge, o);
1490         } else if (!(old->ce_flags & CE_CONFLICTED)) {
1491                 /*
1492                  * See if we can re-use the old CE directly?
1493                  * That way we get the uptodate stat info.
1494                  *
1495                  * This also removes the UPDATE flag on a match; otherwise
1496                  * we will end up overwriting local changes in the work tree.
1497                  */
1498                 if (same(old, merge)) {
1499                         copy_cache_entry(merge, old);
1500                         update = 0;
1501                 } else {
1502                         if (verify_uptodate(old, o)) {
1503                                 free(merge);
1504                                 return -1;
1505                         }
1506                         /* Migrate old flags over */
1507                         update |= old->ce_flags & (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1508                         invalidate_ce_path(old, o);
1509                 }
1510         } else {
1511                 /*
1512                  * Previously unmerged entry left as an existence
1513                  * marker by read_index_unmerged();
1514                  */
1515                 invalidate_ce_path(old, o);
1516         }
1517
1518         do_add_entry(o, merge, update, CE_STAGEMASK);
1519         return 1;
1520 }
1521
1522 static int deleted_entry(const struct cache_entry *ce,
1523                          const struct cache_entry *old,
1524                          struct unpack_trees_options *o)
1525 {
1526         /* Did it exist in the index? */
1527         if (!old) {
1528                 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
1529                         return -1;
1530                 return 0;
1531         }
1532         if (!(old->ce_flags & CE_CONFLICTED) && verify_uptodate(old, o))
1533                 return -1;
1534         add_entry(o, ce, CE_REMOVE, 0);
1535         invalidate_ce_path(ce, o);
1536         return 1;
1537 }
1538
1539 static int keep_entry(const struct cache_entry *ce,
1540                       struct unpack_trees_options *o)
1541 {
1542         add_entry(o, ce, 0, 0);
1543         return 1;
1544 }
1545
1546 #if DBRT_DEBUG
1547 static void show_stage_entry(FILE *o,
1548                              const char *label, const struct cache_entry *ce)
1549 {
1550         if (!ce)
1551                 fprintf(o, "%s (missing)\n", label);
1552         else
1553                 fprintf(o, "%s%06o %s %d\t%s\n",
1554                         label,
1555                         ce->ce_mode,
1556                         sha1_to_hex(ce->sha1),
1557                         ce_stage(ce),
1558                         ce->name);
1559 }
1560 #endif
1561
1562 int threeway_merge(const struct cache_entry * const *stages,
1563                    struct unpack_trees_options *o)
1564 {
1565         const struct cache_entry *index;
1566         const struct cache_entry *head;
1567         const struct cache_entry *remote = stages[o->head_idx + 1];
1568         int count;
1569         int head_match = 0;
1570         int remote_match = 0;
1571
1572         int df_conflict_head = 0;
1573         int df_conflict_remote = 0;
1574
1575         int any_anc_missing = 0;
1576         int no_anc_exists = 1;
1577         int i;
1578
1579         for (i = 1; i < o->head_idx; i++) {
1580                 if (!stages[i] || stages[i] == o->df_conflict_entry)
1581                         any_anc_missing = 1;
1582                 else
1583                         no_anc_exists = 0;
1584         }
1585
1586         index = stages[0];
1587         head = stages[o->head_idx];
1588
1589         if (head == o->df_conflict_entry) {
1590                 df_conflict_head = 1;
1591                 head = NULL;
1592         }
1593
1594         if (remote == o->df_conflict_entry) {
1595                 df_conflict_remote = 1;
1596                 remote = NULL;
1597         }
1598
1599         /*
1600          * First, if there's a #16 situation, note that to prevent #13
1601          * and #14.
1602          */
1603         if (!same(remote, head)) {
1604                 for (i = 1; i < o->head_idx; i++) {
1605                         if (same(stages[i], head)) {
1606                                 head_match = i;
1607                         }
1608                         if (same(stages[i], remote)) {
1609                                 remote_match = i;
1610                         }
1611                 }
1612         }
1613
1614         /*
1615          * We start with cases where the index is allowed to match
1616          * something other than the head: #14(ALT) and #2ALT, where it
1617          * is permitted to match the result instead.
1618          */
1619         /* #14, #14ALT, #2ALT */
1620         if (remote && !df_conflict_head && head_match && !remote_match) {
1621                 if (index && !same(index, remote) && !same(index, head))
1622                         return o->gently ? -1 : reject_merge(index, o);
1623                 return merged_entry(remote, index, o);
1624         }
1625         /*
1626          * If we have an entry in the index cache, then we want to
1627          * make sure that it matches head.
1628          */
1629         if (index && !same(index, head))
1630                 return o->gently ? -1 : reject_merge(index, o);
1631
1632         if (head) {
1633                 /* #5ALT, #15 */
1634                 if (same(head, remote))
1635                         return merged_entry(head, index, o);
1636                 /* #13, #3ALT */
1637                 if (!df_conflict_remote && remote_match && !head_match)
1638                         return merged_entry(head, index, o);
1639         }
1640
1641         /* #1 */
1642         if (!head && !remote && any_anc_missing)
1643                 return 0;
1644
1645         /*
1646          * Under the "aggressive" rule, we resolve mostly trivial
1647          * cases that we historically had git-merge-one-file resolve.
1648          */
1649         if (o->aggressive) {
1650                 int head_deleted = !head;
1651                 int remote_deleted = !remote;
1652                 const struct cache_entry *ce = NULL;
1653
1654                 if (index)
1655                         ce = index;
1656                 else if (head)
1657                         ce = head;
1658                 else if (remote)
1659                         ce = remote;
1660                 else {
1661                         for (i = 1; i < o->head_idx; i++) {
1662                                 if (stages[i] && stages[i] != o->df_conflict_entry) {
1663                                         ce = stages[i];
1664                                         break;
1665                                 }
1666                         }
1667                 }
1668
1669                 /*
1670                  * Deleted in both.
1671                  * Deleted in one and unchanged in the other.
1672                  */
1673                 if ((head_deleted && remote_deleted) ||
1674                     (head_deleted && remote && remote_match) ||
1675                     (remote_deleted && head && head_match)) {
1676                         if (index)
1677                                 return deleted_entry(index, index, o);
1678                         if (ce && !head_deleted) {
1679                                 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
1680                                         return -1;
1681                         }
1682                         return 0;
1683                 }
1684                 /*
1685                  * Added in both, identically.
1686                  */
1687                 if (no_anc_exists && head && remote && same(head, remote))
1688                         return merged_entry(head, index, o);
1689
1690         }
1691
1692         /* Below are "no merge" cases, which require that the index be
1693          * up-to-date to avoid the files getting overwritten with
1694          * conflict resolution files.
1695          */
1696         if (index) {
1697                 if (verify_uptodate(index, o))
1698                         return -1;
1699         }
1700
1701         o->nontrivial_merge = 1;
1702
1703         /* #2, #3, #4, #6, #7, #9, #10, #11. */
1704         count = 0;
1705         if (!head_match || !remote_match) {
1706                 for (i = 1; i < o->head_idx; i++) {
1707                         if (stages[i] && stages[i] != o->df_conflict_entry) {
1708                                 keep_entry(stages[i], o);
1709                                 count++;
1710                                 break;
1711                         }
1712                 }
1713         }
1714 #if DBRT_DEBUG
1715         else {
1716                 fprintf(stderr, "read-tree: warning #16 detected\n");
1717                 show_stage_entry(stderr, "head   ", stages[head_match]);
1718                 show_stage_entry(stderr, "remote ", stages[remote_match]);
1719         }
1720 #endif
1721         if (head) { count += keep_entry(head, o); }
1722         if (remote) { count += keep_entry(remote, o); }
1723         return count;
1724 }
1725
1726 /*
1727  * Two-way merge.
1728  *
1729  * The rule is to "carry forward" what is in the index without losing
1730  * information across a "fast-forward", favoring a successful merge
1731  * over a merge failure when it makes sense.  For details of the
1732  * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
1733  *
1734  */
1735 int twoway_merge(const struct cache_entry * const *src,
1736                  struct unpack_trees_options *o)
1737 {
1738         const struct cache_entry *current = src[0];
1739         const struct cache_entry *oldtree = src[1];
1740         const struct cache_entry *newtree = src[2];
1741
1742         if (o->merge_size != 2)
1743                 return error("Cannot do a twoway merge of %d trees",
1744                              o->merge_size);
1745
1746         if (oldtree == o->df_conflict_entry)
1747                 oldtree = NULL;
1748         if (newtree == o->df_conflict_entry)
1749                 newtree = NULL;
1750
1751         if (current) {
1752                 if (current->ce_flags & CE_CONFLICTED) {
1753                         if (same(oldtree, newtree) || o->reset) {
1754                                 if (!newtree)
1755                                         return deleted_entry(current, current, o);
1756                                 else
1757                                         return merged_entry(newtree, current, o);
1758                         }
1759                         return o->gently ? -1 : reject_merge(current, o);
1760                 }
1761                 else if ((!oldtree && !newtree) || /* 4 and 5 */
1762                          (!oldtree && newtree &&
1763                           same(current, newtree)) || /* 6 and 7 */
1764                          (oldtree && newtree &&
1765                           same(oldtree, newtree)) || /* 14 and 15 */
1766                          (oldtree && newtree &&
1767                           !same(oldtree, newtree) && /* 18 and 19 */
1768                           same(current, newtree))) {
1769                         return keep_entry(current, o);
1770                 }
1771                 else if (oldtree && !newtree && same(current, oldtree)) {
1772                         /* 10 or 11 */
1773                         return deleted_entry(oldtree, current, o);
1774                 }
1775                 else if (oldtree && newtree &&
1776                          same(current, oldtree) && !same(current, newtree)) {
1777                         /* 20 or 21 */
1778                         return merged_entry(newtree, current, o);
1779                 }
1780                 else {
1781                         /* all other failures */
1782                         if (oldtree)
1783                                 return o->gently ? -1 : reject_merge(oldtree, o);
1784                         if (current)
1785                                 return o->gently ? -1 : reject_merge(current, o);
1786                         if (newtree)
1787                                 return o->gently ? -1 : reject_merge(newtree, o);
1788                         return -1;
1789                 }
1790         }
1791         else if (newtree) {
1792                 if (oldtree && !o->initial_checkout) {
1793                         /*
1794                          * deletion of the path was staged;
1795                          */
1796                         if (same(oldtree, newtree))
1797                                 return 1;
1798                         return reject_merge(oldtree, o);
1799                 }
1800                 return merged_entry(newtree, current, o);
1801         }
1802         return deleted_entry(oldtree, current, o);
1803 }
1804
1805 /*
1806  * Bind merge.
1807  *
1808  * Keep the index entries at stage0, collapse stage1 but make sure
1809  * stage0 does not have anything there.
1810  */
1811 int bind_merge(const struct cache_entry * const *src,
1812                struct unpack_trees_options *o)
1813 {
1814         const struct cache_entry *old = src[0];
1815         const struct cache_entry *a = src[1];
1816
1817         if (o->merge_size != 1)
1818                 return error("Cannot do a bind merge of %d trees",
1819                              o->merge_size);
1820         if (a && old)
1821                 return o->gently ? -1 :
1822                         error(ERRORMSG(o, ERROR_BIND_OVERLAP), a->name, old->name);
1823         if (!a)
1824                 return keep_entry(old, o);
1825         else
1826                 return merged_entry(a, NULL, o);
1827 }
1828
1829 /*
1830  * One-way merge.
1831  *
1832  * The rule is:
1833  * - take the stat information from stage0, take the data from stage1
1834  */
1835 int oneway_merge(const struct cache_entry * const *src,
1836                  struct unpack_trees_options *o)
1837 {
1838         const struct cache_entry *old = src[0];
1839         const struct cache_entry *a = src[1];
1840
1841         if (o->merge_size != 1)
1842                 return error("Cannot do a oneway merge of %d trees",
1843                              o->merge_size);
1844
1845         if (!a || a == o->df_conflict_entry)
1846                 return deleted_entry(old, old, o);
1847
1848         if (old && same(old, a)) {
1849                 int update = 0;
1850                 if (o->reset && o->update && !ce_uptodate(old) && !ce_skip_worktree(old)) {
1851                         struct stat st;
1852                         if (lstat(old->name, &st) ||
1853                             ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE))
1854                                 update |= CE_UPDATE;
1855                 }
1856                 add_entry(o, old, update, 0);
1857                 return 0;
1858         }
1859         return merged_entry(a, old, o);
1860 }