Sync with 2.40.2
[git.git] / unpack-trees.c
blobe8c32a40dcba5e8e7cb1dc7f0661953473db350e
1 #include "cache.h"
2 #include "advice.h"
3 #include "strvec.h"
4 #include "repository.h"
5 #include "config.h"
6 #include "dir.h"
7 #include "environment.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "tree.h"
11 #include "tree-walk.h"
12 #include "cache-tree.h"
13 #include "unpack-trees.h"
14 #include "progress.h"
15 #include "refs.h"
16 #include "attr.h"
17 #include "split-index.h"
18 #include "sparse-index.h"
19 #include "submodule.h"
20 #include "submodule-config.h"
21 #include "symlinks.h"
22 #include "trace2.h"
23 #include "fsmonitor.h"
24 #include "object-store.h"
25 #include "promisor-remote.h"
26 #include "entry.h"
27 #include "parallel-checkout.h"
28 #include "setup.h"
31 * Error messages expected by scripts out of plumbing commands such as
32 * read-tree. Non-scripted Porcelain is not required to use these messages
33 * and in fact are encouraged to reword them to better suit their particular
34 * situation better. See how "git checkout" and "git merge" replaces
35 * them using setup_unpack_trees_porcelain(), for example.
37 static const char *unpack_plumbing_errors[NB_UNPACK_TREES_WARNING_TYPES] = {
38 /* ERROR_WOULD_OVERWRITE */
39 "Entry '%s' would be overwritten by merge. Cannot merge.",
41 /* ERROR_NOT_UPTODATE_FILE */
42 "Entry '%s' not uptodate. Cannot merge.",
44 /* ERROR_NOT_UPTODATE_DIR */
45 "Updating '%s' would lose untracked files in it",
47 /* ERROR_CWD_IN_THE_WAY */
48 "Refusing to remove '%s' since it is the current working directory.",
50 /* ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN */
51 "Untracked working tree file '%s' would be overwritten by merge.",
53 /* ERROR_WOULD_LOSE_UNTRACKED_REMOVED */
54 "Untracked working tree file '%s' would be removed by merge.",
56 /* ERROR_BIND_OVERLAP */
57 "Entry '%s' overlaps with '%s'. Cannot bind.",
59 /* ERROR_WOULD_LOSE_SUBMODULE */
60 "Submodule '%s' cannot checkout new HEAD.",
62 /* NB_UNPACK_TREES_ERROR_TYPES; just a meta value */
63 "",
65 /* WARNING_SPARSE_NOT_UPTODATE_FILE */
66 "Path '%s' not uptodate; will not remove from working tree.",
68 /* WARNING_SPARSE_UNMERGED_FILE */
69 "Path '%s' unmerged; will not remove from working tree.",
71 /* WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN */
72 "Path '%s' already present; will not overwrite with sparse update.",
75 #define ERRORMSG(o,type) \
76 ( ((o) && (o)->internal.msgs[(type)]) \
77 ? ((o)->internal.msgs[(type)]) \
78 : (unpack_plumbing_errors[(type)]) )
80 static const char *super_prefixed(const char *path, const char *super_prefix)
83 * It is necessary and sufficient to have two static buffers
84 * here, as the return value of this function is fed to
85 * error() using the unpack_*_errors[] templates we see above.
87 static struct strbuf buf[2] = {STRBUF_INIT, STRBUF_INIT};
88 static int super_prefix_len = -1;
89 static unsigned idx = ARRAY_SIZE(buf) - 1;
91 if (super_prefix_len < 0) {
92 if (!super_prefix) {
93 super_prefix_len = 0;
94 } else {
95 int i;
96 for (i = 0; i < ARRAY_SIZE(buf); i++)
97 strbuf_addstr(&buf[i], super_prefix);
98 super_prefix_len = buf[0].len;
102 if (!super_prefix_len)
103 return path;
105 if (++idx >= ARRAY_SIZE(buf))
106 idx = 0;
108 strbuf_setlen(&buf[idx], super_prefix_len);
109 strbuf_addstr(&buf[idx], path);
111 return buf[idx].buf;
114 void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,
115 const char *cmd)
117 int i;
118 const char **msgs = opts->internal.msgs;
119 const char *msg;
121 strvec_init(&opts->internal.msgs_to_free);
123 if (!strcmp(cmd, "checkout"))
124 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
125 ? _("Your local changes to the following files would be overwritten by checkout:\n%%s"
126 "Please commit your changes or stash them before you switch branches.")
127 : _("Your local changes to the following files would be overwritten by checkout:\n%%s");
128 else if (!strcmp(cmd, "merge"))
129 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
130 ? _("Your local changes to the following files would be overwritten by merge:\n%%s"
131 "Please commit your changes or stash them before you merge.")
132 : _("Your local changes to the following files would be overwritten by merge:\n%%s");
133 else
134 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
135 ? _("Your local changes to the following files would be overwritten by %s:\n%%s"
136 "Please commit your changes or stash them before you %s.")
137 : _("Your local changes to the following files would be overwritten by %s:\n%%s");
138 msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOT_UPTODATE_FILE] =
139 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
141 msgs[ERROR_NOT_UPTODATE_DIR] =
142 _("Updating the following directories would lose untracked files in them:\n%s");
144 msgs[ERROR_CWD_IN_THE_WAY] =
145 _("Refusing to remove the current working directory:\n%s");
147 if (!strcmp(cmd, "checkout"))
148 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
149 ? _("The following untracked working tree files would be removed by checkout:\n%%s"
150 "Please move or remove them before you switch branches.")
151 : _("The following untracked working tree files would be removed by checkout:\n%%s");
152 else if (!strcmp(cmd, "merge"))
153 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
154 ? _("The following untracked working tree files would be removed by merge:\n%%s"
155 "Please move or remove them before you merge.")
156 : _("The following untracked working tree files would be removed by merge:\n%%s");
157 else
158 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
159 ? _("The following untracked working tree files would be removed by %s:\n%%s"
160 "Please move or remove them before you %s.")
161 : _("The following untracked working tree files would be removed by %s:\n%%s");
162 msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED] =
163 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
165 if (!strcmp(cmd, "checkout"))
166 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
167 ? _("The following untracked working tree files would be overwritten by checkout:\n%%s"
168 "Please move or remove them before you switch branches.")
169 : _("The following untracked working tree files would be overwritten by checkout:\n%%s");
170 else if (!strcmp(cmd, "merge"))
171 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
172 ? _("The following untracked working tree files would be overwritten by merge:\n%%s"
173 "Please move or remove them before you merge.")
174 : _("The following untracked working tree files would be overwritten by merge:\n%%s");
175 else
176 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
177 ? _("The following untracked working tree files would be overwritten by %s:\n%%s"
178 "Please move or remove them before you %s.")
179 : _("The following untracked working tree files would be overwritten by %s:\n%%s");
180 msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN] =
181 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
184 * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
185 * cannot easily display it as a list.
187 msgs[ERROR_BIND_OVERLAP] = _("Entry '%s' overlaps with '%s'. Cannot bind.");
189 msgs[ERROR_WOULD_LOSE_SUBMODULE] =
190 _("Cannot update submodule:\n%s");
192 msgs[WARNING_SPARSE_NOT_UPTODATE_FILE] =
193 _("The following paths are not up to date and were left despite sparse patterns:\n%s");
194 msgs[WARNING_SPARSE_UNMERGED_FILE] =
195 _("The following paths are unmerged and were left despite sparse patterns:\n%s");
196 msgs[WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN] =
197 _("The following paths were already present and thus not updated despite sparse patterns:\n%s");
199 opts->internal.show_all_errors = 1;
200 /* rejected paths may not have a static buffer */
201 for (i = 0; i < ARRAY_SIZE(opts->internal.unpack_rejects); i++)
202 opts->internal.unpack_rejects[i].strdup_strings = 1;
205 void clear_unpack_trees_porcelain(struct unpack_trees_options *opts)
207 strvec_clear(&opts->internal.msgs_to_free);
208 memset(opts->internal.msgs, 0, sizeof(opts->internal.msgs));
211 static int do_add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
212 unsigned int set, unsigned int clear)
214 clear |= CE_HASHED;
216 if (set & CE_REMOVE)
217 set |= CE_WT_REMOVE;
219 ce->ce_flags = (ce->ce_flags & ~clear) | set;
220 return add_index_entry(&o->internal.result, ce,
221 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
224 static void add_entry(struct unpack_trees_options *o,
225 const struct cache_entry *ce,
226 unsigned int set, unsigned int clear)
228 do_add_entry(o, dup_cache_entry(ce, &o->internal.result), set, clear);
232 * add error messages on path <path>
233 * corresponding to the type <e> with the message <msg>
234 * indicating if it should be display in porcelain or not
236 static int add_rejected_path(struct unpack_trees_options *o,
237 enum unpack_trees_error_types e,
238 const char *path)
240 if (o->quiet)
241 return -1;
243 if (!o->internal.show_all_errors)
244 return error(ERRORMSG(o, e), super_prefixed(path,
245 o->super_prefix));
248 * Otherwise, insert in a list for future display by
249 * display_(error|warning)_msgs()
251 string_list_append(&o->internal.unpack_rejects[e], path);
252 return -1;
256 * display all the error messages stored in a nice way
258 static void display_error_msgs(struct unpack_trees_options *o)
260 int e;
261 unsigned error_displayed = 0;
262 for (e = 0; e < NB_UNPACK_TREES_ERROR_TYPES; e++) {
263 struct string_list *rejects = &o->internal.unpack_rejects[e];
265 if (rejects->nr > 0) {
266 int i;
267 struct strbuf path = STRBUF_INIT;
269 error_displayed = 1;
270 for (i = 0; i < rejects->nr; i++)
271 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
272 error(ERRORMSG(o, e), super_prefixed(path.buf,
273 o->super_prefix));
274 strbuf_release(&path);
276 string_list_clear(rejects, 0);
278 if (error_displayed)
279 fprintf(stderr, _("Aborting\n"));
283 * display all the warning messages stored in a nice way
285 static void display_warning_msgs(struct unpack_trees_options *o)
287 int e;
288 unsigned warning_displayed = 0;
289 for (e = NB_UNPACK_TREES_ERROR_TYPES + 1;
290 e < NB_UNPACK_TREES_WARNING_TYPES; e++) {
291 struct string_list *rejects = &o->internal.unpack_rejects[e];
293 if (rejects->nr > 0) {
294 int i;
295 struct strbuf path = STRBUF_INIT;
297 warning_displayed = 1;
298 for (i = 0; i < rejects->nr; i++)
299 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
300 warning(ERRORMSG(o, e), super_prefixed(path.buf,
301 o->super_prefix));
302 strbuf_release(&path);
304 string_list_clear(rejects, 0);
306 if (warning_displayed)
307 fprintf(stderr, _("After fixing the above paths, you may want to run `git sparse-checkout reapply`.\n"));
309 static int check_submodule_move_head(const struct cache_entry *ce,
310 const char *old_id,
311 const char *new_id,
312 struct unpack_trees_options *o)
314 unsigned flags = SUBMODULE_MOVE_HEAD_DRY_RUN;
315 const struct submodule *sub = submodule_from_ce(ce);
317 if (!sub)
318 return 0;
320 if (o->reset)
321 flags |= SUBMODULE_MOVE_HEAD_FORCE;
323 if (submodule_move_head(ce->name, o->super_prefix, old_id, new_id,
324 flags))
325 return add_rejected_path(o, ERROR_WOULD_LOSE_SUBMODULE, ce->name);
326 return 0;
330 * Perform the loading of the repository's gitmodules file. This function is
331 * used by 'check_update()' to perform loading of the gitmodules file in two
332 * different situations:
333 * (1) before removing entries from the working tree if the gitmodules file has
334 * been marked for removal. This situation is specified by 'state' == NULL.
335 * (2) before checking out entries to the working tree if the gitmodules file
336 * has been marked for update. This situation is specified by 'state' != NULL.
338 static void load_gitmodules_file(struct index_state *index,
339 struct checkout *state)
341 int pos = index_name_pos(index, GITMODULES_FILE, strlen(GITMODULES_FILE));
343 if (pos >= 0) {
344 struct cache_entry *ce = index->cache[pos];
345 if (!state && ce->ce_flags & CE_WT_REMOVE) {
346 repo_read_gitmodules(the_repository, 0);
347 } else if (state && (ce->ce_flags & CE_UPDATE)) {
348 submodule_free(the_repository);
349 checkout_entry(ce, state, NULL, NULL);
350 repo_read_gitmodules(the_repository, 0);
355 static struct progress *get_progress(struct unpack_trees_options *o,
356 struct index_state *index)
358 unsigned cnt = 0, total = 0;
360 if (!o->update || !o->verbose_update)
361 return NULL;
363 for (; cnt < index->cache_nr; cnt++) {
364 const struct cache_entry *ce = index->cache[cnt];
365 if (ce->ce_flags & (CE_UPDATE | CE_WT_REMOVE))
366 total++;
369 return start_delayed_progress(_("Updating files"), total);
372 static void setup_collided_checkout_detection(struct checkout *state,
373 struct index_state *index)
375 int i;
377 state->clone = 1;
378 for (i = 0; i < index->cache_nr; i++)
379 index->cache[i]->ce_flags &= ~CE_MATCHED;
382 static void report_collided_checkout(struct index_state *index)
384 struct string_list list = STRING_LIST_INIT_NODUP;
385 int i;
387 for (i = 0; i < index->cache_nr; i++) {
388 struct cache_entry *ce = index->cache[i];
390 if (!(ce->ce_flags & CE_MATCHED))
391 continue;
393 string_list_append(&list, ce->name);
394 ce->ce_flags &= ~CE_MATCHED;
397 list.cmp = fspathcmp;
398 string_list_sort(&list);
400 if (list.nr) {
401 warning(_("the following paths have collided (e.g. case-sensitive paths\n"
402 "on a case-insensitive filesystem) and only one from the same\n"
403 "colliding group is in the working tree:\n"));
405 for (i = 0; i < list.nr; i++)
406 fprintf(stderr, " '%s'\n", list.items[i].string);
409 string_list_clear(&list, 0);
412 static int must_checkout(const struct cache_entry *ce)
414 return ce->ce_flags & CE_UPDATE;
417 static int check_updates(struct unpack_trees_options *o,
418 struct index_state *index)
420 unsigned cnt = 0;
421 int errs = 0;
422 struct progress *progress;
423 struct checkout state = CHECKOUT_INIT;
424 int i, pc_workers, pc_threshold;
426 trace_performance_enter();
427 state.super_prefix = o->super_prefix;
428 state.force = 1;
429 state.quiet = 1;
430 state.refresh_cache = 1;
431 state.istate = index;
432 clone_checkout_metadata(&state.meta, &o->meta, NULL);
434 if (!o->update || o->dry_run) {
435 remove_marked_cache_entries(index, 0);
436 trace_performance_leave("check_updates");
437 return 0;
440 if (o->clone)
441 setup_collided_checkout_detection(&state, index);
443 progress = get_progress(o, index);
445 /* Start with clean cache to avoid using any possibly outdated info. */
446 invalidate_lstat_cache();
448 git_attr_set_direction(GIT_ATTR_CHECKOUT);
450 if (should_update_submodules())
451 load_gitmodules_file(index, NULL);
453 for (i = 0; i < index->cache_nr; i++) {
454 const struct cache_entry *ce = index->cache[i];
456 if (ce->ce_flags & CE_WT_REMOVE) {
457 display_progress(progress, ++cnt);
458 unlink_entry(ce, o->super_prefix);
462 remove_marked_cache_entries(index, 0);
463 remove_scheduled_dirs();
465 if (should_update_submodules())
466 load_gitmodules_file(index, &state);
468 if (repo_has_promisor_remote(the_repository))
470 * Prefetch the objects that are to be checked out in the loop
471 * below.
473 prefetch_cache_entries(index, must_checkout);
475 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
477 enable_delayed_checkout(&state);
478 if (pc_workers > 1)
479 init_parallel_checkout();
480 for (i = 0; i < index->cache_nr; i++) {
481 struct cache_entry *ce = index->cache[i];
483 if (must_checkout(ce)) {
484 size_t last_pc_queue_size = pc_queue_size();
486 if (ce->ce_flags & CE_WT_REMOVE)
487 BUG("both update and delete flags are set on %s",
488 ce->name);
489 ce->ce_flags &= ~CE_UPDATE;
490 errs |= checkout_entry(ce, &state, NULL, NULL);
492 if (last_pc_queue_size == pc_queue_size())
493 display_progress(progress, ++cnt);
496 if (pc_workers > 1)
497 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
498 progress, &cnt);
499 stop_progress(&progress);
500 errs |= finish_delayed_checkout(&state, o->verbose_update);
501 git_attr_set_direction(GIT_ATTR_CHECKIN);
503 if (o->clone)
504 report_collided_checkout(index);
506 trace_performance_leave("check_updates");
507 return errs != 0;
510 static int verify_uptodate_sparse(const struct cache_entry *ce,
511 struct unpack_trees_options *o);
512 static int verify_absent_sparse(const struct cache_entry *ce,
513 enum unpack_trees_error_types,
514 struct unpack_trees_options *o);
516 static int apply_sparse_checkout(struct index_state *istate,
517 struct cache_entry *ce,
518 struct unpack_trees_options *o)
520 int was_skip_worktree = ce_skip_worktree(ce);
522 if (ce->ce_flags & CE_NEW_SKIP_WORKTREE)
523 ce->ce_flags |= CE_SKIP_WORKTREE;
524 else
525 ce->ce_flags &= ~CE_SKIP_WORKTREE;
526 if (was_skip_worktree != ce_skip_worktree(ce)) {
527 ce->ce_flags |= CE_UPDATE_IN_BASE;
528 mark_fsmonitor_invalid(istate, ce);
529 istate->cache_changed |= CE_ENTRY_CHANGED;
533 * if (!was_skip_worktree && !ce_skip_worktree()) {
534 * This is perfectly normal. Move on;
539 * Merge strategies may set CE_UPDATE|CE_REMOVE outside checkout
540 * area as a result of ce_skip_worktree() shortcuts in
541 * verify_absent() and verify_uptodate().
542 * Make sure they don't modify worktree if they are already
543 * outside checkout area
545 if (was_skip_worktree && ce_skip_worktree(ce)) {
546 ce->ce_flags &= ~CE_UPDATE;
549 * By default, when CE_REMOVE is on, CE_WT_REMOVE is also
550 * on to get that file removed from both index and worktree.
551 * If that file is already outside worktree area, don't
552 * bother remove it.
554 if (ce->ce_flags & CE_REMOVE)
555 ce->ce_flags &= ~CE_WT_REMOVE;
558 if (!was_skip_worktree && ce_skip_worktree(ce)) {
560 * If CE_UPDATE is set, verify_uptodate() must be called already
561 * also stat info may have lost after merged_entry() so calling
562 * verify_uptodate() again may fail
564 if (!(ce->ce_flags & CE_UPDATE) &&
565 verify_uptodate_sparse(ce, o)) {
566 ce->ce_flags &= ~CE_SKIP_WORKTREE;
567 return -1;
569 ce->ce_flags |= CE_WT_REMOVE;
570 ce->ce_flags &= ~CE_UPDATE;
572 if (was_skip_worktree && !ce_skip_worktree(ce)) {
573 if (verify_absent_sparse(ce, WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN, o))
574 return -1;
575 ce->ce_flags |= CE_UPDATE;
577 return 0;
580 static int warn_conflicted_path(struct index_state *istate,
581 int i,
582 struct unpack_trees_options *o)
584 char *conflicting_path = istate->cache[i]->name;
585 int count = 0;
587 add_rejected_path(o, WARNING_SPARSE_UNMERGED_FILE, conflicting_path);
589 /* Find out how many higher stage entries are at same path */
590 while ((++count) + i < istate->cache_nr &&
591 !strcmp(conflicting_path, istate->cache[count + i]->name))
592 ; /* do nothing */
594 return count;
597 static inline int call_unpack_fn(const struct cache_entry * const *src,
598 struct unpack_trees_options *o)
600 int ret = o->fn(src, o);
601 if (ret > 0)
602 ret = 0;
603 return ret;
606 static void mark_ce_used(struct cache_entry *ce, struct unpack_trees_options *o)
608 ce->ce_flags |= CE_UNPACKED;
610 if (o->internal.cache_bottom < o->src_index->cache_nr &&
611 o->src_index->cache[o->internal.cache_bottom] == ce) {
612 int bottom = o->internal.cache_bottom;
614 while (bottom < o->src_index->cache_nr &&
615 o->src_index->cache[bottom]->ce_flags & CE_UNPACKED)
616 bottom++;
617 o->internal.cache_bottom = bottom;
621 static void mark_all_ce_unused(struct index_state *index)
623 int i;
624 for (i = 0; i < index->cache_nr; i++)
625 index->cache[i]->ce_flags &= ~(CE_UNPACKED | CE_ADDED | CE_NEW_SKIP_WORKTREE);
628 static int locate_in_src_index(const struct cache_entry *ce,
629 struct unpack_trees_options *o)
631 struct index_state *index = o->src_index;
632 int len = ce_namelen(ce);
633 int pos = index_name_pos(index, ce->name, len);
634 if (pos < 0)
635 pos = -1 - pos;
636 return pos;
640 * We call unpack_index_entry() with an unmerged cache entry
641 * only in diff-index, and it wants a single callback. Skip
642 * the other unmerged entry with the same name.
644 static void mark_ce_used_same_name(struct cache_entry *ce,
645 struct unpack_trees_options *o)
647 struct index_state *index = o->src_index;
648 int len = ce_namelen(ce);
649 int pos;
651 for (pos = locate_in_src_index(ce, o); pos < index->cache_nr; pos++) {
652 struct cache_entry *next = index->cache[pos];
653 if (len != ce_namelen(next) ||
654 memcmp(ce->name, next->name, len))
655 break;
656 mark_ce_used(next, o);
660 static struct cache_entry *next_cache_entry(struct unpack_trees_options *o)
662 const struct index_state *index = o->src_index;
663 int pos = o->internal.cache_bottom;
665 while (pos < index->cache_nr) {
666 struct cache_entry *ce = index->cache[pos];
667 if (!(ce->ce_flags & CE_UNPACKED))
668 return ce;
669 pos++;
671 return NULL;
674 static void add_same_unmerged(const struct cache_entry *ce,
675 struct unpack_trees_options *o)
677 struct index_state *index = o->src_index;
678 int len = ce_namelen(ce);
679 int pos = index_name_pos(index, ce->name, len);
681 if (0 <= pos)
682 die("programming error in a caller of mark_ce_used_same_name");
683 for (pos = -pos - 1; pos < index->cache_nr; pos++) {
684 struct cache_entry *next = index->cache[pos];
685 if (len != ce_namelen(next) ||
686 memcmp(ce->name, next->name, len))
687 break;
688 add_entry(o, next, 0, 0);
689 mark_ce_used(next, o);
693 static int unpack_index_entry(struct cache_entry *ce,
694 struct unpack_trees_options *o)
696 const struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
697 int ret;
699 src[0] = ce;
701 mark_ce_used(ce, o);
702 if (ce_stage(ce)) {
703 if (o->skip_unmerged) {
704 add_entry(o, ce, 0, 0);
705 return 0;
708 ret = call_unpack_fn(src, o);
709 if (ce_stage(ce))
710 mark_ce_used_same_name(ce, o);
711 return ret;
714 static int find_cache_pos(struct traverse_info *, const char *p, size_t len);
716 static void restore_cache_bottom(struct traverse_info *info, int bottom)
718 struct unpack_trees_options *o = info->data;
720 if (o->diff_index_cached)
721 return;
722 o->internal.cache_bottom = bottom;
725 static int switch_cache_bottom(struct traverse_info *info)
727 struct unpack_trees_options *o = info->data;
728 int ret, pos;
730 if (o->diff_index_cached)
731 return 0;
732 ret = o->internal.cache_bottom;
733 pos = find_cache_pos(info->prev, info->name, info->namelen);
735 if (pos < -1)
736 o->internal.cache_bottom = -2 - pos;
737 else if (pos < 0)
738 o->internal.cache_bottom = o->src_index->cache_nr;
739 return ret;
742 static inline int are_same_oid(struct name_entry *name_j, struct name_entry *name_k)
744 return !is_null_oid(&name_j->oid) && !is_null_oid(&name_k->oid) && oideq(&name_j->oid, &name_k->oid);
747 static int all_trees_same_as_cache_tree(int n, unsigned long dirmask,
748 struct name_entry *names,
749 struct traverse_info *info)
751 struct unpack_trees_options *o = info->data;
752 int i;
754 if (!o->merge || dirmask != ((1 << n) - 1))
755 return 0;
757 for (i = 1; i < n; i++)
758 if (!are_same_oid(names, names + i))
759 return 0;
761 return cache_tree_matches_traversal(o->src_index->cache_tree, names, info);
764 static int index_pos_by_traverse_info(struct name_entry *names,
765 struct traverse_info *info)
767 struct unpack_trees_options *o = info->data;
768 struct strbuf name = STRBUF_INIT;
769 int pos;
771 strbuf_make_traverse_path(&name, info, names->path, names->pathlen);
772 strbuf_addch(&name, '/');
773 pos = index_name_pos(o->src_index, name.buf, name.len);
774 if (pos >= 0) {
775 if (!o->src_index->sparse_index ||
776 !(o->src_index->cache[pos]->ce_flags & CE_SKIP_WORKTREE))
777 BUG("This is a directory and should not exist in index");
778 } else {
779 pos = -pos - 1;
781 if (pos >= o->src_index->cache_nr ||
782 !starts_with(o->src_index->cache[pos]->name, name.buf) ||
783 (pos > 0 && starts_with(o->src_index->cache[pos-1]->name, name.buf)))
784 BUG("pos %d doesn't point to the first entry of %s in index",
785 pos, name.buf);
786 strbuf_release(&name);
787 return pos;
791 * Fast path if we detect that all trees are the same as cache-tree at this
792 * path. We'll walk these trees in an iterative loop using cache-tree/index
793 * instead of ODB since we already know what these trees contain.
795 static int traverse_by_cache_tree(int pos, int nr_entries, int nr_names,
796 struct traverse_info *info)
798 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
799 struct unpack_trees_options *o = info->data;
800 struct cache_entry *tree_ce = NULL;
801 int ce_len = 0;
802 int i, d;
804 if (!o->merge)
805 BUG("We need cache-tree to do this optimization");
808 * Do what unpack_callback() and unpack_single_entry() normally
809 * do. But we walk all paths in an iterative loop instead.
811 * D/F conflicts and higher stage entries are not a concern
812 * because cache-tree would be invalidated and we would never
813 * get here in the first place.
815 for (i = 0; i < nr_entries; i++) {
816 int new_ce_len, len, rc;
818 src[0] = o->src_index->cache[pos + i];
820 len = ce_namelen(src[0]);
821 new_ce_len = cache_entry_size(len);
823 if (new_ce_len > ce_len) {
824 new_ce_len <<= 1;
825 tree_ce = xrealloc(tree_ce, new_ce_len);
826 memset(tree_ce, 0, new_ce_len);
827 ce_len = new_ce_len;
829 tree_ce->ce_flags = create_ce_flags(0);
831 for (d = 1; d <= nr_names; d++)
832 src[d] = tree_ce;
835 tree_ce->ce_mode = src[0]->ce_mode;
836 tree_ce->ce_namelen = len;
837 oidcpy(&tree_ce->oid, &src[0]->oid);
838 memcpy(tree_ce->name, src[0]->name, len + 1);
840 rc = call_unpack_fn((const struct cache_entry * const *)src, o);
841 if (rc < 0) {
842 free(tree_ce);
843 return rc;
846 mark_ce_used(src[0], o);
848 free(tree_ce);
849 if (o->internal.debug_unpack)
850 printf("Unpacked %d entries from %s to %s using cache-tree\n",
851 nr_entries,
852 o->src_index->cache[pos]->name,
853 o->src_index->cache[pos + nr_entries - 1]->name);
854 return 0;
857 static int traverse_trees_recursive(int n, unsigned long dirmask,
858 unsigned long df_conflicts,
859 struct name_entry *names,
860 struct traverse_info *info)
862 struct unpack_trees_options *o = info->data;
863 int i, ret, bottom;
864 int nr_buf = 0;
865 struct tree_desc t[MAX_UNPACK_TREES];
866 void *buf[MAX_UNPACK_TREES];
867 struct traverse_info newinfo;
868 struct name_entry *p;
869 int nr_entries;
871 nr_entries = all_trees_same_as_cache_tree(n, dirmask, names, info);
872 if (nr_entries > 0) {
873 int pos = index_pos_by_traverse_info(names, info);
875 if (!o->merge || df_conflicts)
876 BUG("Wrong condition to get here buddy");
879 * All entries up to 'pos' must have been processed
880 * (i.e. marked CE_UNPACKED) at this point. But to be safe,
881 * save and restore cache_bottom anyway to not miss
882 * unprocessed entries before 'pos'.
884 bottom = o->internal.cache_bottom;
885 ret = traverse_by_cache_tree(pos, nr_entries, n, info);
886 o->internal.cache_bottom = bottom;
887 return ret;
890 p = names;
891 while (!p->mode)
892 p++;
894 newinfo = *info;
895 newinfo.prev = info;
896 newinfo.pathspec = info->pathspec;
897 newinfo.name = p->path;
898 newinfo.namelen = p->pathlen;
899 newinfo.mode = p->mode;
900 newinfo.pathlen = st_add3(newinfo.pathlen, tree_entry_len(p), 1);
901 newinfo.df_conflicts |= df_conflicts;
904 * Fetch the tree from the ODB for each peer directory in the
905 * n commits.
907 * For 2- and 3-way traversals, we try to avoid hitting the
908 * ODB twice for the same OID. This should yield a nice speed
909 * up in checkouts and merges when the commits are similar.
911 * We don't bother doing the full O(n^2) search for larger n,
912 * because wider traversals don't happen that often and we
913 * avoid the search setup.
915 * When 2 peer OIDs are the same, we just copy the tree
916 * descriptor data. This implicitly borrows the buffer
917 * data from the earlier cell.
919 for (i = 0; i < n; i++, dirmask >>= 1) {
920 if (i > 0 && are_same_oid(&names[i], &names[i - 1]))
921 t[i] = t[i - 1];
922 else if (i > 1 && are_same_oid(&names[i], &names[i - 2]))
923 t[i] = t[i - 2];
924 else {
925 const struct object_id *oid = NULL;
926 if (dirmask & 1)
927 oid = &names[i].oid;
928 buf[nr_buf++] = fill_tree_descriptor(the_repository, t + i, oid);
932 bottom = switch_cache_bottom(&newinfo);
933 ret = traverse_trees(o->src_index, n, t, &newinfo);
934 restore_cache_bottom(&newinfo, bottom);
936 for (i = 0; i < nr_buf; i++)
937 free(buf[i]);
939 return ret;
943 * Compare the traverse-path to the cache entry without actually
944 * having to generate the textual representation of the traverse
945 * path.
947 * NOTE! This *only* compares up to the size of the traverse path
948 * itself - the caller needs to do the final check for the cache
949 * entry having more data at the end!
951 static int do_compare_entry_piecewise(const struct cache_entry *ce,
952 const struct traverse_info *info,
953 const char *name, size_t namelen,
954 unsigned mode)
956 int pathlen, ce_len;
957 const char *ce_name;
959 if (info->prev) {
960 int cmp = do_compare_entry_piecewise(ce, info->prev,
961 info->name, info->namelen,
962 info->mode);
963 if (cmp)
964 return cmp;
966 pathlen = info->pathlen;
967 ce_len = ce_namelen(ce);
969 /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
970 if (ce_len < pathlen)
971 return -1;
973 ce_len -= pathlen;
974 ce_name = ce->name + pathlen;
976 return df_name_compare(ce_name, ce_len, S_IFREG, name, namelen, mode);
979 static int do_compare_entry(const struct cache_entry *ce,
980 const struct traverse_info *info,
981 const char *name, size_t namelen,
982 unsigned mode)
984 int pathlen, ce_len;
985 const char *ce_name;
986 int cmp;
987 unsigned ce_mode;
990 * If we have not precomputed the traverse path, it is quicker
991 * to avoid doing so. But if we have precomputed it,
992 * it is quicker to use the precomputed version.
994 if (!info->traverse_path)
995 return do_compare_entry_piecewise(ce, info, name, namelen, mode);
997 cmp = strncmp(ce->name, info->traverse_path, info->pathlen);
998 if (cmp)
999 return cmp;
1001 pathlen = info->pathlen;
1002 ce_len = ce_namelen(ce);
1004 if (ce_len < pathlen)
1005 return -1;
1007 ce_len -= pathlen;
1008 ce_name = ce->name + pathlen;
1010 ce_mode = S_ISSPARSEDIR(ce->ce_mode) ? S_IFDIR : S_IFREG;
1011 return df_name_compare(ce_name, ce_len, ce_mode, name, namelen, mode);
1014 static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
1016 int cmp = do_compare_entry(ce, info, n->path, n->pathlen, n->mode);
1017 if (cmp)
1018 return cmp;
1021 * At this point, we know that we have a prefix match. If ce
1022 * is a sparse directory, then allow an exact match. This only
1023 * works when the input name is a directory, since ce->name
1024 * ends in a directory separator.
1026 if (S_ISSPARSEDIR(ce->ce_mode) &&
1027 ce->ce_namelen == traverse_path_len(info, tree_entry_len(n)) + 1)
1028 return 0;
1031 * Even if the beginning compared identically, the ce should
1032 * compare as bigger than a directory leading up to it!
1034 return ce_namelen(ce) > traverse_path_len(info, tree_entry_len(n));
1037 static int ce_in_traverse_path(const struct cache_entry *ce,
1038 const struct traverse_info *info)
1040 if (!info->prev)
1041 return 1;
1042 if (do_compare_entry(ce, info->prev,
1043 info->name, info->namelen, info->mode))
1044 return 0;
1046 * If ce (blob) is the same name as the path (which is a tree
1047 * we will be descending into), it won't be inside it.
1049 return (info->pathlen < ce_namelen(ce));
1052 static struct cache_entry *create_ce_entry(const struct traverse_info *info,
1053 const struct name_entry *n,
1054 int stage,
1055 struct index_state *istate,
1056 int is_transient,
1057 int is_sparse_directory)
1059 size_t len = traverse_path_len(info, tree_entry_len(n));
1060 size_t alloc_len = is_sparse_directory ? len + 1 : len;
1061 struct cache_entry *ce =
1062 is_transient ?
1063 make_empty_transient_cache_entry(alloc_len, NULL) :
1064 make_empty_cache_entry(istate, alloc_len);
1066 ce->ce_mode = create_ce_mode(n->mode);
1067 ce->ce_flags = create_ce_flags(stage);
1068 ce->ce_namelen = len;
1069 oidcpy(&ce->oid, &n->oid);
1070 /* len+1 because the cache_entry allocates space for NUL */
1071 make_traverse_path(ce->name, len + 1, info, n->path, n->pathlen);
1073 if (is_sparse_directory) {
1074 ce->name[len] = '/';
1075 ce->name[len + 1] = '\0';
1076 ce->ce_namelen++;
1077 ce->ce_flags |= CE_SKIP_WORKTREE;
1080 return ce;
1084 * Determine whether the path specified by 'p' should be unpacked as a new
1085 * sparse directory in a sparse index. A new sparse directory 'A/':
1086 * - must be outside the sparse cone.
1087 * - must not already be in the index (i.e., no index entry with name 'A/'
1088 * exists).
1089 * - must not have any child entries in the index (i.e., no index entry
1090 * 'A/<something>' exists).
1091 * If 'p' meets the above requirements, return 1; otherwise, return 0.
1093 static int entry_is_new_sparse_dir(const struct traverse_info *info,
1094 const struct name_entry *p)
1096 int res, pos;
1097 struct strbuf dirpath = STRBUF_INIT;
1098 struct unpack_trees_options *o = info->data;
1100 if (!S_ISDIR(p->mode))
1101 return 0;
1104 * If the path is inside the sparse cone, it can't be a sparse directory.
1106 strbuf_add(&dirpath, info->traverse_path, info->pathlen);
1107 strbuf_add(&dirpath, p->path, p->pathlen);
1108 strbuf_addch(&dirpath, '/');
1109 if (path_in_cone_mode_sparse_checkout(dirpath.buf, o->src_index)) {
1110 res = 0;
1111 goto cleanup;
1114 pos = index_name_pos_sparse(o->src_index, dirpath.buf, dirpath.len);
1115 if (pos >= 0) {
1116 /* Path is already in the index, not a new sparse dir */
1117 res = 0;
1118 goto cleanup;
1121 /* Where would this sparse dir be inserted into the index? */
1122 pos = -pos - 1;
1123 if (pos >= o->src_index->cache_nr) {
1125 * Sparse dir would be inserted at the end of the index, so we
1126 * know it has no child entries.
1128 res = 1;
1129 goto cleanup;
1133 * If the dir has child entries in the index, the first would be at the
1134 * position the sparse directory would be inserted. If the entry at this
1135 * position is inside the dir, not a new sparse dir.
1137 res = strncmp(o->src_index->cache[pos]->name, dirpath.buf, dirpath.len);
1139 cleanup:
1140 strbuf_release(&dirpath);
1141 return res;
1145 * Note that traverse_by_cache_tree() duplicates some logic in this function
1146 * without actually calling it. If you change the logic here you may need to
1147 * check and change there as well.
1149 static int unpack_single_entry(int n, unsigned long mask,
1150 unsigned long dirmask,
1151 struct cache_entry **src,
1152 const struct name_entry *names,
1153 const struct traverse_info *info,
1154 int *is_new_sparse_dir)
1156 int i;
1157 struct unpack_trees_options *o = info->data;
1158 unsigned long conflicts = info->df_conflicts | dirmask;
1159 const struct name_entry *p = names;
1161 *is_new_sparse_dir = 0;
1162 if (mask == dirmask && !src[0]) {
1164 * If we're not in a sparse index, we can't unpack a directory
1165 * without recursing into it, so we return.
1167 if (!o->src_index->sparse_index)
1168 return 0;
1170 /* Find first entry with a real name (we could use "mask" too) */
1171 while (!p->mode)
1172 p++;
1175 * If the directory is completely missing from the index but
1176 * would otherwise be a sparse directory, we should unpack it.
1177 * If not, we'll return and continue recursively traversing the
1178 * tree.
1180 *is_new_sparse_dir = entry_is_new_sparse_dir(info, p);
1181 if (!*is_new_sparse_dir)
1182 return 0;
1186 * When we are unpacking a sparse directory, then this isn't necessarily
1187 * a directory-file conflict.
1189 if (mask == dirmask &&
1190 (*is_new_sparse_dir || (src[0] && S_ISSPARSEDIR(src[0]->ce_mode))))
1191 conflicts = 0;
1194 * Ok, we've filled in up to any potential index entry in src[0],
1195 * now do the rest.
1197 for (i = 0; i < n; i++) {
1198 int stage;
1199 unsigned int bit = 1ul << i;
1200 if (conflicts & bit) {
1201 src[i + o->merge] = o->df_conflict_entry;
1202 continue;
1204 if (!(mask & bit))
1205 continue;
1206 if (!o->merge)
1207 stage = 0;
1208 else if (i + 1 < o->head_idx)
1209 stage = 1;
1210 else if (i + 1 > o->head_idx)
1211 stage = 3;
1212 else
1213 stage = 2;
1216 * If the merge bit is set, then the cache entries are
1217 * discarded in the following block. In this case,
1218 * construct "transient" cache_entries, as they are
1219 * not stored in the index. otherwise construct the
1220 * cache entry from the index aware logic.
1222 src[i + o->merge] = create_ce_entry(info, names + i, stage,
1223 &o->internal.result,
1224 o->merge, bit & dirmask);
1227 if (o->merge) {
1228 int rc = call_unpack_fn((const struct cache_entry * const *)src,
1230 for (i = 0; i < n; i++) {
1231 struct cache_entry *ce = src[i + o->merge];
1232 if (ce != o->df_conflict_entry)
1233 discard_cache_entry(ce);
1235 return rc;
1238 for (i = 0; i < n; i++)
1239 if (src[i] && src[i] != o->df_conflict_entry)
1240 if (do_add_entry(o, src[i], 0, 0))
1241 return -1;
1243 return 0;
1246 static int unpack_failed(struct unpack_trees_options *o, const char *message)
1248 discard_index(&o->internal.result);
1249 if (!o->quiet && !o->exiting_early) {
1250 if (message)
1251 return error("%s", message);
1252 return -1;
1254 return -1;
1258 * The tree traversal is looking at name p. If we have a matching entry,
1259 * return it. If name p is a directory in the index, do not return
1260 * anything, as we will want to match it when the traversal descends into
1261 * the directory.
1263 static int find_cache_pos(struct traverse_info *info,
1264 const char *p, size_t p_len)
1266 int pos;
1267 struct unpack_trees_options *o = info->data;
1268 struct index_state *index = o->src_index;
1269 int pfxlen = info->pathlen;
1271 for (pos = o->internal.cache_bottom; pos < index->cache_nr; pos++) {
1272 const struct cache_entry *ce = index->cache[pos];
1273 const char *ce_name, *ce_slash;
1274 int cmp, ce_len;
1276 if (ce->ce_flags & CE_UNPACKED) {
1278 * cache_bottom entry is already unpacked, so
1279 * we can never match it; don't check it
1280 * again.
1282 if (pos == o->internal.cache_bottom)
1283 ++o->internal.cache_bottom;
1284 continue;
1286 if (!ce_in_traverse_path(ce, info)) {
1288 * Check if we can skip future cache checks
1289 * (because we're already past all possible
1290 * entries in the traverse path).
1292 if (info->traverse_path) {
1293 if (strncmp(ce->name, info->traverse_path,
1294 info->pathlen) > 0)
1295 break;
1297 continue;
1299 ce_name = ce->name + pfxlen;
1300 ce_slash = strchr(ce_name, '/');
1301 if (ce_slash)
1302 ce_len = ce_slash - ce_name;
1303 else
1304 ce_len = ce_namelen(ce) - pfxlen;
1305 cmp = name_compare(p, p_len, ce_name, ce_len);
1307 * Exact match; if we have a directory we need to
1308 * delay returning it.
1310 if (!cmp)
1311 return ce_slash ? -2 - pos : pos;
1312 if (0 < cmp)
1313 continue; /* keep looking */
1315 * ce_name sorts after p->path; could it be that we
1316 * have files under p->path directory in the index?
1317 * E.g. ce_name == "t-i", and p->path == "t"; we may
1318 * have "t/a" in the index.
1320 if (p_len < ce_len && !memcmp(ce_name, p, p_len) &&
1321 ce_name[p_len] < '/')
1322 continue; /* keep looking */
1323 break;
1325 return -1;
1329 * Given a sparse directory entry 'ce', compare ce->name to
1330 * info->traverse_path + p->path + '/' if info->traverse_path
1331 * is non-empty.
1333 * Compare ce->name to p->path + '/' otherwise. Note that
1334 * ce->name must end in a trailing '/' because it is a sparse
1335 * directory entry.
1337 static int sparse_dir_matches_path(const struct cache_entry *ce,
1338 struct traverse_info *info,
1339 const struct name_entry *p)
1341 assert(S_ISSPARSEDIR(ce->ce_mode));
1342 assert(ce->name[ce->ce_namelen - 1] == '/');
1344 if (info->pathlen)
1345 return ce->ce_namelen == info->pathlen + p->pathlen + 1 &&
1346 ce->name[info->pathlen - 1] == '/' &&
1347 !strncmp(ce->name, info->traverse_path, info->pathlen) &&
1348 !strncmp(ce->name + info->pathlen, p->path, p->pathlen);
1349 return ce->ce_namelen == p->pathlen + 1 &&
1350 !strncmp(ce->name, p->path, p->pathlen);
1353 static struct cache_entry *find_cache_entry(struct traverse_info *info,
1354 const struct name_entry *p)
1356 const char *path;
1357 int pos = find_cache_pos(info, p->path, p->pathlen);
1358 struct unpack_trees_options *o = info->data;
1360 if (0 <= pos)
1361 return o->src_index->cache[pos];
1364 * Check for a sparse-directory entry named "path/".
1365 * Due to the input p->path not having a trailing
1366 * slash, the negative 'pos' value overshoots the
1367 * expected position, hence "-2" instead of "-1".
1369 pos = -pos - 2;
1371 if (pos < 0 || pos >= o->src_index->cache_nr)
1372 return NULL;
1375 * Due to lexicographic sorting and sparse directory
1376 * entries ending with a trailing slash, our path as a
1377 * sparse directory (e.g "subdir/") and our path as a
1378 * file (e.g. "subdir") might be separated by other
1379 * paths (e.g. "subdir-").
1381 while (pos >= 0) {
1382 struct cache_entry *ce = o->src_index->cache[pos];
1384 if (!skip_prefix(ce->name, info->traverse_path, &path) ||
1385 strncmp(path, p->path, p->pathlen) ||
1386 path[p->pathlen] != '/')
1387 return NULL;
1389 if (S_ISSPARSEDIR(ce->ce_mode) &&
1390 sparse_dir_matches_path(ce, info, p))
1391 return ce;
1393 pos--;
1396 return NULL;
1399 static void debug_path(struct traverse_info *info)
1401 if (info->prev) {
1402 debug_path(info->prev);
1403 if (*info->prev->name)
1404 putchar('/');
1406 printf("%s", info->name);
1409 static void debug_name_entry(int i, struct name_entry *n)
1411 printf("ent#%d %06o %s\n", i,
1412 n->path ? n->mode : 0,
1413 n->path ? n->path : "(missing)");
1416 static void debug_unpack_callback(int n,
1417 unsigned long mask,
1418 unsigned long dirmask,
1419 struct name_entry *names,
1420 struct traverse_info *info)
1422 int i;
1423 printf("* unpack mask %lu, dirmask %lu, cnt %d ",
1424 mask, dirmask, n);
1425 debug_path(info);
1426 putchar('\n');
1427 for (i = 0; i < n; i++)
1428 debug_name_entry(i, names + i);
1432 * Returns true if and only if the given cache_entry is a
1433 * sparse-directory entry that matches the given name_entry
1434 * from the tree walk at the given traverse_info.
1436 static int is_sparse_directory_entry(struct cache_entry *ce,
1437 const struct name_entry *name,
1438 struct traverse_info *info)
1440 if (!ce || !name || !S_ISSPARSEDIR(ce->ce_mode))
1441 return 0;
1443 return sparse_dir_matches_path(ce, info, name);
1446 static int unpack_sparse_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1448 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1449 struct unpack_trees_options *o = info->data;
1450 int ret, is_new_sparse_dir;
1452 assert(o->merge);
1455 * Unlike in 'unpack_callback', where src[0] is derived from the index when
1456 * merging, src[0] is a transient cache entry derived from the first tree
1457 * provided. Create the temporary entry as if it came from a non-sparse index.
1459 if (!is_null_oid(&names[0].oid)) {
1460 src[0] = create_ce_entry(info, &names[0], 0,
1461 &o->internal.result, 1,
1462 dirmask & (1ul << 0));
1463 src[0]->ce_flags |= (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1467 * 'unpack_single_entry' assumes that src[0] is derived directly from
1468 * the index, rather than from an entry in 'names'. This is *not* true when
1469 * merging a sparse directory, in which case names[0] is the "index" source
1470 * entry. To match the expectations of 'unpack_single_entry', shift past the
1471 * "index" tree (i.e., names[0]) and adjust 'names', 'n', 'mask', and
1472 * 'dirmask' accordingly.
1474 ret = unpack_single_entry(n - 1, mask >> 1, dirmask >> 1, src, names + 1, info, &is_new_sparse_dir);
1476 if (src[0])
1477 discard_cache_entry(src[0]);
1479 return ret >= 0 ? mask : -1;
1483 * Note that traverse_by_cache_tree() duplicates some logic in this function
1484 * without actually calling it. If you change the logic here you may need to
1485 * check and change there as well.
1487 static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1489 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1490 struct unpack_trees_options *o = info->data;
1491 const struct name_entry *p = names;
1492 int is_new_sparse_dir;
1494 /* Find first entry with a real name (we could use "mask" too) */
1495 while (!p->mode)
1496 p++;
1498 if (o->internal.debug_unpack)
1499 debug_unpack_callback(n, mask, dirmask, names, info);
1501 /* Are we supposed to look at the index too? */
1502 if (o->merge) {
1503 while (1) {
1504 int cmp;
1505 struct cache_entry *ce;
1507 if (o->diff_index_cached)
1508 ce = next_cache_entry(o);
1509 else
1510 ce = find_cache_entry(info, p);
1512 if (!ce)
1513 break;
1514 cmp = compare_entry(ce, info, p);
1515 if (cmp < 0) {
1516 if (unpack_index_entry(ce, o) < 0)
1517 return unpack_failed(o, NULL);
1518 continue;
1520 if (!cmp) {
1521 if (ce_stage(ce)) {
1523 * If we skip unmerged index
1524 * entries, we'll skip this
1525 * entry *and* the tree
1526 * entries associated with it!
1528 if (o->skip_unmerged) {
1529 add_same_unmerged(ce, o);
1530 return mask;
1533 src[0] = ce;
1535 break;
1539 if (unpack_single_entry(n, mask, dirmask, src, names, info, &is_new_sparse_dir))
1540 return -1;
1542 if (o->merge && src[0]) {
1543 if (ce_stage(src[0]))
1544 mark_ce_used_same_name(src[0], o);
1545 else
1546 mark_ce_used(src[0], o);
1549 /* Now handle any directories.. */
1550 if (dirmask) {
1551 /* special case: "diff-index --cached" looking at a tree */
1552 if (o->diff_index_cached &&
1553 n == 1 && dirmask == 1 && S_ISDIR(names->mode)) {
1554 int matches;
1555 matches = cache_tree_matches_traversal(o->src_index->cache_tree,
1556 names, info);
1558 * Everything under the name matches; skip the
1559 * entire hierarchy. diff_index_cached codepath
1560 * special cases D/F conflicts in such a way that
1561 * it does not do any look-ahead, so this is safe.
1563 if (matches) {
1565 * Only increment the cache_bottom if the
1566 * directory isn't a sparse directory index
1567 * entry (if it is, it was already incremented)
1568 * in 'mark_ce_used()'
1570 if (!src[0] || !S_ISSPARSEDIR(src[0]->ce_mode))
1571 o->internal.cache_bottom += matches;
1572 return mask;
1576 if (!is_sparse_directory_entry(src[0], p, info) &&
1577 !is_new_sparse_dir &&
1578 traverse_trees_recursive(n, dirmask, mask & ~dirmask,
1579 names, info) < 0) {
1580 return -1;
1583 return mask;
1586 return mask;
1589 static int clear_ce_flags_1(struct index_state *istate,
1590 struct cache_entry **cache, int nr,
1591 struct strbuf *prefix,
1592 int select_mask, int clear_mask,
1593 struct pattern_list *pl,
1594 enum pattern_match_result default_match,
1595 int progress_nr);
1597 /* Whole directory matching */
1598 static int clear_ce_flags_dir(struct index_state *istate,
1599 struct cache_entry **cache, int nr,
1600 struct strbuf *prefix,
1601 char *basename,
1602 int select_mask, int clear_mask,
1603 struct pattern_list *pl,
1604 enum pattern_match_result default_match,
1605 int progress_nr)
1607 struct cache_entry **cache_end;
1608 int dtype = DT_DIR;
1609 int rc;
1610 enum pattern_match_result ret, orig_ret;
1611 orig_ret = path_matches_pattern_list(prefix->buf, prefix->len,
1612 basename, &dtype, pl, istate);
1614 strbuf_addch(prefix, '/');
1616 /* If undecided, use matching result of parent dir in defval */
1617 if (orig_ret == UNDECIDED)
1618 ret = default_match;
1619 else
1620 ret = orig_ret;
1622 for (cache_end = cache; cache_end != cache + nr; cache_end++) {
1623 struct cache_entry *ce = *cache_end;
1624 if (strncmp(ce->name, prefix->buf, prefix->len))
1625 break;
1628 if (pl->use_cone_patterns && orig_ret == MATCHED_RECURSIVE) {
1629 struct cache_entry **ce = cache;
1630 rc = cache_end - cache;
1632 while (ce < cache_end) {
1633 (*ce)->ce_flags &= ~clear_mask;
1634 ce++;
1636 } else if (pl->use_cone_patterns && orig_ret == NOT_MATCHED) {
1637 rc = cache_end - cache;
1638 } else {
1639 rc = clear_ce_flags_1(istate, cache, cache_end - cache,
1640 prefix,
1641 select_mask, clear_mask,
1642 pl, ret,
1643 progress_nr);
1646 strbuf_setlen(prefix, prefix->len - 1);
1647 return rc;
1651 * Traverse the index, find every entry that matches according to
1652 * o->pl. Do "ce_flags &= ~clear_mask" on those entries. Return the
1653 * number of traversed entries.
1655 * If select_mask is non-zero, only entries whose ce_flags has on of
1656 * those bits enabled are traversed.
1658 * cache : pointer to an index entry
1659 * prefix_len : an offset to its path
1661 * The current path ("prefix") including the trailing '/' is
1662 * cache[0]->name[0..(prefix_len-1)]
1663 * Top level path has prefix_len zero.
1665 static int clear_ce_flags_1(struct index_state *istate,
1666 struct cache_entry **cache, int nr,
1667 struct strbuf *prefix,
1668 int select_mask, int clear_mask,
1669 struct pattern_list *pl,
1670 enum pattern_match_result default_match,
1671 int progress_nr)
1673 struct cache_entry **cache_end = nr ? cache + nr : cache;
1676 * Process all entries that have the given prefix and meet
1677 * select_mask condition
1679 while(cache != cache_end) {
1680 struct cache_entry *ce = *cache;
1681 const char *name, *slash;
1682 int len, dtype;
1683 enum pattern_match_result ret;
1685 display_progress(istate->progress, progress_nr);
1687 if (select_mask && !(ce->ce_flags & select_mask)) {
1688 cache++;
1689 progress_nr++;
1690 continue;
1693 if (prefix->len && strncmp(ce->name, prefix->buf, prefix->len))
1694 break;
1696 name = ce->name + prefix->len;
1697 slash = strchr(name, '/');
1699 /* If it's a directory, try whole directory match first */
1700 if (slash) {
1701 int processed;
1703 len = slash - name;
1704 strbuf_add(prefix, name, len);
1706 processed = clear_ce_flags_dir(istate, cache, cache_end - cache,
1707 prefix,
1708 prefix->buf + prefix->len - len,
1709 select_mask, clear_mask,
1710 pl, default_match,
1711 progress_nr);
1713 /* clear_c_f_dir eats a whole dir already? */
1714 if (processed) {
1715 cache += processed;
1716 progress_nr += processed;
1717 strbuf_setlen(prefix, prefix->len - len);
1718 continue;
1721 strbuf_addch(prefix, '/');
1722 processed = clear_ce_flags_1(istate, cache, cache_end - cache,
1723 prefix,
1724 select_mask, clear_mask, pl,
1725 default_match, progress_nr);
1727 cache += processed;
1728 progress_nr += processed;
1730 strbuf_setlen(prefix, prefix->len - len - 1);
1731 continue;
1734 /* Non-directory */
1735 dtype = ce_to_dtype(ce);
1736 ret = path_matches_pattern_list(ce->name,
1737 ce_namelen(ce),
1738 name, &dtype, pl, istate);
1739 if (ret == UNDECIDED)
1740 ret = default_match;
1741 if (ret == MATCHED || ret == MATCHED_RECURSIVE)
1742 ce->ce_flags &= ~clear_mask;
1743 cache++;
1744 progress_nr++;
1747 display_progress(istate->progress, progress_nr);
1748 return nr - (cache_end - cache);
1751 static int clear_ce_flags(struct index_state *istate,
1752 int select_mask, int clear_mask,
1753 struct pattern_list *pl,
1754 int show_progress)
1756 static struct strbuf prefix = STRBUF_INIT;
1757 char label[100];
1758 int rval;
1760 strbuf_reset(&prefix);
1761 if (show_progress)
1762 istate->progress = start_delayed_progress(
1763 _("Updating index flags"),
1764 istate->cache_nr);
1766 xsnprintf(label, sizeof(label), "clear_ce_flags(0x%08lx,0x%08lx)",
1767 (unsigned long)select_mask, (unsigned long)clear_mask);
1768 trace2_region_enter("unpack_trees", label, the_repository);
1769 rval = clear_ce_flags_1(istate,
1770 istate->cache,
1771 istate->cache_nr,
1772 &prefix,
1773 select_mask, clear_mask,
1774 pl, 0, 0);
1775 trace2_region_leave("unpack_trees", label, the_repository);
1777 stop_progress(&istate->progress);
1778 return rval;
1782 * Set/Clear CE_NEW_SKIP_WORKTREE according to $GIT_DIR/info/sparse-checkout
1784 static void mark_new_skip_worktree(struct pattern_list *pl,
1785 struct index_state *istate,
1786 int select_flag, int skip_wt_flag,
1787 int show_progress)
1789 int i;
1792 * 1. Pretend the narrowest worktree: only unmerged entries
1793 * are checked out
1795 for (i = 0; i < istate->cache_nr; i++) {
1796 struct cache_entry *ce = istate->cache[i];
1798 if (select_flag && !(ce->ce_flags & select_flag))
1799 continue;
1801 if (!ce_stage(ce) && !(ce->ce_flags & CE_CONFLICTED))
1802 ce->ce_flags |= skip_wt_flag;
1803 else
1804 ce->ce_flags &= ~skip_wt_flag;
1808 * 2. Widen worktree according to sparse-checkout file.
1809 * Matched entries will have skip_wt_flag cleared (i.e. "in")
1811 clear_ce_flags(istate, select_flag, skip_wt_flag, pl, show_progress);
1814 static void populate_from_existing_patterns(struct unpack_trees_options *o,
1815 struct pattern_list *pl)
1817 if (get_sparse_checkout_patterns(pl) < 0)
1818 o->skip_sparse_checkout = 1;
1819 else
1820 o->internal.pl = pl;
1823 static void update_sparsity_for_prefix(const char *prefix,
1824 struct index_state *istate)
1826 int prefix_len = strlen(prefix);
1827 struct strbuf ce_prefix = STRBUF_INIT;
1829 if (!istate->sparse_index)
1830 return;
1832 while (prefix_len > 0 && prefix[prefix_len - 1] == '/')
1833 prefix_len--;
1835 if (prefix_len <= 0)
1836 BUG("Invalid prefix passed to update_sparsity_for_prefix");
1838 strbuf_grow(&ce_prefix, prefix_len + 1);
1839 strbuf_add(&ce_prefix, prefix, prefix_len);
1840 strbuf_addch(&ce_prefix, '/');
1843 * If the prefix points to a sparse directory or a path inside a sparse
1844 * directory, the index should be expanded. This is accomplished in one
1845 * of two ways:
1846 * - if the prefix is inside a sparse directory, it will be expanded by
1847 * the 'ensure_full_index(...)' call in 'index_name_pos(...)'.
1848 * - if the prefix matches an existing sparse directory entry,
1849 * 'index_name_pos(...)' will return its index position, triggering
1850 * the 'ensure_full_index(...)' below.
1852 if (!path_in_cone_mode_sparse_checkout(ce_prefix.buf, istate) &&
1853 index_name_pos(istate, ce_prefix.buf, ce_prefix.len) >= 0)
1854 ensure_full_index(istate);
1856 strbuf_release(&ce_prefix);
1859 static int verify_absent(const struct cache_entry *,
1860 enum unpack_trees_error_types,
1861 struct unpack_trees_options *);
1863 * N-way merge "len" trees. Returns 0 on success, -1 on failure to manipulate the
1864 * resulting index, -2 on failure to reflect the changes to the work tree.
1866 * CE_ADDED, CE_UNPACKED and CE_NEW_SKIP_WORKTREE are used internally
1868 int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
1870 struct repository *repo = the_repository;
1871 int i, ret;
1872 static struct cache_entry *dfc;
1873 struct pattern_list pl;
1874 int free_pattern_list = 0;
1875 struct dir_struct dir = DIR_INIT;
1877 if (o->reset == UNPACK_RESET_INVALID)
1878 BUG("o->reset had a value of 1; should be UNPACK_TREES_*_UNTRACKED");
1880 if (len > MAX_UNPACK_TREES)
1881 die("unpack_trees takes at most %d trees", MAX_UNPACK_TREES);
1882 if (o->internal.dir)
1883 BUG("o->internal.dir is for internal use only");
1884 if (o->internal.pl)
1885 BUG("o->internal.pl is for internal use only");
1886 if (o->df_conflict_entry)
1887 BUG("o->df_conflict_entry is an output only field");
1889 trace_performance_enter();
1890 trace2_region_enter("unpack_trees", "unpack_trees", the_repository);
1892 prepare_repo_settings(repo);
1893 if (repo->settings.command_requires_full_index) {
1894 ensure_full_index(o->src_index);
1895 if (o->dst_index)
1896 ensure_full_index(o->dst_index);
1899 if (o->reset == UNPACK_RESET_OVERWRITE_UNTRACKED &&
1900 o->preserve_ignored)
1901 BUG("UNPACK_RESET_OVERWRITE_UNTRACKED incompatible with preserved ignored files");
1903 if (!o->preserve_ignored) {
1904 o->internal.dir = &dir;
1905 o->internal.dir->flags |= DIR_SHOW_IGNORED;
1906 setup_standard_excludes(o->internal.dir);
1909 if (o->prefix)
1910 update_sparsity_for_prefix(o->prefix, o->src_index);
1912 if (!core_apply_sparse_checkout || !o->update)
1913 o->skip_sparse_checkout = 1;
1914 if (!o->skip_sparse_checkout) {
1915 memset(&pl, 0, sizeof(pl));
1916 free_pattern_list = 1;
1917 populate_from_existing_patterns(o, &pl);
1920 index_state_init(&o->internal.result, o->src_index->repo);
1921 o->internal.result.initialized = 1;
1922 o->internal.result.timestamp.sec = o->src_index->timestamp.sec;
1923 o->internal.result.timestamp.nsec = o->src_index->timestamp.nsec;
1924 o->internal.result.version = o->src_index->version;
1925 if (!o->src_index->split_index) {
1926 o->internal.result.split_index = NULL;
1927 } else if (o->src_index == o->dst_index) {
1929 * o->dst_index (and thus o->src_index) will be discarded
1930 * and overwritten with o->internal.result at the end of
1931 * this function, so just use src_index's split_index to
1932 * avoid having to create a new one.
1934 o->internal.result.split_index = o->src_index->split_index;
1935 if (o->src_index->cache_changed & SPLIT_INDEX_ORDERED)
1936 o->internal.result.cache_changed |= SPLIT_INDEX_ORDERED;
1937 o->internal.result.split_index->refcount++;
1938 } else {
1939 o->internal.result.split_index =
1940 init_split_index(&o->internal.result);
1942 oidcpy(&o->internal.result.oid, &o->src_index->oid);
1943 o->internal.merge_size = len;
1944 mark_all_ce_unused(o->src_index);
1946 o->internal.result.fsmonitor_last_update =
1947 xstrdup_or_null(o->src_index->fsmonitor_last_update);
1948 o->internal.result.fsmonitor_has_run_once = o->src_index->fsmonitor_has_run_once;
1950 if (!o->src_index->initialized &&
1951 !repo->settings.command_requires_full_index &&
1952 is_sparse_index_allowed(&o->internal.result, 0))
1953 o->internal.result.sparse_index = 1;
1956 * Sparse checkout loop #1: set NEW_SKIP_WORKTREE on existing entries
1958 if (!o->skip_sparse_checkout)
1959 mark_new_skip_worktree(o->internal.pl, o->src_index, 0,
1960 CE_NEW_SKIP_WORKTREE, o->verbose_update);
1962 if (!dfc)
1963 dfc = xcalloc(1, cache_entry_size(0));
1964 o->df_conflict_entry = dfc;
1966 if (len) {
1967 const char *prefix = o->prefix ? o->prefix : "";
1968 struct traverse_info info;
1970 setup_traverse_info(&info, prefix);
1971 info.fn = unpack_callback;
1972 info.data = o;
1973 info.show_all_errors = o->internal.show_all_errors;
1974 info.pathspec = o->pathspec;
1976 if (o->prefix) {
1978 * Unpack existing index entries that sort before the
1979 * prefix the tree is spliced into. Note that o->merge
1980 * is always true in this case.
1982 while (1) {
1983 struct cache_entry *ce = next_cache_entry(o);
1984 if (!ce)
1985 break;
1986 if (ce_in_traverse_path(ce, &info))
1987 break;
1988 if (unpack_index_entry(ce, o) < 0)
1989 goto return_failed;
1993 trace_performance_enter();
1994 trace2_region_enter("unpack_trees", "traverse_trees", the_repository);
1995 ret = traverse_trees(o->src_index, len, t, &info);
1996 trace2_region_leave("unpack_trees", "traverse_trees", the_repository);
1997 trace_performance_leave("traverse_trees");
1998 if (ret < 0)
1999 goto return_failed;
2002 /* Any left-over entries in the index? */
2003 if (o->merge) {
2004 while (1) {
2005 struct cache_entry *ce = next_cache_entry(o);
2006 if (!ce)
2007 break;
2008 if (unpack_index_entry(ce, o) < 0)
2009 goto return_failed;
2012 mark_all_ce_unused(o->src_index);
2014 if (o->trivial_merges_only && o->internal.nontrivial_merge) {
2015 ret = unpack_failed(o, "Merge requires file-level merging");
2016 goto done;
2019 if (!o->skip_sparse_checkout) {
2021 * Sparse checkout loop #2: set NEW_SKIP_WORKTREE on entries not in loop #1
2022 * If they will have NEW_SKIP_WORKTREE, also set CE_SKIP_WORKTREE
2023 * so apply_sparse_checkout() won't attempt to remove it from worktree
2025 mark_new_skip_worktree(o->internal.pl, &o->internal.result,
2026 CE_ADDED, CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE,
2027 o->verbose_update);
2029 ret = 0;
2030 for (i = 0; i < o->internal.result.cache_nr; i++) {
2031 struct cache_entry *ce = o->internal.result.cache[i];
2034 * Entries marked with CE_ADDED in merged_entry() do not have
2035 * verify_absent() check (the check is effectively disabled
2036 * because CE_NEW_SKIP_WORKTREE is set unconditionally).
2038 * Do the real check now because we have had
2039 * correct CE_NEW_SKIP_WORKTREE
2041 if (ce->ce_flags & CE_ADDED &&
2042 verify_absent(ce, WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN, o))
2043 ret = 1;
2045 if (apply_sparse_checkout(&o->internal.result, ce, o))
2046 ret = 1;
2048 if (ret == 1) {
2050 * Inability to sparsify or de-sparsify individual
2051 * paths is not an error, but just a warning.
2053 if (o->internal.show_all_errors)
2054 display_warning_msgs(o);
2055 ret = 0;
2059 ret = check_updates(o, &o->internal.result) ? (-2) : 0;
2060 if (o->dst_index) {
2061 move_index_extensions(&o->internal.result, o->src_index);
2062 if (!ret) {
2063 if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0))
2064 cache_tree_verify(the_repository,
2065 &o->internal.result);
2066 if (!o->skip_cache_tree_update &&
2067 !cache_tree_fully_valid(o->internal.result.cache_tree))
2068 cache_tree_update(&o->internal.result,
2069 WRITE_TREE_SILENT |
2070 WRITE_TREE_REPAIR);
2073 o->internal.result.updated_workdir = 1;
2074 discard_index(o->dst_index);
2075 *o->dst_index = o->internal.result;
2076 } else {
2077 discard_index(&o->internal.result);
2079 o->src_index = NULL;
2081 done:
2082 if (free_pattern_list)
2083 clear_pattern_list(&pl);
2084 if (o->internal.dir) {
2085 dir_clear(o->internal.dir);
2086 o->internal.dir = NULL;
2088 trace2_region_leave("unpack_trees", "unpack_trees", the_repository);
2089 trace_performance_leave("unpack_trees");
2090 return ret;
2092 return_failed:
2093 if (o->internal.show_all_errors)
2094 display_error_msgs(o);
2095 mark_all_ce_unused(o->src_index);
2096 ret = unpack_failed(o, NULL);
2097 if (o->exiting_early)
2098 ret = 0;
2099 goto done;
2103 * Update SKIP_WORKTREE bits according to sparsity patterns, and update
2104 * working directory to match.
2106 * CE_NEW_SKIP_WORKTREE is used internally.
2108 enum update_sparsity_result update_sparsity(struct unpack_trees_options *o,
2109 struct pattern_list *pl)
2111 enum update_sparsity_result ret = UPDATE_SPARSITY_SUCCESS;
2112 int i;
2113 unsigned old_show_all_errors;
2114 int free_pattern_list = 0;
2116 old_show_all_errors = o->internal.show_all_errors;
2117 o->internal.show_all_errors = 1;
2118 index_state_init(&o->internal.result, o->src_index->repo);
2120 /* Sanity checks */
2121 if (!o->update || o->index_only || o->skip_sparse_checkout)
2122 BUG("update_sparsity() is for reflecting sparsity patterns in working directory");
2123 if (o->src_index != o->dst_index || o->fn)
2124 BUG("update_sparsity() called wrong");
2126 trace_performance_enter();
2128 /* If we weren't given patterns, use the recorded ones */
2129 if (!pl) {
2130 free_pattern_list = 1;
2131 pl = xcalloc(1, sizeof(*pl));
2132 populate_from_existing_patterns(o, pl);
2134 o->internal.pl = pl;
2136 /* Expand sparse directories as needed */
2137 expand_index(o->src_index, o->internal.pl);
2139 /* Set NEW_SKIP_WORKTREE on existing entries. */
2140 mark_all_ce_unused(o->src_index);
2141 mark_new_skip_worktree(o->internal.pl, o->src_index, 0,
2142 CE_NEW_SKIP_WORKTREE, o->verbose_update);
2144 /* Then loop over entries and update/remove as needed */
2145 ret = UPDATE_SPARSITY_SUCCESS;
2146 for (i = 0; i < o->src_index->cache_nr; i++) {
2147 struct cache_entry *ce = o->src_index->cache[i];
2150 if (ce_stage(ce)) {
2151 /* -1 because for loop will increment by 1 */
2152 i += warn_conflicted_path(o->src_index, i, o) - 1;
2153 ret = UPDATE_SPARSITY_WARNINGS;
2154 continue;
2157 if (apply_sparse_checkout(o->src_index, ce, o))
2158 ret = UPDATE_SPARSITY_WARNINGS;
2161 if (check_updates(o, o->src_index))
2162 ret = UPDATE_SPARSITY_WORKTREE_UPDATE_FAILURES;
2164 display_warning_msgs(o);
2165 o->internal.show_all_errors = old_show_all_errors;
2166 if (free_pattern_list) {
2167 clear_pattern_list(pl);
2168 free(pl);
2169 o->internal.pl = NULL;
2171 trace_performance_leave("update_sparsity");
2172 return ret;
2175 /* Here come the merge functions */
2177 static int reject_merge(const struct cache_entry *ce,
2178 struct unpack_trees_options *o)
2180 return add_rejected_path(o, ERROR_WOULD_OVERWRITE, ce->name);
2183 static int same(const struct cache_entry *a, const struct cache_entry *b)
2185 if (!!a != !!b)
2186 return 0;
2187 if (!a && !b)
2188 return 1;
2189 if ((a->ce_flags | b->ce_flags) & CE_CONFLICTED)
2190 return 0;
2191 return a->ce_mode == b->ce_mode &&
2192 oideq(&a->oid, &b->oid);
2197 * When a CE gets turned into an unmerged entry, we
2198 * want it to be up-to-date
2200 static int verify_uptodate_1(const struct cache_entry *ce,
2201 struct unpack_trees_options *o,
2202 enum unpack_trees_error_types error_type)
2204 struct stat st;
2206 if (o->index_only)
2207 return 0;
2210 * CE_VALID and CE_SKIP_WORKTREE cheat, we better check again
2211 * if this entry is truly up-to-date because this file may be
2212 * overwritten.
2214 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2215 ; /* keep checking */
2216 else if (o->reset || ce_uptodate(ce))
2217 return 0;
2219 if (!lstat(ce->name, &st)) {
2220 int flags = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE;
2221 unsigned changed = ie_match_stat(o->src_index, ce, &st, flags);
2223 if (submodule_from_ce(ce)) {
2224 int r = check_submodule_move_head(ce,
2225 "HEAD", oid_to_hex(&ce->oid), o);
2226 if (r)
2227 return add_rejected_path(o, error_type, ce->name);
2228 return 0;
2231 if (!changed)
2232 return 0;
2234 * Historic default policy was to allow submodule to be out
2235 * of sync wrt the superproject index. If the submodule was
2236 * not considered interesting above, we don't care here.
2238 if (S_ISGITLINK(ce->ce_mode))
2239 return 0;
2241 errno = 0;
2243 if (errno == ENOENT)
2244 return 0;
2245 return add_rejected_path(o, error_type, ce->name);
2248 int verify_uptodate(const struct cache_entry *ce,
2249 struct unpack_trees_options *o)
2251 if (!o->skip_sparse_checkout &&
2252 (ce->ce_flags & CE_SKIP_WORKTREE) &&
2253 (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2254 return 0;
2255 return verify_uptodate_1(ce, o, ERROR_NOT_UPTODATE_FILE);
2258 static int verify_uptodate_sparse(const struct cache_entry *ce,
2259 struct unpack_trees_options *o)
2261 return verify_uptodate_1(ce, o, WARNING_SPARSE_NOT_UPTODATE_FILE);
2265 * TODO: We should actually invalidate o->internal.result, not src_index [1].
2266 * But since cache tree and untracked cache both are not copied to
2267 * o->internal.result until unpacking is complete, we invalidate them on
2268 * src_index instead with the assumption that they will be copied to
2269 * dst_index at the end.
2271 * [1] src_index->cache_tree is also used in unpack_callback() so if
2272 * we invalidate o->internal.result, we need to update it to use
2273 * o->internal.result.cache_tree as well.
2275 static void invalidate_ce_path(const struct cache_entry *ce,
2276 struct unpack_trees_options *o)
2278 if (!ce)
2279 return;
2280 cache_tree_invalidate_path(o->src_index, ce->name);
2281 untracked_cache_invalidate_path(o->src_index, ce->name, 1);
2285 * Check that checking out ce->sha1 in subdir ce->name is not
2286 * going to overwrite any working files.
2288 static int verify_clean_submodule(const char *old_sha1,
2289 const struct cache_entry *ce,
2290 struct unpack_trees_options *o)
2292 if (!submodule_from_ce(ce))
2293 return 0;
2295 return check_submodule_move_head(ce, old_sha1,
2296 oid_to_hex(&ce->oid), o);
2299 static int verify_clean_subdirectory(const struct cache_entry *ce,
2300 struct unpack_trees_options *o)
2303 * we are about to extract "ce->name"; we would not want to lose
2304 * anything in the existing directory there.
2306 int namelen;
2307 int i;
2308 struct dir_struct d;
2309 char *pathbuf;
2310 int cnt = 0;
2312 if (S_ISGITLINK(ce->ce_mode)) {
2313 struct object_id oid;
2314 int sub_head = resolve_gitlink_ref(ce->name, "HEAD", &oid);
2316 * If we are not going to update the submodule, then
2317 * we don't care.
2319 if (!sub_head && oideq(&oid, &ce->oid))
2320 return 0;
2321 return verify_clean_submodule(sub_head ? NULL : oid_to_hex(&oid),
2322 ce, o);
2326 * First let's make sure we do not have a local modification
2327 * in that directory.
2329 namelen = ce_namelen(ce);
2330 for (i = locate_in_src_index(ce, o);
2331 i < o->src_index->cache_nr;
2332 i++) {
2333 struct cache_entry *ce2 = o->src_index->cache[i];
2334 int len = ce_namelen(ce2);
2335 if (len < namelen ||
2336 strncmp(ce->name, ce2->name, namelen) ||
2337 ce2->name[namelen] != '/')
2338 break;
2340 * ce2->name is an entry in the subdirectory to be
2341 * removed.
2343 if (!ce_stage(ce2)) {
2344 if (verify_uptodate(ce2, o))
2345 return -1;
2346 add_entry(o, ce2, CE_REMOVE, 0);
2347 invalidate_ce_path(ce, o);
2348 mark_ce_used(ce2, o);
2350 cnt++;
2353 /* Do not lose a locally present file that is not ignored. */
2354 pathbuf = xstrfmt("%.*s/", namelen, ce->name);
2356 memset(&d, 0, sizeof(d));
2357 if (o->internal.dir)
2358 setup_standard_excludes(&d);
2359 i = read_directory(&d, o->src_index, pathbuf, namelen+1, NULL);
2360 dir_clear(&d);
2361 free(pathbuf);
2362 if (i)
2363 return add_rejected_path(o, ERROR_NOT_UPTODATE_DIR, ce->name);
2365 /* Do not lose startup_info->original_cwd */
2366 if (startup_info->original_cwd &&
2367 !strcmp(startup_info->original_cwd, ce->name))
2368 return add_rejected_path(o, ERROR_CWD_IN_THE_WAY, ce->name);
2370 return cnt;
2374 * This gets called when there was no index entry for the tree entry 'dst',
2375 * but we found a file in the working tree that 'lstat()' said was fine,
2376 * and we're on a case-insensitive filesystem.
2378 * See if we can find a case-insensitive match in the index that also
2379 * matches the stat information, and assume it's that other file!
2381 static int icase_exists(struct unpack_trees_options *o, const char *name, int len, struct stat *st)
2383 const struct cache_entry *src;
2385 src = index_file_exists(o->src_index, name, len, 1);
2386 return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
2389 enum absent_checking_type {
2390 COMPLETELY_ABSENT,
2391 ABSENT_ANY_DIRECTORY
2394 static int check_ok_to_remove(const char *name, int len, int dtype,
2395 const struct cache_entry *ce, struct stat *st,
2396 enum unpack_trees_error_types error_type,
2397 enum absent_checking_type absent_type,
2398 struct unpack_trees_options *o)
2400 const struct cache_entry *result;
2403 * It may be that the 'lstat()' succeeded even though
2404 * target 'ce' was absent, because there is an old
2405 * entry that is different only in case..
2407 * Ignore that lstat() if it matches.
2409 if (ignore_case && icase_exists(o, name, len, st))
2410 return 0;
2412 if (o->internal.dir &&
2413 is_excluded(o->internal.dir, o->src_index, name, &dtype))
2415 * ce->name is explicitly excluded, so it is Ok to
2416 * overwrite it.
2418 return 0;
2419 if (S_ISDIR(st->st_mode)) {
2421 * We are checking out path "foo" and
2422 * found "foo/." in the working tree.
2423 * This is tricky -- if we have modified
2424 * files that are in "foo/" we would lose
2425 * them.
2427 if (verify_clean_subdirectory(ce, o) < 0)
2428 return -1;
2429 return 0;
2432 /* If we only care about directories, then we can remove */
2433 if (absent_type == ABSENT_ANY_DIRECTORY)
2434 return 0;
2437 * The previous round may already have decided to
2438 * delete this path, which is in a subdirectory that
2439 * is being replaced with a blob.
2441 result = index_file_exists(&o->internal.result, name, len, 0);
2442 if (result) {
2443 if (result->ce_flags & CE_REMOVE)
2444 return 0;
2447 return add_rejected_path(o, error_type, name);
2451 * We do not want to remove or overwrite a working tree file that
2452 * is not tracked, unless it is ignored.
2454 static int verify_absent_1(const struct cache_entry *ce,
2455 enum unpack_trees_error_types error_type,
2456 enum absent_checking_type absent_type,
2457 struct unpack_trees_options *o)
2459 int len;
2460 struct stat st;
2462 if (o->index_only || !o->update)
2463 return 0;
2465 if (o->reset == UNPACK_RESET_OVERWRITE_UNTRACKED) {
2466 /* Avoid nuking startup_info->original_cwd... */
2467 if (startup_info->original_cwd &&
2468 !strcmp(startup_info->original_cwd, ce->name))
2469 return add_rejected_path(o, ERROR_CWD_IN_THE_WAY,
2470 ce->name);
2471 /* ...but nuke anything else. */
2472 return 0;
2475 len = check_leading_path(ce->name, ce_namelen(ce), 0);
2476 if (!len)
2477 return 0;
2478 else if (len > 0) {
2479 char *path;
2480 int ret;
2482 path = xmemdupz(ce->name, len);
2483 if (lstat(path, &st))
2484 ret = error_errno("cannot stat '%s'", path);
2485 else {
2486 if (submodule_from_ce(ce))
2487 ret = check_submodule_move_head(ce,
2488 oid_to_hex(&ce->oid),
2489 NULL, o);
2490 else
2491 ret = check_ok_to_remove(path, len, DT_UNKNOWN, NULL,
2492 &st, error_type,
2493 absent_type, o);
2495 free(path);
2496 return ret;
2497 } else if (lstat(ce->name, &st)) {
2498 if (errno != ENOENT)
2499 return error_errno("cannot stat '%s'", ce->name);
2500 return 0;
2501 } else {
2502 if (submodule_from_ce(ce))
2503 return check_submodule_move_head(ce, oid_to_hex(&ce->oid),
2504 NULL, o);
2506 return check_ok_to_remove(ce->name, ce_namelen(ce),
2507 ce_to_dtype(ce), ce, &st,
2508 error_type, absent_type, o);
2512 static int verify_absent(const struct cache_entry *ce,
2513 enum unpack_trees_error_types error_type,
2514 struct unpack_trees_options *o)
2516 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2517 return 0;
2518 return verify_absent_1(ce, error_type, COMPLETELY_ABSENT, o);
2521 static int verify_absent_if_directory(const struct cache_entry *ce,
2522 enum unpack_trees_error_types error_type,
2523 struct unpack_trees_options *o)
2525 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2526 return 0;
2527 return verify_absent_1(ce, error_type, ABSENT_ANY_DIRECTORY, o);
2530 static int verify_absent_sparse(const struct cache_entry *ce,
2531 enum unpack_trees_error_types error_type,
2532 struct unpack_trees_options *o)
2534 return verify_absent_1(ce, error_type, COMPLETELY_ABSENT, o);
2537 static int merged_entry(const struct cache_entry *ce,
2538 const struct cache_entry *old,
2539 struct unpack_trees_options *o)
2541 int update = CE_UPDATE;
2542 struct cache_entry *merge = dup_cache_entry(ce, &o->internal.result);
2544 if (!old) {
2546 * New index entries. In sparse checkout, the following
2547 * verify_absent() will be delayed until after
2548 * traverse_trees() finishes in unpack_trees(), then:
2550 * - CE_NEW_SKIP_WORKTREE will be computed correctly
2551 * - verify_absent() be called again, this time with
2552 * correct CE_NEW_SKIP_WORKTREE
2554 * verify_absent() call here does nothing in sparse
2555 * checkout (i.e. o->skip_sparse_checkout == 0)
2557 update |= CE_ADDED;
2558 merge->ce_flags |= CE_NEW_SKIP_WORKTREE;
2560 if (verify_absent(merge,
2561 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
2562 discard_cache_entry(merge);
2563 return -1;
2565 invalidate_ce_path(merge, o);
2567 if (submodule_from_ce(ce) && file_exists(ce->name)) {
2568 int ret = check_submodule_move_head(ce, NULL,
2569 oid_to_hex(&ce->oid),
2571 if (ret)
2572 return ret;
2575 } else if (!(old->ce_flags & CE_CONFLICTED)) {
2577 * See if we can re-use the old CE directly?
2578 * That way we get the uptodate stat info.
2580 * This also removes the UPDATE flag on a match; otherwise
2581 * we will end up overwriting local changes in the work tree.
2583 if (same(old, merge)) {
2584 copy_cache_entry(merge, old);
2585 update = 0;
2586 } else {
2587 if (verify_uptodate(old, o)) {
2588 discard_cache_entry(merge);
2589 return -1;
2591 /* Migrate old flags over */
2592 update |= old->ce_flags & (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
2593 invalidate_ce_path(old, o);
2596 if (submodule_from_ce(ce) && file_exists(ce->name)) {
2597 int ret = check_submodule_move_head(ce, oid_to_hex(&old->oid),
2598 oid_to_hex(&ce->oid),
2600 if (ret)
2601 return ret;
2603 } else {
2605 * Previously unmerged entry left as an existence
2606 * marker by read_index_unmerged();
2608 if (verify_absent_if_directory(merge,
2609 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
2610 discard_cache_entry(merge);
2611 return -1;
2614 invalidate_ce_path(old, o);
2617 if (do_add_entry(o, merge, update, CE_STAGEMASK) < 0)
2618 return -1;
2619 return 1;
2622 static int merged_sparse_dir(const struct cache_entry * const *src, int n,
2623 struct unpack_trees_options *o)
2625 struct tree_desc t[MAX_UNPACK_TREES + 1];
2626 void * tree_bufs[MAX_UNPACK_TREES + 1];
2627 struct traverse_info info;
2628 int i, ret;
2631 * Create the tree traversal information for traversing into *only* the
2632 * sparse directory.
2634 setup_traverse_info(&info, src[0]->name);
2635 info.fn = unpack_sparse_callback;
2636 info.data = o;
2637 info.show_all_errors = o->internal.show_all_errors;
2638 info.pathspec = o->pathspec;
2640 /* Get the tree descriptors of the sparse directory in each of the merging trees */
2641 for (i = 0; i < n; i++)
2642 tree_bufs[i] = fill_tree_descriptor(o->src_index->repo, &t[i],
2643 src[i] && !is_null_oid(&src[i]->oid) ? &src[i]->oid : NULL);
2645 ret = traverse_trees(o->src_index, n, t, &info);
2647 for (i = 0; i < n; i++)
2648 free(tree_bufs[i]);
2650 return ret;
2653 static int deleted_entry(const struct cache_entry *ce,
2654 const struct cache_entry *old,
2655 struct unpack_trees_options *o)
2657 /* Did it exist in the index? */
2658 if (!old) {
2659 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2660 return -1;
2661 return 0;
2662 } else if (verify_absent_if_directory(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o)) {
2663 return -1;
2666 if (!(old->ce_flags & CE_CONFLICTED) && verify_uptodate(old, o))
2667 return -1;
2668 add_entry(o, ce, CE_REMOVE, 0);
2669 invalidate_ce_path(ce, o);
2670 return 1;
2673 static int keep_entry(const struct cache_entry *ce,
2674 struct unpack_trees_options *o)
2676 add_entry(o, ce, 0, 0);
2677 if (ce_stage(ce))
2678 invalidate_ce_path(ce, o);
2679 return 1;
2682 #if DBRT_DEBUG
2683 static void show_stage_entry(FILE *o,
2684 const char *label, const struct cache_entry *ce)
2686 if (!ce)
2687 fprintf(o, "%s (missing)\n", label);
2688 else
2689 fprintf(o, "%s%06o %s %d\t%s\n",
2690 label,
2691 ce->ce_mode,
2692 oid_to_hex(&ce->oid),
2693 ce_stage(ce),
2694 ce->name);
2696 #endif
2698 int threeway_merge(const struct cache_entry * const *stages,
2699 struct unpack_trees_options *o)
2701 const struct cache_entry *index;
2702 const struct cache_entry *head;
2703 const struct cache_entry *remote = stages[o->head_idx + 1];
2704 int count;
2705 int head_match = 0;
2706 int remote_match = 0;
2708 int df_conflict_head = 0;
2709 int df_conflict_remote = 0;
2711 int any_anc_missing = 0;
2712 int no_anc_exists = 1;
2713 int i;
2715 for (i = 1; i < o->head_idx; i++) {
2716 if (!stages[i] || stages[i] == o->df_conflict_entry)
2717 any_anc_missing = 1;
2718 else
2719 no_anc_exists = 0;
2722 index = stages[0];
2723 head = stages[o->head_idx];
2725 if (head == o->df_conflict_entry) {
2726 df_conflict_head = 1;
2727 head = NULL;
2730 if (remote == o->df_conflict_entry) {
2731 df_conflict_remote = 1;
2732 remote = NULL;
2736 * First, if there's a #16 situation, note that to prevent #13
2737 * and #14.
2739 if (!same(remote, head)) {
2740 for (i = 1; i < o->head_idx; i++) {
2741 if (same(stages[i], head)) {
2742 head_match = i;
2744 if (same(stages[i], remote)) {
2745 remote_match = i;
2751 * We start with cases where the index is allowed to match
2752 * something other than the head: #14(ALT) and #2ALT, where it
2753 * is permitted to match the result instead.
2755 /* #14, #14ALT, #2ALT */
2756 if (remote && !df_conflict_head && head_match && !remote_match) {
2757 if (index && !same(index, remote) && !same(index, head)) {
2758 if (S_ISSPARSEDIR(index->ce_mode))
2759 return merged_sparse_dir(stages, 4, o);
2760 else
2761 return reject_merge(index, o);
2763 return merged_entry(remote, index, o);
2766 * If we have an entry in the index cache, then we want to
2767 * make sure that it matches head.
2769 if (index && !same(index, head)) {
2770 if (S_ISSPARSEDIR(index->ce_mode))
2771 return merged_sparse_dir(stages, 4, o);
2772 else
2773 return reject_merge(index, o);
2776 if (head) {
2777 /* #5ALT, #15 */
2778 if (same(head, remote))
2779 return merged_entry(head, index, o);
2780 /* #13, #3ALT */
2781 if (!df_conflict_remote && remote_match && !head_match)
2782 return merged_entry(head, index, o);
2785 /* #1 */
2786 if (!head && !remote && any_anc_missing)
2787 return 0;
2790 * Under the "aggressive" rule, we resolve mostly trivial
2791 * cases that we historically had git-merge-one-file resolve.
2793 if (o->aggressive) {
2794 int head_deleted = !head;
2795 int remote_deleted = !remote;
2796 const struct cache_entry *ce = NULL;
2798 if (index)
2799 ce = index;
2800 else if (head)
2801 ce = head;
2802 else if (remote)
2803 ce = remote;
2804 else {
2805 for (i = 1; i < o->head_idx; i++) {
2806 if (stages[i] && stages[i] != o->df_conflict_entry) {
2807 ce = stages[i];
2808 break;
2814 * Deleted in both.
2815 * Deleted in one and unchanged in the other.
2817 if ((head_deleted && remote_deleted) ||
2818 (head_deleted && remote && remote_match) ||
2819 (remote_deleted && head && head_match)) {
2820 if (index)
2821 return deleted_entry(index, index, o);
2822 if (ce && !head_deleted) {
2823 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2824 return -1;
2826 return 0;
2829 * Added in both, identically.
2831 if (no_anc_exists && head && remote && same(head, remote))
2832 return merged_entry(head, index, o);
2836 /* Handle "no merge" cases (see t/t1000-read-tree-m-3way.sh) */
2837 if (index) {
2839 * If we've reached the "no merge" cases and we're merging
2840 * a sparse directory, we may have an "edit/edit" conflict that
2841 * can be resolved by individually merging directory contents.
2843 if (S_ISSPARSEDIR(index->ce_mode))
2844 return merged_sparse_dir(stages, 4, o);
2847 * If we're not merging a sparse directory, ensure the index is
2848 * up-to-date to avoid files getting overwritten with conflict
2849 * resolution files
2851 if (verify_uptodate(index, o))
2852 return -1;
2855 o->internal.nontrivial_merge = 1;
2857 /* #2, #3, #4, #6, #7, #9, #10, #11. */
2858 count = 0;
2859 if (!head_match || !remote_match) {
2860 for (i = 1; i < o->head_idx; i++) {
2861 if (stages[i] && stages[i] != o->df_conflict_entry) {
2862 keep_entry(stages[i], o);
2863 count++;
2864 break;
2868 #if DBRT_DEBUG
2869 else {
2870 fprintf(stderr, "read-tree: warning #16 detected\n");
2871 show_stage_entry(stderr, "head ", stages[head_match]);
2872 show_stage_entry(stderr, "remote ", stages[remote_match]);
2874 #endif
2875 if (head) { count += keep_entry(head, o); }
2876 if (remote) { count += keep_entry(remote, o); }
2877 return count;
2881 * Two-way merge.
2883 * The rule is to "carry forward" what is in the index without losing
2884 * information across a "fast-forward", favoring a successful merge
2885 * over a merge failure when it makes sense. For details of the
2886 * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
2889 int twoway_merge(const struct cache_entry * const *src,
2890 struct unpack_trees_options *o)
2892 const struct cache_entry *current = src[0];
2893 const struct cache_entry *oldtree = src[1];
2894 const struct cache_entry *newtree = src[2];
2896 if (o->internal.merge_size != 2)
2897 return error("Cannot do a twoway merge of %d trees",
2898 o->internal.merge_size);
2900 if (oldtree == o->df_conflict_entry)
2901 oldtree = NULL;
2902 if (newtree == o->df_conflict_entry)
2903 newtree = NULL;
2905 if (current) {
2906 if (current->ce_flags & CE_CONFLICTED) {
2907 if (same(oldtree, newtree) || o->reset) {
2908 if (!newtree)
2909 return deleted_entry(current, current, o);
2910 else
2911 return merged_entry(newtree, current, o);
2913 return reject_merge(current, o);
2914 } else if ((!oldtree && !newtree) || /* 4 and 5 */
2915 (!oldtree && newtree &&
2916 same(current, newtree)) || /* 6 and 7 */
2917 (oldtree && newtree &&
2918 same(oldtree, newtree)) || /* 14 and 15 */
2919 (oldtree && newtree &&
2920 !same(oldtree, newtree) && /* 18 and 19 */
2921 same(current, newtree))) {
2922 return keep_entry(current, o);
2923 } else if (oldtree && !newtree && same(current, oldtree)) {
2924 /* 10 or 11 */
2925 return deleted_entry(oldtree, current, o);
2926 } else if (oldtree && newtree &&
2927 same(current, oldtree) && !same(current, newtree)) {
2928 /* 20 or 21 */
2929 return merged_entry(newtree, current, o);
2930 } else if (current && !oldtree && newtree &&
2931 S_ISSPARSEDIR(current->ce_mode) != S_ISSPARSEDIR(newtree->ce_mode) &&
2932 ce_stage(current) == 0) {
2934 * This case is a directory/file conflict across the sparse-index
2935 * boundary. When we are changing from one path to another via
2936 * 'git checkout', then we want to replace one entry with another
2937 * via merged_entry(). If there are staged changes, then we should
2938 * reject the merge instead.
2940 return merged_entry(newtree, current, o);
2941 } else if (S_ISSPARSEDIR(current->ce_mode)) {
2943 * The sparse directories differ, but we don't know whether that's
2944 * because of two different files in the directory being modified
2945 * (can be trivially merged) or if there is a real file conflict.
2946 * Merge the sparse directory by OID to compare file-by-file.
2948 return merged_sparse_dir(src, 3, o);
2949 } else
2950 return reject_merge(current, o);
2952 else if (newtree) {
2953 if (oldtree && !o->initial_checkout) {
2955 * deletion of the path was staged;
2957 if (same(oldtree, newtree))
2958 return 1;
2959 return reject_merge(oldtree, o);
2961 return merged_entry(newtree, current, o);
2963 return deleted_entry(oldtree, current, o);
2967 * Bind merge.
2969 * Keep the index entries at stage0, collapse stage1 but make sure
2970 * stage0 does not have anything there.
2972 int bind_merge(const struct cache_entry * const *src,
2973 struct unpack_trees_options *o)
2975 const struct cache_entry *old = src[0];
2976 const struct cache_entry *a = src[1];
2978 if (o->internal.merge_size != 1)
2979 return error("Cannot do a bind merge of %d trees",
2980 o->internal.merge_size);
2981 if (a && old)
2982 return o->quiet ? -1 :
2983 error(ERRORMSG(o, ERROR_BIND_OVERLAP),
2984 super_prefixed(a->name, o->super_prefix),
2985 super_prefixed(old->name, o->super_prefix));
2986 if (!a)
2987 return keep_entry(old, o);
2988 else
2989 return merged_entry(a, NULL, o);
2993 * One-way merge.
2995 * The rule is:
2996 * - take the stat information from stage0, take the data from stage1
2998 int oneway_merge(const struct cache_entry * const *src,
2999 struct unpack_trees_options *o)
3001 const struct cache_entry *old = src[0];
3002 const struct cache_entry *a = src[1];
3004 if (o->internal.merge_size != 1)
3005 return error("Cannot do a oneway merge of %d trees",
3006 o->internal.merge_size);
3008 if (!a || a == o->df_conflict_entry)
3009 return deleted_entry(old, old, o);
3011 if (old && same(old, a)) {
3012 int update = 0;
3013 if (o->reset && o->update && !ce_uptodate(old) && !ce_skip_worktree(old) &&
3014 !(old->ce_flags & CE_FSMONITOR_VALID)) {
3015 struct stat st;
3016 if (lstat(old->name, &st) ||
3017 ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE))
3018 update |= CE_UPDATE;
3020 if (o->update && S_ISGITLINK(old->ce_mode) &&
3021 should_update_submodules() && !verify_uptodate(old, o))
3022 update |= CE_UPDATE;
3023 add_entry(o, old, update, CE_STAGEMASK);
3024 return 0;
3026 return merged_entry(a, old, o);
3030 * Merge worktree and untracked entries in a stash entry.
3032 * Ignore all index entries. Collapse remaining trees but make sure that they
3033 * don't have any conflicting files.
3035 int stash_worktree_untracked_merge(const struct cache_entry * const *src,
3036 struct unpack_trees_options *o)
3038 const struct cache_entry *worktree = src[1];
3039 const struct cache_entry *untracked = src[2];
3041 if (o->internal.merge_size != 2)
3042 BUG("invalid merge_size: %d", o->internal.merge_size);
3044 if (worktree && untracked)
3045 return error(_("worktree and untracked commit have duplicate entries: %s"),
3046 super_prefixed(worktree->name, o->super_prefix));
3048 return merged_entry(worktree ? worktree : untracked, NULL, o);