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