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