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