Merge branch 'ak/restore-both-incompatible-with-conflicts'
[git/debian.git] / unpack-trees.c
bloba75fb9f05b4775e8135436a8f915b1a310cad5b6
1 #include "cache.h"
2 #include "strvec.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "dir.h"
6 #include "hex.h"
7 #include "tree.h"
8 #include "tree-walk.h"
9 #include "cache-tree.h"
10 #include "unpack-trees.h"
11 #include "progress.h"
12 #include "refs.h"
13 #include "attr.h"
14 #include "split-index.h"
15 #include "sparse-index.h"
16 #include "submodule.h"
17 #include "submodule-config.h"
18 #include "fsmonitor.h"
19 #include "object-store.h"
20 #include "promisor-remote.h"
21 #include "entry.h"
22 #include "parallel-checkout.h"
25 * Error messages expected by scripts out of plumbing commands such as
26 * read-tree. Non-scripted Porcelain is not required to use these messages
27 * and in fact are encouraged to reword them to better suit their particular
28 * situation better. See how "git checkout" and "git merge" replaces
29 * them using setup_unpack_trees_porcelain(), for example.
31 static const char *unpack_plumbing_errors[NB_UNPACK_TREES_WARNING_TYPES] = {
32 /* ERROR_WOULD_OVERWRITE */
33 "Entry '%s' would be overwritten by merge. Cannot merge.",
35 /* ERROR_NOT_UPTODATE_FILE */
36 "Entry '%s' not uptodate. Cannot merge.",
38 /* ERROR_NOT_UPTODATE_DIR */
39 "Updating '%s' would lose untracked files in it",
41 /* ERROR_CWD_IN_THE_WAY */
42 "Refusing to remove '%s' since it is the current working directory.",
44 /* ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN */
45 "Untracked working tree file '%s' would be overwritten by merge.",
47 /* ERROR_WOULD_LOSE_UNTRACKED_REMOVED */
48 "Untracked working tree file '%s' would be removed by merge.",
50 /* ERROR_BIND_OVERLAP */
51 "Entry '%s' overlaps with '%s'. Cannot bind.",
53 /* ERROR_WOULD_LOSE_SUBMODULE */
54 "Submodule '%s' cannot checkout new HEAD.",
56 /* NB_UNPACK_TREES_ERROR_TYPES; just a meta value */
57 "",
59 /* WARNING_SPARSE_NOT_UPTODATE_FILE */
60 "Path '%s' not uptodate; will not remove from working tree.",
62 /* WARNING_SPARSE_UNMERGED_FILE */
63 "Path '%s' unmerged; will not remove from working tree.",
65 /* WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN */
66 "Path '%s' already present; will not overwrite with sparse update.",
69 #define ERRORMSG(o,type) \
70 ( ((o) && (o)->internal.msgs[(type)]) \
71 ? ((o)->internal.msgs[(type)]) \
72 : (unpack_plumbing_errors[(type)]) )
74 static const char *super_prefixed(const char *path, const char *super_prefix)
77 * It is necessary and sufficient to have two static buffers
78 * here, as the return value of this function is fed to
79 * error() using the unpack_*_errors[] templates we see above.
81 static struct strbuf buf[2] = {STRBUF_INIT, STRBUF_INIT};
82 static int super_prefix_len = -1;
83 static unsigned idx = ARRAY_SIZE(buf) - 1;
85 if (super_prefix_len < 0) {
86 if (!super_prefix) {
87 super_prefix_len = 0;
88 } else {
89 int i;
90 for (i = 0; i < ARRAY_SIZE(buf); i++)
91 strbuf_addstr(&buf[i], super_prefix);
92 super_prefix_len = buf[0].len;
96 if (!super_prefix_len)
97 return path;
99 if (++idx >= ARRAY_SIZE(buf))
100 idx = 0;
102 strbuf_setlen(&buf[idx], super_prefix_len);
103 strbuf_addstr(&buf[idx], path);
105 return buf[idx].buf;
108 void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,
109 const char *cmd)
111 int i;
112 const char **msgs = opts->internal.msgs;
113 const char *msg;
115 strvec_init(&opts->internal.msgs_to_free);
117 if (!strcmp(cmd, "checkout"))
118 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
119 ? _("Your local changes to the following files would be overwritten by checkout:\n%%s"
120 "Please commit your changes or stash them before you switch branches.")
121 : _("Your local changes to the following files would be overwritten by checkout:\n%%s");
122 else if (!strcmp(cmd, "merge"))
123 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
124 ? _("Your local changes to the following files would be overwritten by merge:\n%%s"
125 "Please commit your changes or stash them before you merge.")
126 : _("Your local changes to the following files would be overwritten by merge:\n%%s");
127 else
128 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
129 ? _("Your local changes to the following files would be overwritten by %s:\n%%s"
130 "Please commit your changes or stash them before you %s.")
131 : _("Your local changes to the following files would be overwritten by %s:\n%%s");
132 msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOT_UPTODATE_FILE] =
133 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
135 msgs[ERROR_NOT_UPTODATE_DIR] =
136 _("Updating the following directories would lose untracked files in them:\n%s");
138 msgs[ERROR_CWD_IN_THE_WAY] =
139 _("Refusing to remove the current working directory:\n%s");
141 if (!strcmp(cmd, "checkout"))
142 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
143 ? _("The following untracked working tree files would be removed by checkout:\n%%s"
144 "Please move or remove them before you switch branches.")
145 : _("The following untracked working tree files would be removed by checkout:\n%%s");
146 else if (!strcmp(cmd, "merge"))
147 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
148 ? _("The following untracked working tree files would be removed by merge:\n%%s"
149 "Please move or remove them before you merge.")
150 : _("The following untracked working tree files would be removed by merge:\n%%s");
151 else
152 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
153 ? _("The following untracked working tree files would be removed by %s:\n%%s"
154 "Please move or remove them before you %s.")
155 : _("The following untracked working tree files would be removed by %s:\n%%s");
156 msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED] =
157 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
159 if (!strcmp(cmd, "checkout"))
160 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
161 ? _("The following untracked working tree files would be overwritten by checkout:\n%%s"
162 "Please move or remove them before you switch branches.")
163 : _("The following untracked working tree files would be overwritten by checkout:\n%%s");
164 else if (!strcmp(cmd, "merge"))
165 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
166 ? _("The following untracked working tree files would be overwritten by merge:\n%%s"
167 "Please move or remove them before you merge.")
168 : _("The following untracked working tree files would be overwritten by merge:\n%%s");
169 else
170 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
171 ? _("The following untracked working tree files would be overwritten by %s:\n%%s"
172 "Please move or remove them before you %s.")
173 : _("The following untracked working tree files would be overwritten by %s:\n%%s");
174 msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN] =
175 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
178 * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
179 * cannot easily display it as a list.
181 msgs[ERROR_BIND_OVERLAP] = _("Entry '%s' overlaps with '%s'. Cannot bind.");
183 msgs[ERROR_WOULD_LOSE_SUBMODULE] =
184 _("Cannot update submodule:\n%s");
186 msgs[WARNING_SPARSE_NOT_UPTODATE_FILE] =
187 _("The following paths are not up to date and were left despite sparse patterns:\n%s");
188 msgs[WARNING_SPARSE_UNMERGED_FILE] =
189 _("The following paths are unmerged and were left despite sparse patterns:\n%s");
190 msgs[WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN] =
191 _("The following paths were already present and thus not updated despite sparse patterns:\n%s");
193 opts->internal.show_all_errors = 1;
194 /* rejected paths may not have a static buffer */
195 for (i = 0; i < ARRAY_SIZE(opts->internal.unpack_rejects); i++)
196 opts->internal.unpack_rejects[i].strdup_strings = 1;
199 void clear_unpack_trees_porcelain(struct unpack_trees_options *opts)
201 strvec_clear(&opts->internal.msgs_to_free);
202 memset(opts->internal.msgs, 0, sizeof(opts->internal.msgs));
205 static int do_add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
206 unsigned int set, unsigned int clear)
208 clear |= CE_HASHED;
210 if (set & CE_REMOVE)
211 set |= CE_WT_REMOVE;
213 ce->ce_flags = (ce->ce_flags & ~clear) | set;
214 return add_index_entry(&o->internal.result, ce,
215 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
218 static void add_entry(struct unpack_trees_options *o,
219 const struct cache_entry *ce,
220 unsigned int set, unsigned int clear)
222 do_add_entry(o, dup_cache_entry(ce, &o->internal.result), set, clear);
226 * add error messages on path <path>
227 * corresponding to the type <e> with the message <msg>
228 * indicating if it should be display in porcelain or not
230 static int add_rejected_path(struct unpack_trees_options *o,
231 enum unpack_trees_error_types e,
232 const char *path)
234 if (o->quiet)
235 return -1;
237 if (!o->internal.show_all_errors)
238 return error(ERRORMSG(o, e), super_prefixed(path,
239 o->super_prefix));
242 * Otherwise, insert in a list for future display by
243 * display_(error|warning)_msgs()
245 string_list_append(&o->internal.unpack_rejects[e], path);
246 return -1;
250 * display all the error messages stored in a nice way
252 static void display_error_msgs(struct unpack_trees_options *o)
254 int e;
255 unsigned error_displayed = 0;
256 for (e = 0; e < NB_UNPACK_TREES_ERROR_TYPES; e++) {
257 struct string_list *rejects = &o->internal.unpack_rejects[e];
259 if (rejects->nr > 0) {
260 int i;
261 struct strbuf path = STRBUF_INIT;
263 error_displayed = 1;
264 for (i = 0; i < rejects->nr; i++)
265 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
266 error(ERRORMSG(o, e), super_prefixed(path.buf,
267 o->super_prefix));
268 strbuf_release(&path);
270 string_list_clear(rejects, 0);
272 if (error_displayed)
273 fprintf(stderr, _("Aborting\n"));
277 * display all the warning messages stored in a nice way
279 static void display_warning_msgs(struct unpack_trees_options *o)
281 int e;
282 unsigned warning_displayed = 0;
283 for (e = NB_UNPACK_TREES_ERROR_TYPES + 1;
284 e < NB_UNPACK_TREES_WARNING_TYPES; e++) {
285 struct string_list *rejects = &o->internal.unpack_rejects[e];
287 if (rejects->nr > 0) {
288 int i;
289 struct strbuf path = STRBUF_INIT;
291 warning_displayed = 1;
292 for (i = 0; i < rejects->nr; i++)
293 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
294 warning(ERRORMSG(o, e), super_prefixed(path.buf,
295 o->super_prefix));
296 strbuf_release(&path);
298 string_list_clear(rejects, 0);
300 if (warning_displayed)
301 fprintf(stderr, _("After fixing the above paths, you may want to run `git sparse-checkout reapply`.\n"));
303 static int check_submodule_move_head(const struct cache_entry *ce,
304 const char *old_id,
305 const char *new_id,
306 struct unpack_trees_options *o)
308 unsigned flags = SUBMODULE_MOVE_HEAD_DRY_RUN;
309 const struct submodule *sub = submodule_from_ce(ce);
311 if (!sub)
312 return 0;
314 if (o->reset)
315 flags |= SUBMODULE_MOVE_HEAD_FORCE;
317 if (submodule_move_head(ce->name, o->super_prefix, old_id, new_id,
318 flags))
319 return add_rejected_path(o, ERROR_WOULD_LOSE_SUBMODULE, ce->name);
320 return 0;
324 * Perform the loading of the repository's gitmodules file. This function is
325 * used by 'check_update()' to perform loading of the gitmodules file in two
326 * different situations:
327 * (1) before removing entries from the working tree if the gitmodules file has
328 * been marked for removal. This situation is specified by 'state' == NULL.
329 * (2) before checking out entries to the working tree if the gitmodules file
330 * has been marked for update. This situation is specified by 'state' != NULL.
332 static void load_gitmodules_file(struct index_state *index,
333 struct checkout *state)
335 int pos = index_name_pos(index, GITMODULES_FILE, strlen(GITMODULES_FILE));
337 if (pos >= 0) {
338 struct cache_entry *ce = index->cache[pos];
339 if (!state && ce->ce_flags & CE_WT_REMOVE) {
340 repo_read_gitmodules(the_repository, 0);
341 } else if (state && (ce->ce_flags & CE_UPDATE)) {
342 submodule_free(the_repository);
343 checkout_entry(ce, state, NULL, NULL);
344 repo_read_gitmodules(the_repository, 0);
349 static struct progress *get_progress(struct unpack_trees_options *o,
350 struct index_state *index)
352 unsigned cnt = 0, total = 0;
354 if (!o->update || !o->verbose_update)
355 return NULL;
357 for (; cnt < index->cache_nr; cnt++) {
358 const struct cache_entry *ce = index->cache[cnt];
359 if (ce->ce_flags & (CE_UPDATE | CE_WT_REMOVE))
360 total++;
363 return start_delayed_progress(_("Updating files"), total);
366 static void setup_collided_checkout_detection(struct checkout *state,
367 struct index_state *index)
369 int i;
371 state->clone = 1;
372 for (i = 0; i < index->cache_nr; i++)
373 index->cache[i]->ce_flags &= ~CE_MATCHED;
376 static void report_collided_checkout(struct index_state *index)
378 struct string_list list = STRING_LIST_INIT_NODUP;
379 int i;
381 for (i = 0; i < index->cache_nr; i++) {
382 struct cache_entry *ce = index->cache[i];
384 if (!(ce->ce_flags & CE_MATCHED))
385 continue;
387 string_list_append(&list, ce->name);
388 ce->ce_flags &= ~CE_MATCHED;
391 list.cmp = fspathcmp;
392 string_list_sort(&list);
394 if (list.nr) {
395 warning(_("the following paths have collided (e.g. case-sensitive paths\n"
396 "on a case-insensitive filesystem) and only one from the same\n"
397 "colliding group is in the working tree:\n"));
399 for (i = 0; i < list.nr; i++)
400 fprintf(stderr, " '%s'\n", list.items[i].string);
403 string_list_clear(&list, 0);
406 static int must_checkout(const struct cache_entry *ce)
408 return ce->ce_flags & CE_UPDATE;
411 static int check_updates(struct unpack_trees_options *o,
412 struct index_state *index)
414 unsigned cnt = 0;
415 int errs = 0;
416 struct progress *progress;
417 struct checkout state = CHECKOUT_INIT;
418 int i, pc_workers, pc_threshold;
420 trace_performance_enter();
421 state.super_prefix = o->super_prefix;
422 state.force = 1;
423 state.quiet = 1;
424 state.refresh_cache = 1;
425 state.istate = index;
426 clone_checkout_metadata(&state.meta, &o->meta, NULL);
428 if (!o->update || o->dry_run) {
429 remove_marked_cache_entries(index, 0);
430 trace_performance_leave("check_updates");
431 return 0;
434 if (o->clone)
435 setup_collided_checkout_detection(&state, index);
437 progress = get_progress(o, index);
439 /* Start with clean cache to avoid using any possibly outdated info. */
440 invalidate_lstat_cache();
442 git_attr_set_direction(GIT_ATTR_CHECKOUT);
444 if (should_update_submodules())
445 load_gitmodules_file(index, NULL);
447 for (i = 0; i < index->cache_nr; i++) {
448 const struct cache_entry *ce = index->cache[i];
450 if (ce->ce_flags & CE_WT_REMOVE) {
451 display_progress(progress, ++cnt);
452 unlink_entry(ce, o->super_prefix);
456 remove_marked_cache_entries(index, 0);
457 remove_scheduled_dirs();
459 if (should_update_submodules())
460 load_gitmodules_file(index, &state);
462 if (has_promisor_remote())
464 * Prefetch the objects that are to be checked out in the loop
465 * below.
467 prefetch_cache_entries(index, must_checkout);
469 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
471 enable_delayed_checkout(&state);
472 if (pc_workers > 1)
473 init_parallel_checkout();
474 for (i = 0; i < index->cache_nr; i++) {
475 struct cache_entry *ce = index->cache[i];
477 if (must_checkout(ce)) {
478 size_t last_pc_queue_size = pc_queue_size();
480 if (ce->ce_flags & CE_WT_REMOVE)
481 BUG("both update and delete flags are set on %s",
482 ce->name);
483 ce->ce_flags &= ~CE_UPDATE;
484 errs |= checkout_entry(ce, &state, NULL, NULL);
486 if (last_pc_queue_size == pc_queue_size())
487 display_progress(progress, ++cnt);
490 if (pc_workers > 1)
491 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
492 progress, &cnt);
493 stop_progress(&progress);
494 errs |= finish_delayed_checkout(&state, o->verbose_update);
495 git_attr_set_direction(GIT_ATTR_CHECKIN);
497 if (o->clone)
498 report_collided_checkout(index);
500 trace_performance_leave("check_updates");
501 return errs != 0;
504 static int verify_uptodate_sparse(const struct cache_entry *ce,
505 struct unpack_trees_options *o);
506 static int verify_absent_sparse(const struct cache_entry *ce,
507 enum unpack_trees_error_types,
508 struct unpack_trees_options *o);
510 static int apply_sparse_checkout(struct index_state *istate,
511 struct cache_entry *ce,
512 struct unpack_trees_options *o)
514 int was_skip_worktree = ce_skip_worktree(ce);
516 if (ce->ce_flags & CE_NEW_SKIP_WORKTREE)
517 ce->ce_flags |= CE_SKIP_WORKTREE;
518 else
519 ce->ce_flags &= ~CE_SKIP_WORKTREE;
520 if (was_skip_worktree != ce_skip_worktree(ce)) {
521 ce->ce_flags |= CE_UPDATE_IN_BASE;
522 mark_fsmonitor_invalid(istate, ce);
523 istate->cache_changed |= CE_ENTRY_CHANGED;
527 * if (!was_skip_worktree && !ce_skip_worktree()) {
528 * This is perfectly normal. Move on;
533 * Merge strategies may set CE_UPDATE|CE_REMOVE outside checkout
534 * area as a result of ce_skip_worktree() shortcuts in
535 * verify_absent() and verify_uptodate().
536 * Make sure they don't modify worktree if they are already
537 * outside checkout area
539 if (was_skip_worktree && ce_skip_worktree(ce)) {
540 ce->ce_flags &= ~CE_UPDATE;
543 * By default, when CE_REMOVE is on, CE_WT_REMOVE is also
544 * on to get that file removed from both index and worktree.
545 * If that file is already outside worktree area, don't
546 * bother remove it.
548 if (ce->ce_flags & CE_REMOVE)
549 ce->ce_flags &= ~CE_WT_REMOVE;
552 if (!was_skip_worktree && ce_skip_worktree(ce)) {
554 * If CE_UPDATE is set, verify_uptodate() must be called already
555 * also stat info may have lost after merged_entry() so calling
556 * verify_uptodate() again may fail
558 if (!(ce->ce_flags & CE_UPDATE) &&
559 verify_uptodate_sparse(ce, o)) {
560 ce->ce_flags &= ~CE_SKIP_WORKTREE;
561 return -1;
563 ce->ce_flags |= CE_WT_REMOVE;
564 ce->ce_flags &= ~CE_UPDATE;
566 if (was_skip_worktree && !ce_skip_worktree(ce)) {
567 if (verify_absent_sparse(ce, WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN, o))
568 return -1;
569 ce->ce_flags |= CE_UPDATE;
571 return 0;
574 static int warn_conflicted_path(struct index_state *istate,
575 int i,
576 struct unpack_trees_options *o)
578 char *conflicting_path = istate->cache[i]->name;
579 int count = 0;
581 add_rejected_path(o, WARNING_SPARSE_UNMERGED_FILE, conflicting_path);
583 /* Find out how many higher stage entries are at same path */
584 while ((++count) + i < istate->cache_nr &&
585 !strcmp(conflicting_path, istate->cache[count + i]->name))
586 ; /* do nothing */
588 return count;
591 static inline int call_unpack_fn(const struct cache_entry * const *src,
592 struct unpack_trees_options *o)
594 int ret = o->fn(src, o);
595 if (ret > 0)
596 ret = 0;
597 return ret;
600 static void mark_ce_used(struct cache_entry *ce, struct unpack_trees_options *o)
602 ce->ce_flags |= CE_UNPACKED;
604 if (o->internal.cache_bottom < o->src_index->cache_nr &&
605 o->src_index->cache[o->internal.cache_bottom] == ce) {
606 int bottom = o->internal.cache_bottom;
608 while (bottom < o->src_index->cache_nr &&
609 o->src_index->cache[bottom]->ce_flags & CE_UNPACKED)
610 bottom++;
611 o->internal.cache_bottom = bottom;
615 static void mark_all_ce_unused(struct index_state *index)
617 int i;
618 for (i = 0; i < index->cache_nr; i++)
619 index->cache[i]->ce_flags &= ~(CE_UNPACKED | CE_ADDED | CE_NEW_SKIP_WORKTREE);
622 static int locate_in_src_index(const struct cache_entry *ce,
623 struct unpack_trees_options *o)
625 struct index_state *index = o->src_index;
626 int len = ce_namelen(ce);
627 int pos = index_name_pos(index, ce->name, len);
628 if (pos < 0)
629 pos = -1 - pos;
630 return pos;
634 * We call unpack_index_entry() with an unmerged cache entry
635 * only in diff-index, and it wants a single callback. Skip
636 * the other unmerged entry with the same name.
638 static void mark_ce_used_same_name(struct cache_entry *ce,
639 struct unpack_trees_options *o)
641 struct index_state *index = o->src_index;
642 int len = ce_namelen(ce);
643 int pos;
645 for (pos = locate_in_src_index(ce, o); pos < index->cache_nr; pos++) {
646 struct cache_entry *next = index->cache[pos];
647 if (len != ce_namelen(next) ||
648 memcmp(ce->name, next->name, len))
649 break;
650 mark_ce_used(next, o);
654 static struct cache_entry *next_cache_entry(struct unpack_trees_options *o)
656 const struct index_state *index = o->src_index;
657 int pos = o->internal.cache_bottom;
659 while (pos < index->cache_nr) {
660 struct cache_entry *ce = index->cache[pos];
661 if (!(ce->ce_flags & CE_UNPACKED))
662 return ce;
663 pos++;
665 return NULL;
668 static void add_same_unmerged(const struct cache_entry *ce,
669 struct unpack_trees_options *o)
671 struct index_state *index = o->src_index;
672 int len = ce_namelen(ce);
673 int pos = index_name_pos(index, ce->name, len);
675 if (0 <= pos)
676 die("programming error in a caller of mark_ce_used_same_name");
677 for (pos = -pos - 1; pos < index->cache_nr; pos++) {
678 struct cache_entry *next = index->cache[pos];
679 if (len != ce_namelen(next) ||
680 memcmp(ce->name, next->name, len))
681 break;
682 add_entry(o, next, 0, 0);
683 mark_ce_used(next, o);
687 static int unpack_index_entry(struct cache_entry *ce,
688 struct unpack_trees_options *o)
690 const struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
691 int ret;
693 src[0] = ce;
695 mark_ce_used(ce, o);
696 if (ce_stage(ce)) {
697 if (o->skip_unmerged) {
698 add_entry(o, ce, 0, 0);
699 return 0;
702 ret = call_unpack_fn(src, o);
703 if (ce_stage(ce))
704 mark_ce_used_same_name(ce, o);
705 return ret;
708 static int find_cache_pos(struct traverse_info *, const char *p, size_t len);
710 static void restore_cache_bottom(struct traverse_info *info, int bottom)
712 struct unpack_trees_options *o = info->data;
714 if (o->diff_index_cached)
715 return;
716 o->internal.cache_bottom = bottom;
719 static int switch_cache_bottom(struct traverse_info *info)
721 struct unpack_trees_options *o = info->data;
722 int ret, pos;
724 if (o->diff_index_cached)
725 return 0;
726 ret = o->internal.cache_bottom;
727 pos = find_cache_pos(info->prev, info->name, info->namelen);
729 if (pos < -1)
730 o->internal.cache_bottom = -2 - pos;
731 else if (pos < 0)
732 o->internal.cache_bottom = o->src_index->cache_nr;
733 return ret;
736 static inline int are_same_oid(struct name_entry *name_j, struct name_entry *name_k)
738 return !is_null_oid(&name_j->oid) && !is_null_oid(&name_k->oid) && oideq(&name_j->oid, &name_k->oid);
741 static int all_trees_same_as_cache_tree(int n, unsigned long dirmask,
742 struct name_entry *names,
743 struct traverse_info *info)
745 struct unpack_trees_options *o = info->data;
746 int i;
748 if (!o->merge || dirmask != ((1 << n) - 1))
749 return 0;
751 for (i = 1; i < n; i++)
752 if (!are_same_oid(names, names + i))
753 return 0;
755 return cache_tree_matches_traversal(o->src_index->cache_tree, names, info);
758 static int index_pos_by_traverse_info(struct name_entry *names,
759 struct traverse_info *info)
761 struct unpack_trees_options *o = info->data;
762 struct strbuf name = STRBUF_INIT;
763 int pos;
765 strbuf_make_traverse_path(&name, info, names->path, names->pathlen);
766 strbuf_addch(&name, '/');
767 pos = index_name_pos(o->src_index, name.buf, name.len);
768 if (pos >= 0) {
769 if (!o->src_index->sparse_index ||
770 !(o->src_index->cache[pos]->ce_flags & CE_SKIP_WORKTREE))
771 BUG("This is a directory and should not exist in index");
772 } else {
773 pos = -pos - 1;
775 if (pos >= o->src_index->cache_nr ||
776 !starts_with(o->src_index->cache[pos]->name, name.buf) ||
777 (pos > 0 && starts_with(o->src_index->cache[pos-1]->name, name.buf)))
778 BUG("pos %d doesn't point to the first entry of %s in index",
779 pos, name.buf);
780 strbuf_release(&name);
781 return pos;
785 * Fast path if we detect that all trees are the same as cache-tree at this
786 * path. We'll walk these trees in an iterative loop using cache-tree/index
787 * instead of ODB since we already know what these trees contain.
789 static int traverse_by_cache_tree(int pos, int nr_entries, int nr_names,
790 struct traverse_info *info)
792 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
793 struct unpack_trees_options *o = info->data;
794 struct cache_entry *tree_ce = NULL;
795 int ce_len = 0;
796 int i, d;
798 if (!o->merge)
799 BUG("We need cache-tree to do this optimization");
802 * Do what unpack_callback() and unpack_single_entry() normally
803 * do. But we walk all paths in an iterative loop instead.
805 * D/F conflicts and higher stage entries are not a concern
806 * because cache-tree would be invalidated and we would never
807 * get here in the first place.
809 for (i = 0; i < nr_entries; i++) {
810 int new_ce_len, len, rc;
812 src[0] = o->src_index->cache[pos + i];
814 len = ce_namelen(src[0]);
815 new_ce_len = cache_entry_size(len);
817 if (new_ce_len > ce_len) {
818 new_ce_len <<= 1;
819 tree_ce = xrealloc(tree_ce, new_ce_len);
820 memset(tree_ce, 0, new_ce_len);
821 ce_len = new_ce_len;
823 tree_ce->ce_flags = create_ce_flags(0);
825 for (d = 1; d <= nr_names; d++)
826 src[d] = tree_ce;
829 tree_ce->ce_mode = src[0]->ce_mode;
830 tree_ce->ce_namelen = len;
831 oidcpy(&tree_ce->oid, &src[0]->oid);
832 memcpy(tree_ce->name, src[0]->name, len + 1);
834 rc = call_unpack_fn((const struct cache_entry * const *)src, o);
835 if (rc < 0) {
836 free(tree_ce);
837 return rc;
840 mark_ce_used(src[0], o);
842 free(tree_ce);
843 if (o->internal.debug_unpack)
844 printf("Unpacked %d entries from %s to %s using cache-tree\n",
845 nr_entries,
846 o->src_index->cache[pos]->name,
847 o->src_index->cache[pos + nr_entries - 1]->name);
848 return 0;
851 static int traverse_trees_recursive(int n, unsigned long dirmask,
852 unsigned long df_conflicts,
853 struct name_entry *names,
854 struct traverse_info *info)
856 struct unpack_trees_options *o = info->data;
857 int i, ret, bottom;
858 int nr_buf = 0;
859 struct tree_desc t[MAX_UNPACK_TREES];
860 void *buf[MAX_UNPACK_TREES];
861 struct traverse_info newinfo;
862 struct name_entry *p;
863 int nr_entries;
865 nr_entries = all_trees_same_as_cache_tree(n, dirmask, names, info);
866 if (nr_entries > 0) {
867 int pos = index_pos_by_traverse_info(names, info);
869 if (!o->merge || df_conflicts)
870 BUG("Wrong condition to get here buddy");
873 * All entries up to 'pos' must have been processed
874 * (i.e. marked CE_UNPACKED) at this point. But to be safe,
875 * save and restore cache_bottom anyway to not miss
876 * unprocessed entries before 'pos'.
878 bottom = o->internal.cache_bottom;
879 ret = traverse_by_cache_tree(pos, nr_entries, n, info);
880 o->internal.cache_bottom = bottom;
881 return ret;
884 p = names;
885 while (!p->mode)
886 p++;
888 newinfo = *info;
889 newinfo.prev = info;
890 newinfo.pathspec = info->pathspec;
891 newinfo.name = p->path;
892 newinfo.namelen = p->pathlen;
893 newinfo.mode = p->mode;
894 newinfo.pathlen = st_add3(newinfo.pathlen, tree_entry_len(p), 1);
895 newinfo.df_conflicts |= df_conflicts;
898 * Fetch the tree from the ODB for each peer directory in the
899 * n commits.
901 * For 2- and 3-way traversals, we try to avoid hitting the
902 * ODB twice for the same OID. This should yield a nice speed
903 * up in checkouts and merges when the commits are similar.
905 * We don't bother doing the full O(n^2) search for larger n,
906 * because wider traversals don't happen that often and we
907 * avoid the search setup.
909 * When 2 peer OIDs are the same, we just copy the tree
910 * descriptor data. This implicitly borrows the buffer
911 * data from the earlier cell.
913 for (i = 0; i < n; i++, dirmask >>= 1) {
914 if (i > 0 && are_same_oid(&names[i], &names[i - 1]))
915 t[i] = t[i - 1];
916 else if (i > 1 && are_same_oid(&names[i], &names[i - 2]))
917 t[i] = t[i - 2];
918 else {
919 const struct object_id *oid = NULL;
920 if (dirmask & 1)
921 oid = &names[i].oid;
922 buf[nr_buf++] = fill_tree_descriptor(the_repository, t + i, oid);
926 bottom = switch_cache_bottom(&newinfo);
927 ret = traverse_trees(o->src_index, n, t, &newinfo);
928 restore_cache_bottom(&newinfo, bottom);
930 for (i = 0; i < nr_buf; i++)
931 free(buf[i]);
933 return ret;
937 * Compare the traverse-path to the cache entry without actually
938 * having to generate the textual representation of the traverse
939 * path.
941 * NOTE! This *only* compares up to the size of the traverse path
942 * itself - the caller needs to do the final check for the cache
943 * entry having more data at the end!
945 static int do_compare_entry_piecewise(const struct cache_entry *ce,
946 const struct traverse_info *info,
947 const char *name, size_t namelen,
948 unsigned mode)
950 int pathlen, ce_len;
951 const char *ce_name;
953 if (info->prev) {
954 int cmp = do_compare_entry_piecewise(ce, info->prev,
955 info->name, info->namelen,
956 info->mode);
957 if (cmp)
958 return cmp;
960 pathlen = info->pathlen;
961 ce_len = ce_namelen(ce);
963 /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
964 if (ce_len < pathlen)
965 return -1;
967 ce_len -= pathlen;
968 ce_name = ce->name + pathlen;
970 return df_name_compare(ce_name, ce_len, S_IFREG, name, namelen, mode);
973 static int do_compare_entry(const struct cache_entry *ce,
974 const struct traverse_info *info,
975 const char *name, size_t namelen,
976 unsigned mode)
978 int pathlen, ce_len;
979 const char *ce_name;
980 int cmp;
981 unsigned ce_mode;
984 * If we have not precomputed the traverse path, it is quicker
985 * to avoid doing so. But if we have precomputed it,
986 * it is quicker to use the precomputed version.
988 if (!info->traverse_path)
989 return do_compare_entry_piecewise(ce, info, name, namelen, mode);
991 cmp = strncmp(ce->name, info->traverse_path, info->pathlen);
992 if (cmp)
993 return cmp;
995 pathlen = info->pathlen;
996 ce_len = ce_namelen(ce);
998 if (ce_len < pathlen)
999 return -1;
1001 ce_len -= pathlen;
1002 ce_name = ce->name + pathlen;
1004 ce_mode = S_ISSPARSEDIR(ce->ce_mode) ? S_IFDIR : S_IFREG;
1005 return df_name_compare(ce_name, ce_len, ce_mode, name, namelen, mode);
1008 static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
1010 int cmp = do_compare_entry(ce, info, n->path, n->pathlen, n->mode);
1011 if (cmp)
1012 return cmp;
1015 * At this point, we know that we have a prefix match. If ce
1016 * is a sparse directory, then allow an exact match. This only
1017 * works when the input name is a directory, since ce->name
1018 * ends in a directory separator.
1020 if (S_ISSPARSEDIR(ce->ce_mode) &&
1021 ce->ce_namelen == traverse_path_len(info, tree_entry_len(n)) + 1)
1022 return 0;
1025 * Even if the beginning compared identically, the ce should
1026 * compare as bigger than a directory leading up to it!
1028 return ce_namelen(ce) > traverse_path_len(info, tree_entry_len(n));
1031 static int ce_in_traverse_path(const struct cache_entry *ce,
1032 const struct traverse_info *info)
1034 if (!info->prev)
1035 return 1;
1036 if (do_compare_entry(ce, info->prev,
1037 info->name, info->namelen, info->mode))
1038 return 0;
1040 * If ce (blob) is the same name as the path (which is a tree
1041 * we will be descending into), it won't be inside it.
1043 return (info->pathlen < ce_namelen(ce));
1046 static struct cache_entry *create_ce_entry(const struct traverse_info *info,
1047 const struct name_entry *n,
1048 int stage,
1049 struct index_state *istate,
1050 int is_transient,
1051 int is_sparse_directory)
1053 size_t len = traverse_path_len(info, tree_entry_len(n));
1054 size_t alloc_len = is_sparse_directory ? len + 1 : len;
1055 struct cache_entry *ce =
1056 is_transient ?
1057 make_empty_transient_cache_entry(alloc_len, NULL) :
1058 make_empty_cache_entry(istate, alloc_len);
1060 ce->ce_mode = create_ce_mode(n->mode);
1061 ce->ce_flags = create_ce_flags(stage);
1062 ce->ce_namelen = len;
1063 oidcpy(&ce->oid, &n->oid);
1064 /* len+1 because the cache_entry allocates space for NUL */
1065 make_traverse_path(ce->name, len + 1, info, n->path, n->pathlen);
1067 if (is_sparse_directory) {
1068 ce->name[len] = '/';
1069 ce->name[len + 1] = '\0';
1070 ce->ce_namelen++;
1071 ce->ce_flags |= CE_SKIP_WORKTREE;
1074 return ce;
1078 * Determine whether the path specified by 'p' should be unpacked as a new
1079 * sparse directory in a sparse index. A new sparse directory 'A/':
1080 * - must be outside the sparse cone.
1081 * - must not already be in the index (i.e., no index entry with name 'A/'
1082 * exists).
1083 * - must not have any child entries in the index (i.e., no index entry
1084 * 'A/<something>' exists).
1085 * If 'p' meets the above requirements, return 1; otherwise, return 0.
1087 static int entry_is_new_sparse_dir(const struct traverse_info *info,
1088 const struct name_entry *p)
1090 int res, pos;
1091 struct strbuf dirpath = STRBUF_INIT;
1092 struct unpack_trees_options *o = info->data;
1094 if (!S_ISDIR(p->mode))
1095 return 0;
1098 * If the path is inside the sparse cone, it can't be a sparse directory.
1100 strbuf_add(&dirpath, info->traverse_path, info->pathlen);
1101 strbuf_add(&dirpath, p->path, p->pathlen);
1102 strbuf_addch(&dirpath, '/');
1103 if (path_in_cone_mode_sparse_checkout(dirpath.buf, o->src_index)) {
1104 res = 0;
1105 goto cleanup;
1108 pos = index_name_pos_sparse(o->src_index, dirpath.buf, dirpath.len);
1109 if (pos >= 0) {
1110 /* Path is already in the index, not a new sparse dir */
1111 res = 0;
1112 goto cleanup;
1115 /* Where would this sparse dir be inserted into the index? */
1116 pos = -pos - 1;
1117 if (pos >= o->src_index->cache_nr) {
1119 * Sparse dir would be inserted at the end of the index, so we
1120 * know it has no child entries.
1122 res = 1;
1123 goto cleanup;
1127 * If the dir has child entries in the index, the first would be at the
1128 * position the sparse directory would be inserted. If the entry at this
1129 * position is inside the dir, not a new sparse dir.
1131 res = strncmp(o->src_index->cache[pos]->name, dirpath.buf, dirpath.len);
1133 cleanup:
1134 strbuf_release(&dirpath);
1135 return res;
1139 * Note that traverse_by_cache_tree() duplicates some logic in this function
1140 * without actually calling it. If you change the logic here you may need to
1141 * check and change there as well.
1143 static int unpack_single_entry(int n, unsigned long mask,
1144 unsigned long dirmask,
1145 struct cache_entry **src,
1146 const struct name_entry *names,
1147 const struct traverse_info *info,
1148 int *is_new_sparse_dir)
1150 int i;
1151 struct unpack_trees_options *o = info->data;
1152 unsigned long conflicts = info->df_conflicts | dirmask;
1153 const struct name_entry *p = names;
1155 *is_new_sparse_dir = 0;
1156 if (mask == dirmask && !src[0]) {
1158 * If we're not in a sparse index, we can't unpack a directory
1159 * without recursing into it, so we return.
1161 if (!o->src_index->sparse_index)
1162 return 0;
1164 /* Find first entry with a real name (we could use "mask" too) */
1165 while (!p->mode)
1166 p++;
1169 * If the directory is completely missing from the index but
1170 * would otherwise be a sparse directory, we should unpack it.
1171 * If not, we'll return and continue recursively traversing the
1172 * tree.
1174 *is_new_sparse_dir = entry_is_new_sparse_dir(info, p);
1175 if (!*is_new_sparse_dir)
1176 return 0;
1180 * When we are unpacking a sparse directory, then this isn't necessarily
1181 * a directory-file conflict.
1183 if (mask == dirmask &&
1184 (*is_new_sparse_dir || (src[0] && S_ISSPARSEDIR(src[0]->ce_mode))))
1185 conflicts = 0;
1188 * Ok, we've filled in up to any potential index entry in src[0],
1189 * now do the rest.
1191 for (i = 0; i < n; i++) {
1192 int stage;
1193 unsigned int bit = 1ul << i;
1194 if (conflicts & bit) {
1195 src[i + o->merge] = o->df_conflict_entry;
1196 continue;
1198 if (!(mask & bit))
1199 continue;
1200 if (!o->merge)
1201 stage = 0;
1202 else if (i + 1 < o->head_idx)
1203 stage = 1;
1204 else if (i + 1 > o->head_idx)
1205 stage = 3;
1206 else
1207 stage = 2;
1210 * If the merge bit is set, then the cache entries are
1211 * discarded in the following block. In this case,
1212 * construct "transient" cache_entries, as they are
1213 * not stored in the index. otherwise construct the
1214 * cache entry from the index aware logic.
1216 src[i + o->merge] = create_ce_entry(info, names + i, stage,
1217 &o->internal.result,
1218 o->merge, bit & dirmask);
1221 if (o->merge) {
1222 int rc = call_unpack_fn((const struct cache_entry * const *)src,
1224 for (i = 0; i < n; i++) {
1225 struct cache_entry *ce = src[i + o->merge];
1226 if (ce != o->df_conflict_entry)
1227 discard_cache_entry(ce);
1229 return rc;
1232 for (i = 0; i < n; i++)
1233 if (src[i] && src[i] != o->df_conflict_entry)
1234 if (do_add_entry(o, src[i], 0, 0))
1235 return -1;
1237 return 0;
1240 static int unpack_failed(struct unpack_trees_options *o, const char *message)
1242 discard_index(&o->internal.result);
1243 if (!o->quiet && !o->exiting_early) {
1244 if (message)
1245 return error("%s", message);
1246 return -1;
1248 return -1;
1252 * The tree traversal is looking at name p. If we have a matching entry,
1253 * return it. If name p is a directory in the index, do not return
1254 * anything, as we will want to match it when the traversal descends into
1255 * the directory.
1257 static int find_cache_pos(struct traverse_info *info,
1258 const char *p, size_t p_len)
1260 int pos;
1261 struct unpack_trees_options *o = info->data;
1262 struct index_state *index = o->src_index;
1263 int pfxlen = info->pathlen;
1265 for (pos = o->internal.cache_bottom; pos < index->cache_nr; pos++) {
1266 const struct cache_entry *ce = index->cache[pos];
1267 const char *ce_name, *ce_slash;
1268 int cmp, ce_len;
1270 if (ce->ce_flags & CE_UNPACKED) {
1272 * cache_bottom entry is already unpacked, so
1273 * we can never match it; don't check it
1274 * again.
1276 if (pos == o->internal.cache_bottom)
1277 ++o->internal.cache_bottom;
1278 continue;
1280 if (!ce_in_traverse_path(ce, info)) {
1282 * Check if we can skip future cache checks
1283 * (because we're already past all possible
1284 * entries in the traverse path).
1286 if (info->traverse_path) {
1287 if (strncmp(ce->name, info->traverse_path,
1288 info->pathlen) > 0)
1289 break;
1291 continue;
1293 ce_name = ce->name + pfxlen;
1294 ce_slash = strchr(ce_name, '/');
1295 if (ce_slash)
1296 ce_len = ce_slash - ce_name;
1297 else
1298 ce_len = ce_namelen(ce) - pfxlen;
1299 cmp = name_compare(p, p_len, ce_name, ce_len);
1301 * Exact match; if we have a directory we need to
1302 * delay returning it.
1304 if (!cmp)
1305 return ce_slash ? -2 - pos : pos;
1306 if (0 < cmp)
1307 continue; /* keep looking */
1309 * ce_name sorts after p->path; could it be that we
1310 * have files under p->path directory in the index?
1311 * E.g. ce_name == "t-i", and p->path == "t"; we may
1312 * have "t/a" in the index.
1314 if (p_len < ce_len && !memcmp(ce_name, p, p_len) &&
1315 ce_name[p_len] < '/')
1316 continue; /* keep looking */
1317 break;
1319 return -1;
1323 * Given a sparse directory entry 'ce', compare ce->name to
1324 * info->traverse_path + p->path + '/' if info->traverse_path
1325 * is non-empty.
1327 * Compare ce->name to p->path + '/' otherwise. Note that
1328 * ce->name must end in a trailing '/' because it is a sparse
1329 * directory entry.
1331 static int sparse_dir_matches_path(const struct cache_entry *ce,
1332 struct traverse_info *info,
1333 const struct name_entry *p)
1335 assert(S_ISSPARSEDIR(ce->ce_mode));
1336 assert(ce->name[ce->ce_namelen - 1] == '/');
1338 if (info->pathlen)
1339 return ce->ce_namelen == info->pathlen + p->pathlen + 1 &&
1340 ce->name[info->pathlen - 1] == '/' &&
1341 !strncmp(ce->name, info->traverse_path, info->pathlen) &&
1342 !strncmp(ce->name + info->pathlen, p->path, p->pathlen);
1343 return ce->ce_namelen == p->pathlen + 1 &&
1344 !strncmp(ce->name, p->path, p->pathlen);
1347 static struct cache_entry *find_cache_entry(struct traverse_info *info,
1348 const struct name_entry *p)
1350 const char *path;
1351 int pos = find_cache_pos(info, p->path, p->pathlen);
1352 struct unpack_trees_options *o = info->data;
1354 if (0 <= pos)
1355 return o->src_index->cache[pos];
1358 * Check for a sparse-directory entry named "path/".
1359 * Due to the input p->path not having a trailing
1360 * slash, the negative 'pos' value overshoots the
1361 * expected position, hence "-2" instead of "-1".
1363 pos = -pos - 2;
1365 if (pos < 0 || pos >= o->src_index->cache_nr)
1366 return NULL;
1369 * Due to lexicographic sorting and sparse directory
1370 * entries ending with a trailing slash, our path as a
1371 * sparse directory (e.g "subdir/") and our path as a
1372 * file (e.g. "subdir") might be separated by other
1373 * paths (e.g. "subdir-").
1375 while (pos >= 0) {
1376 struct cache_entry *ce = o->src_index->cache[pos];
1378 if (!skip_prefix(ce->name, info->traverse_path, &path) ||
1379 strncmp(path, p->path, p->pathlen) ||
1380 path[p->pathlen] != '/')
1381 return NULL;
1383 if (S_ISSPARSEDIR(ce->ce_mode) &&
1384 sparse_dir_matches_path(ce, info, p))
1385 return ce;
1387 pos--;
1390 return NULL;
1393 static void debug_path(struct traverse_info *info)
1395 if (info->prev) {
1396 debug_path(info->prev);
1397 if (*info->prev->name)
1398 putchar('/');
1400 printf("%s", info->name);
1403 static void debug_name_entry(int i, struct name_entry *n)
1405 printf("ent#%d %06o %s\n", i,
1406 n->path ? n->mode : 0,
1407 n->path ? n->path : "(missing)");
1410 static void debug_unpack_callback(int n,
1411 unsigned long mask,
1412 unsigned long dirmask,
1413 struct name_entry *names,
1414 struct traverse_info *info)
1416 int i;
1417 printf("* unpack mask %lu, dirmask %lu, cnt %d ",
1418 mask, dirmask, n);
1419 debug_path(info);
1420 putchar('\n');
1421 for (i = 0; i < n; i++)
1422 debug_name_entry(i, names + i);
1426 * Returns true if and only if the given cache_entry is a
1427 * sparse-directory entry that matches the given name_entry
1428 * from the tree walk at the given traverse_info.
1430 static int is_sparse_directory_entry(struct cache_entry *ce,
1431 const struct name_entry *name,
1432 struct traverse_info *info)
1434 if (!ce || !name || !S_ISSPARSEDIR(ce->ce_mode))
1435 return 0;
1437 return sparse_dir_matches_path(ce, info, name);
1440 static int unpack_sparse_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1442 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1443 struct unpack_trees_options *o = info->data;
1444 int ret, is_new_sparse_dir;
1446 assert(o->merge);
1449 * Unlike in 'unpack_callback', where src[0] is derived from the index when
1450 * merging, src[0] is a transient cache entry derived from the first tree
1451 * provided. Create the temporary entry as if it came from a non-sparse index.
1453 if (!is_null_oid(&names[0].oid)) {
1454 src[0] = create_ce_entry(info, &names[0], 0,
1455 &o->internal.result, 1,
1456 dirmask & (1ul << 0));
1457 src[0]->ce_flags |= (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1461 * 'unpack_single_entry' assumes that src[0] is derived directly from
1462 * the index, rather than from an entry in 'names'. This is *not* true when
1463 * merging a sparse directory, in which case names[0] is the "index" source
1464 * entry. To match the expectations of 'unpack_single_entry', shift past the
1465 * "index" tree (i.e., names[0]) and adjust 'names', 'n', 'mask', and
1466 * 'dirmask' accordingly.
1468 ret = unpack_single_entry(n - 1, mask >> 1, dirmask >> 1, src, names + 1, info, &is_new_sparse_dir);
1470 if (src[0])
1471 discard_cache_entry(src[0]);
1473 return ret >= 0 ? mask : -1;
1477 * Note that traverse_by_cache_tree() duplicates some logic in this function
1478 * without actually calling it. If you change the logic here you may need to
1479 * check and change there as well.
1481 static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1483 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1484 struct unpack_trees_options *o = info->data;
1485 const struct name_entry *p = names;
1486 int is_new_sparse_dir;
1488 /* Find first entry with a real name (we could use "mask" too) */
1489 while (!p->mode)
1490 p++;
1492 if (o->internal.debug_unpack)
1493 debug_unpack_callback(n, mask, dirmask, names, info);
1495 /* Are we supposed to look at the index too? */
1496 if (o->merge) {
1497 while (1) {
1498 int cmp;
1499 struct cache_entry *ce;
1501 if (o->diff_index_cached)
1502 ce = next_cache_entry(o);
1503 else
1504 ce = find_cache_entry(info, p);
1506 if (!ce)
1507 break;
1508 cmp = compare_entry(ce, info, p);
1509 if (cmp < 0) {
1510 if (unpack_index_entry(ce, o) < 0)
1511 return unpack_failed(o, NULL);
1512 continue;
1514 if (!cmp) {
1515 if (ce_stage(ce)) {
1517 * If we skip unmerged index
1518 * entries, we'll skip this
1519 * entry *and* the tree
1520 * entries associated with it!
1522 if (o->skip_unmerged) {
1523 add_same_unmerged(ce, o);
1524 return mask;
1527 src[0] = ce;
1529 break;
1533 if (unpack_single_entry(n, mask, dirmask, src, names, info, &is_new_sparse_dir))
1534 return -1;
1536 if (o->merge && src[0]) {
1537 if (ce_stage(src[0]))
1538 mark_ce_used_same_name(src[0], o);
1539 else
1540 mark_ce_used(src[0], o);
1543 /* Now handle any directories.. */
1544 if (dirmask) {
1545 /* special case: "diff-index --cached" looking at a tree */
1546 if (o->diff_index_cached &&
1547 n == 1 && dirmask == 1 && S_ISDIR(names->mode)) {
1548 int matches;
1549 matches = cache_tree_matches_traversal(o->src_index->cache_tree,
1550 names, info);
1552 * Everything under the name matches; skip the
1553 * entire hierarchy. diff_index_cached codepath
1554 * special cases D/F conflicts in such a way that
1555 * it does not do any look-ahead, so this is safe.
1557 if (matches) {
1559 * Only increment the cache_bottom if the
1560 * directory isn't a sparse directory index
1561 * entry (if it is, it was already incremented)
1562 * in 'mark_ce_used()'
1564 if (!src[0] || !S_ISSPARSEDIR(src[0]->ce_mode))
1565 o->internal.cache_bottom += matches;
1566 return mask;
1570 if (!is_sparse_directory_entry(src[0], p, info) &&
1571 !is_new_sparse_dir &&
1572 traverse_trees_recursive(n, dirmask, mask & ~dirmask,
1573 names, info) < 0) {
1574 return -1;
1577 return mask;
1580 return mask;
1583 static int clear_ce_flags_1(struct index_state *istate,
1584 struct cache_entry **cache, int nr,
1585 struct strbuf *prefix,
1586 int select_mask, int clear_mask,
1587 struct pattern_list *pl,
1588 enum pattern_match_result default_match,
1589 int progress_nr);
1591 /* Whole directory matching */
1592 static int clear_ce_flags_dir(struct index_state *istate,
1593 struct cache_entry **cache, int nr,
1594 struct strbuf *prefix,
1595 char *basename,
1596 int select_mask, int clear_mask,
1597 struct pattern_list *pl,
1598 enum pattern_match_result default_match,
1599 int progress_nr)
1601 struct cache_entry **cache_end;
1602 int dtype = DT_DIR;
1603 int rc;
1604 enum pattern_match_result ret, orig_ret;
1605 orig_ret = path_matches_pattern_list(prefix->buf, prefix->len,
1606 basename, &dtype, pl, istate);
1608 strbuf_addch(prefix, '/');
1610 /* If undecided, use matching result of parent dir in defval */
1611 if (orig_ret == UNDECIDED)
1612 ret = default_match;
1613 else
1614 ret = orig_ret;
1616 for (cache_end = cache; cache_end != cache + nr; cache_end++) {
1617 struct cache_entry *ce = *cache_end;
1618 if (strncmp(ce->name, prefix->buf, prefix->len))
1619 break;
1622 if (pl->use_cone_patterns && orig_ret == MATCHED_RECURSIVE) {
1623 struct cache_entry **ce = cache;
1624 rc = cache_end - cache;
1626 while (ce < cache_end) {
1627 (*ce)->ce_flags &= ~clear_mask;
1628 ce++;
1630 } else if (pl->use_cone_patterns && orig_ret == NOT_MATCHED) {
1631 rc = cache_end - cache;
1632 } else {
1633 rc = clear_ce_flags_1(istate, cache, cache_end - cache,
1634 prefix,
1635 select_mask, clear_mask,
1636 pl, ret,
1637 progress_nr);
1640 strbuf_setlen(prefix, prefix->len - 1);
1641 return rc;
1645 * Traverse the index, find every entry that matches according to
1646 * o->pl. Do "ce_flags &= ~clear_mask" on those entries. Return the
1647 * number of traversed entries.
1649 * If select_mask is non-zero, only entries whose ce_flags has on of
1650 * those bits enabled are traversed.
1652 * cache : pointer to an index entry
1653 * prefix_len : an offset to its path
1655 * The current path ("prefix") including the trailing '/' is
1656 * cache[0]->name[0..(prefix_len-1)]
1657 * Top level path has prefix_len zero.
1659 static int clear_ce_flags_1(struct index_state *istate,
1660 struct cache_entry **cache, int nr,
1661 struct strbuf *prefix,
1662 int select_mask, int clear_mask,
1663 struct pattern_list *pl,
1664 enum pattern_match_result default_match,
1665 int progress_nr)
1667 struct cache_entry **cache_end = nr ? cache + nr : cache;
1670 * Process all entries that have the given prefix and meet
1671 * select_mask condition
1673 while(cache != cache_end) {
1674 struct cache_entry *ce = *cache;
1675 const char *name, *slash;
1676 int len, dtype;
1677 enum pattern_match_result ret;
1679 display_progress(istate->progress, progress_nr);
1681 if (select_mask && !(ce->ce_flags & select_mask)) {
1682 cache++;
1683 progress_nr++;
1684 continue;
1687 if (prefix->len && strncmp(ce->name, prefix->buf, prefix->len))
1688 break;
1690 name = ce->name + prefix->len;
1691 slash = strchr(name, '/');
1693 /* If it's a directory, try whole directory match first */
1694 if (slash) {
1695 int processed;
1697 len = slash - name;
1698 strbuf_add(prefix, name, len);
1700 processed = clear_ce_flags_dir(istate, cache, cache_end - cache,
1701 prefix,
1702 prefix->buf + prefix->len - len,
1703 select_mask, clear_mask,
1704 pl, default_match,
1705 progress_nr);
1707 /* clear_c_f_dir eats a whole dir already? */
1708 if (processed) {
1709 cache += processed;
1710 progress_nr += processed;
1711 strbuf_setlen(prefix, prefix->len - len);
1712 continue;
1715 strbuf_addch(prefix, '/');
1716 processed = clear_ce_flags_1(istate, cache, cache_end - cache,
1717 prefix,
1718 select_mask, clear_mask, pl,
1719 default_match, progress_nr);
1721 cache += processed;
1722 progress_nr += processed;
1724 strbuf_setlen(prefix, prefix->len - len - 1);
1725 continue;
1728 /* Non-directory */
1729 dtype = ce_to_dtype(ce);
1730 ret = path_matches_pattern_list(ce->name,
1731 ce_namelen(ce),
1732 name, &dtype, pl, istate);
1733 if (ret == UNDECIDED)
1734 ret = default_match;
1735 if (ret == MATCHED || ret == MATCHED_RECURSIVE)
1736 ce->ce_flags &= ~clear_mask;
1737 cache++;
1738 progress_nr++;
1741 display_progress(istate->progress, progress_nr);
1742 return nr - (cache_end - cache);
1745 static int clear_ce_flags(struct index_state *istate,
1746 int select_mask, int clear_mask,
1747 struct pattern_list *pl,
1748 int show_progress)
1750 static struct strbuf prefix = STRBUF_INIT;
1751 char label[100];
1752 int rval;
1754 strbuf_reset(&prefix);
1755 if (show_progress)
1756 istate->progress = start_delayed_progress(
1757 _("Updating index flags"),
1758 istate->cache_nr);
1760 xsnprintf(label, sizeof(label), "clear_ce_flags(0x%08lx,0x%08lx)",
1761 (unsigned long)select_mask, (unsigned long)clear_mask);
1762 trace2_region_enter("unpack_trees", label, the_repository);
1763 rval = clear_ce_flags_1(istate,
1764 istate->cache,
1765 istate->cache_nr,
1766 &prefix,
1767 select_mask, clear_mask,
1768 pl, 0, 0);
1769 trace2_region_leave("unpack_trees", label, the_repository);
1771 stop_progress(&istate->progress);
1772 return rval;
1776 * Set/Clear CE_NEW_SKIP_WORKTREE according to $GIT_DIR/info/sparse-checkout
1778 static void mark_new_skip_worktree(struct pattern_list *pl,
1779 struct index_state *istate,
1780 int select_flag, int skip_wt_flag,
1781 int show_progress)
1783 int i;
1786 * 1. Pretend the narrowest worktree: only unmerged entries
1787 * are checked out
1789 for (i = 0; i < istate->cache_nr; i++) {
1790 struct cache_entry *ce = istate->cache[i];
1792 if (select_flag && !(ce->ce_flags & select_flag))
1793 continue;
1795 if (!ce_stage(ce) && !(ce->ce_flags & CE_CONFLICTED))
1796 ce->ce_flags |= skip_wt_flag;
1797 else
1798 ce->ce_flags &= ~skip_wt_flag;
1802 * 2. Widen worktree according to sparse-checkout file.
1803 * Matched entries will have skip_wt_flag cleared (i.e. "in")
1805 clear_ce_flags(istate, select_flag, skip_wt_flag, pl, show_progress);
1808 static void populate_from_existing_patterns(struct unpack_trees_options *o,
1809 struct pattern_list *pl)
1811 if (get_sparse_checkout_patterns(pl) < 0)
1812 o->skip_sparse_checkout = 1;
1813 else
1814 o->internal.pl = pl;
1817 static void update_sparsity_for_prefix(const char *prefix,
1818 struct index_state *istate)
1820 int prefix_len = strlen(prefix);
1821 struct strbuf ce_prefix = STRBUF_INIT;
1823 if (!istate->sparse_index)
1824 return;
1826 while (prefix_len > 0 && prefix[prefix_len - 1] == '/')
1827 prefix_len--;
1829 if (prefix_len <= 0)
1830 BUG("Invalid prefix passed to update_sparsity_for_prefix");
1832 strbuf_grow(&ce_prefix, prefix_len + 1);
1833 strbuf_add(&ce_prefix, prefix, prefix_len);
1834 strbuf_addch(&ce_prefix, '/');
1837 * If the prefix points to a sparse directory or a path inside a sparse
1838 * directory, the index should be expanded. This is accomplished in one
1839 * of two ways:
1840 * - if the prefix is inside a sparse directory, it will be expanded by
1841 * the 'ensure_full_index(...)' call in 'index_name_pos(...)'.
1842 * - if the prefix matches an existing sparse directory entry,
1843 * 'index_name_pos(...)' will return its index position, triggering
1844 * the 'ensure_full_index(...)' below.
1846 if (!path_in_cone_mode_sparse_checkout(ce_prefix.buf, istate) &&
1847 index_name_pos(istate, ce_prefix.buf, ce_prefix.len) >= 0)
1848 ensure_full_index(istate);
1850 strbuf_release(&ce_prefix);
1853 static int verify_absent(const struct cache_entry *,
1854 enum unpack_trees_error_types,
1855 struct unpack_trees_options *);
1857 * N-way merge "len" trees. Returns 0 on success, -1 on failure to manipulate the
1858 * resulting index, -2 on failure to reflect the changes to the work tree.
1860 * CE_ADDED, CE_UNPACKED and CE_NEW_SKIP_WORKTREE are used internally
1862 int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
1864 struct repository *repo = the_repository;
1865 int i, ret;
1866 static struct cache_entry *dfc;
1867 struct pattern_list pl;
1868 int free_pattern_list = 0;
1869 struct dir_struct dir = DIR_INIT;
1871 if (o->reset == UNPACK_RESET_INVALID)
1872 BUG("o->reset had a value of 1; should be UNPACK_TREES_*_UNTRACKED");
1874 if (len > MAX_UNPACK_TREES)
1875 die("unpack_trees takes at most %d trees", MAX_UNPACK_TREES);
1876 if (o->internal.dir)
1877 BUG("o->internal.dir is for internal use only");
1878 if (o->internal.pl)
1879 BUG("o->internal.pl is for internal use only");
1880 if (o->df_conflict_entry)
1881 BUG("o->df_conflict_entry is an output only field");
1883 trace_performance_enter();
1884 trace2_region_enter("unpack_trees", "unpack_trees", the_repository);
1886 prepare_repo_settings(repo);
1887 if (repo->settings.command_requires_full_index) {
1888 ensure_full_index(o->src_index);
1889 if (o->dst_index)
1890 ensure_full_index(o->dst_index);
1893 if (o->reset == UNPACK_RESET_OVERWRITE_UNTRACKED &&
1894 o->preserve_ignored)
1895 BUG("UNPACK_RESET_OVERWRITE_UNTRACKED incompatible with preserved ignored files");
1897 if (!o->preserve_ignored) {
1898 o->internal.dir = &dir;
1899 o->internal.dir->flags |= DIR_SHOW_IGNORED;
1900 setup_standard_excludes(o->internal.dir);
1903 if (o->prefix)
1904 update_sparsity_for_prefix(o->prefix, o->src_index);
1906 if (!core_apply_sparse_checkout || !o->update)
1907 o->skip_sparse_checkout = 1;
1908 if (!o->skip_sparse_checkout) {
1909 memset(&pl, 0, sizeof(pl));
1910 free_pattern_list = 1;
1911 populate_from_existing_patterns(o, &pl);
1914 index_state_init(&o->internal.result, o->src_index->repo);
1915 o->internal.result.initialized = 1;
1916 o->internal.result.timestamp.sec = o->src_index->timestamp.sec;
1917 o->internal.result.timestamp.nsec = o->src_index->timestamp.nsec;
1918 o->internal.result.version = o->src_index->version;
1919 if (!o->src_index->split_index) {
1920 o->internal.result.split_index = NULL;
1921 } else if (o->src_index == o->dst_index) {
1923 * o->dst_index (and thus o->src_index) will be discarded
1924 * and overwritten with o->internal.result at the end of
1925 * this function, so just use src_index's split_index to
1926 * avoid having to create a new one.
1928 o->internal.result.split_index = o->src_index->split_index;
1929 o->internal.result.split_index->refcount++;
1930 } else {
1931 o->internal.result.split_index =
1932 init_split_index(&o->internal.result);
1934 oidcpy(&o->internal.result.oid, &o->src_index->oid);
1935 o->internal.merge_size = len;
1936 mark_all_ce_unused(o->src_index);
1938 o->internal.result.fsmonitor_last_update =
1939 xstrdup_or_null(o->src_index->fsmonitor_last_update);
1940 o->internal.result.fsmonitor_has_run_once = o->src_index->fsmonitor_has_run_once;
1942 if (!o->src_index->initialized &&
1943 !repo->settings.command_requires_full_index &&
1944 is_sparse_index_allowed(&o->internal.result, 0))
1945 o->internal.result.sparse_index = 1;
1948 * Sparse checkout loop #1: set NEW_SKIP_WORKTREE on existing entries
1950 if (!o->skip_sparse_checkout)
1951 mark_new_skip_worktree(o->internal.pl, o->src_index, 0,
1952 CE_NEW_SKIP_WORKTREE, o->verbose_update);
1954 if (!dfc)
1955 dfc = xcalloc(1, cache_entry_size(0));
1956 o->df_conflict_entry = dfc;
1958 if (len) {
1959 const char *prefix = o->prefix ? o->prefix : "";
1960 struct traverse_info info;
1962 setup_traverse_info(&info, prefix);
1963 info.fn = unpack_callback;
1964 info.data = o;
1965 info.show_all_errors = o->internal.show_all_errors;
1966 info.pathspec = o->pathspec;
1968 if (o->prefix) {
1970 * Unpack existing index entries that sort before the
1971 * prefix the tree is spliced into. Note that o->merge
1972 * is always true in this case.
1974 while (1) {
1975 struct cache_entry *ce = next_cache_entry(o);
1976 if (!ce)
1977 break;
1978 if (ce_in_traverse_path(ce, &info))
1979 break;
1980 if (unpack_index_entry(ce, o) < 0)
1981 goto return_failed;
1985 trace_performance_enter();
1986 trace2_region_enter("unpack_trees", "traverse_trees", the_repository);
1987 ret = traverse_trees(o->src_index, len, t, &info);
1988 trace2_region_leave("unpack_trees", "traverse_trees", the_repository);
1989 trace_performance_leave("traverse_trees");
1990 if (ret < 0)
1991 goto return_failed;
1994 /* Any left-over entries in the index? */
1995 if (o->merge) {
1996 while (1) {
1997 struct cache_entry *ce = next_cache_entry(o);
1998 if (!ce)
1999 break;
2000 if (unpack_index_entry(ce, o) < 0)
2001 goto return_failed;
2004 mark_all_ce_unused(o->src_index);
2006 if (o->trivial_merges_only && o->internal.nontrivial_merge) {
2007 ret = unpack_failed(o, "Merge requires file-level merging");
2008 goto done;
2011 if (!o->skip_sparse_checkout) {
2013 * Sparse checkout loop #2: set NEW_SKIP_WORKTREE on entries not in loop #1
2014 * If they will have NEW_SKIP_WORKTREE, also set CE_SKIP_WORKTREE
2015 * so apply_sparse_checkout() won't attempt to remove it from worktree
2017 mark_new_skip_worktree(o->internal.pl, &o->internal.result,
2018 CE_ADDED, CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE,
2019 o->verbose_update);
2021 ret = 0;
2022 for (i = 0; i < o->internal.result.cache_nr; i++) {
2023 struct cache_entry *ce = o->internal.result.cache[i];
2026 * Entries marked with CE_ADDED in merged_entry() do not have
2027 * verify_absent() check (the check is effectively disabled
2028 * because CE_NEW_SKIP_WORKTREE is set unconditionally).
2030 * Do the real check now because we have had
2031 * correct CE_NEW_SKIP_WORKTREE
2033 if (ce->ce_flags & CE_ADDED &&
2034 verify_absent(ce, WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN, o))
2035 ret = 1;
2037 if (apply_sparse_checkout(&o->internal.result, ce, o))
2038 ret = 1;
2040 if (ret == 1) {
2042 * Inability to sparsify or de-sparsify individual
2043 * paths is not an error, but just a warning.
2045 if (o->internal.show_all_errors)
2046 display_warning_msgs(o);
2047 ret = 0;
2051 ret = check_updates(o, &o->internal.result) ? (-2) : 0;
2052 if (o->dst_index) {
2053 move_index_extensions(&o->internal.result, o->src_index);
2054 if (!ret) {
2055 if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0))
2056 cache_tree_verify(the_repository,
2057 &o->internal.result);
2058 if (!o->skip_cache_tree_update &&
2059 !cache_tree_fully_valid(o->internal.result.cache_tree))
2060 cache_tree_update(&o->internal.result,
2061 WRITE_TREE_SILENT |
2062 WRITE_TREE_REPAIR);
2065 o->internal.result.updated_workdir = 1;
2066 discard_index(o->dst_index);
2067 *o->dst_index = o->internal.result;
2068 } else {
2069 discard_index(&o->internal.result);
2071 o->src_index = NULL;
2073 done:
2074 if (free_pattern_list)
2075 clear_pattern_list(&pl);
2076 if (o->internal.dir) {
2077 dir_clear(o->internal.dir);
2078 o->internal.dir = NULL;
2080 trace2_region_leave("unpack_trees", "unpack_trees", the_repository);
2081 trace_performance_leave("unpack_trees");
2082 return ret;
2084 return_failed:
2085 if (o->internal.show_all_errors)
2086 display_error_msgs(o);
2087 mark_all_ce_unused(o->src_index);
2088 ret = unpack_failed(o, NULL);
2089 if (o->exiting_early)
2090 ret = 0;
2091 goto done;
2095 * Update SKIP_WORKTREE bits according to sparsity patterns, and update
2096 * working directory to match.
2098 * CE_NEW_SKIP_WORKTREE is used internally.
2100 enum update_sparsity_result update_sparsity(struct unpack_trees_options *o,
2101 struct pattern_list *pl)
2103 enum update_sparsity_result ret = UPDATE_SPARSITY_SUCCESS;
2104 int i;
2105 unsigned old_show_all_errors;
2106 int free_pattern_list = 0;
2108 old_show_all_errors = o->internal.show_all_errors;
2109 o->internal.show_all_errors = 1;
2110 index_state_init(&o->internal.result, o->src_index->repo);
2112 /* Sanity checks */
2113 if (!o->update || o->index_only || o->skip_sparse_checkout)
2114 BUG("update_sparsity() is for reflecting sparsity patterns in working directory");
2115 if (o->src_index != o->dst_index || o->fn)
2116 BUG("update_sparsity() called wrong");
2118 trace_performance_enter();
2120 /* If we weren't given patterns, use the recorded ones */
2121 if (!pl) {
2122 free_pattern_list = 1;
2123 pl = xcalloc(1, sizeof(*pl));
2124 populate_from_existing_patterns(o, pl);
2126 o->internal.pl = pl;
2128 /* Expand sparse directories as needed */
2129 expand_index(o->src_index, o->internal.pl);
2131 /* Set NEW_SKIP_WORKTREE on existing entries. */
2132 mark_all_ce_unused(o->src_index);
2133 mark_new_skip_worktree(o->internal.pl, o->src_index, 0,
2134 CE_NEW_SKIP_WORKTREE, o->verbose_update);
2136 /* Then loop over entries and update/remove as needed */
2137 ret = UPDATE_SPARSITY_SUCCESS;
2138 for (i = 0; i < o->src_index->cache_nr; i++) {
2139 struct cache_entry *ce = o->src_index->cache[i];
2142 if (ce_stage(ce)) {
2143 /* -1 because for loop will increment by 1 */
2144 i += warn_conflicted_path(o->src_index, i, o) - 1;
2145 ret = UPDATE_SPARSITY_WARNINGS;
2146 continue;
2149 if (apply_sparse_checkout(o->src_index, ce, o))
2150 ret = UPDATE_SPARSITY_WARNINGS;
2153 if (check_updates(o, o->src_index))
2154 ret = UPDATE_SPARSITY_WORKTREE_UPDATE_FAILURES;
2156 display_warning_msgs(o);
2157 o->internal.show_all_errors = old_show_all_errors;
2158 if (free_pattern_list) {
2159 clear_pattern_list(pl);
2160 free(pl);
2161 o->internal.pl = NULL;
2163 trace_performance_leave("update_sparsity");
2164 return ret;
2167 /* Here come the merge functions */
2169 static int reject_merge(const struct cache_entry *ce,
2170 struct unpack_trees_options *o)
2172 return add_rejected_path(o, ERROR_WOULD_OVERWRITE, ce->name);
2175 static int same(const struct cache_entry *a, const struct cache_entry *b)
2177 if (!!a != !!b)
2178 return 0;
2179 if (!a && !b)
2180 return 1;
2181 if ((a->ce_flags | b->ce_flags) & CE_CONFLICTED)
2182 return 0;
2183 return a->ce_mode == b->ce_mode &&
2184 oideq(&a->oid, &b->oid);
2189 * When a CE gets turned into an unmerged entry, we
2190 * want it to be up-to-date
2192 static int verify_uptodate_1(const struct cache_entry *ce,
2193 struct unpack_trees_options *o,
2194 enum unpack_trees_error_types error_type)
2196 struct stat st;
2198 if (o->index_only)
2199 return 0;
2202 * CE_VALID and CE_SKIP_WORKTREE cheat, we better check again
2203 * if this entry is truly up-to-date because this file may be
2204 * overwritten.
2206 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2207 ; /* keep checking */
2208 else if (o->reset || ce_uptodate(ce))
2209 return 0;
2211 if (!lstat(ce->name, &st)) {
2212 int flags = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE;
2213 unsigned changed = ie_match_stat(o->src_index, ce, &st, flags);
2215 if (submodule_from_ce(ce)) {
2216 int r = check_submodule_move_head(ce,
2217 "HEAD", oid_to_hex(&ce->oid), o);
2218 if (r)
2219 return add_rejected_path(o, error_type, ce->name);
2220 return 0;
2223 if (!changed)
2224 return 0;
2226 * Historic default policy was to allow submodule to be out
2227 * of sync wrt the superproject index. If the submodule was
2228 * not considered interesting above, we don't care here.
2230 if (S_ISGITLINK(ce->ce_mode))
2231 return 0;
2233 errno = 0;
2235 if (errno == ENOENT)
2236 return 0;
2237 return add_rejected_path(o, error_type, ce->name);
2240 int verify_uptodate(const struct cache_entry *ce,
2241 struct unpack_trees_options *o)
2243 if (!o->skip_sparse_checkout &&
2244 (ce->ce_flags & CE_SKIP_WORKTREE) &&
2245 (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2246 return 0;
2247 return verify_uptodate_1(ce, o, ERROR_NOT_UPTODATE_FILE);
2250 static int verify_uptodate_sparse(const struct cache_entry *ce,
2251 struct unpack_trees_options *o)
2253 return verify_uptodate_1(ce, o, WARNING_SPARSE_NOT_UPTODATE_FILE);
2257 * TODO: We should actually invalidate o->internal.result, not src_index [1].
2258 * But since cache tree and untracked cache both are not copied to
2259 * o->internal.result until unpacking is complete, we invalidate them on
2260 * src_index instead with the assumption that they will be copied to
2261 * dst_index at the end.
2263 * [1] src_index->cache_tree is also used in unpack_callback() so if
2264 * we invalidate o->internal.result, we need to update it to use
2265 * o->internal.result.cache_tree as well.
2267 static void invalidate_ce_path(const struct cache_entry *ce,
2268 struct unpack_trees_options *o)
2270 if (!ce)
2271 return;
2272 cache_tree_invalidate_path(o->src_index, ce->name);
2273 untracked_cache_invalidate_path(o->src_index, ce->name, 1);
2277 * Check that checking out ce->sha1 in subdir ce->name is not
2278 * going to overwrite any working files.
2280 static int verify_clean_submodule(const char *old_sha1,
2281 const struct cache_entry *ce,
2282 struct unpack_trees_options *o)
2284 if (!submodule_from_ce(ce))
2285 return 0;
2287 return check_submodule_move_head(ce, old_sha1,
2288 oid_to_hex(&ce->oid), o);
2291 static int verify_clean_subdirectory(const struct cache_entry *ce,
2292 struct unpack_trees_options *o)
2295 * we are about to extract "ce->name"; we would not want to lose
2296 * anything in the existing directory there.
2298 int namelen;
2299 int i;
2300 struct dir_struct d;
2301 char *pathbuf;
2302 int cnt = 0;
2304 if (S_ISGITLINK(ce->ce_mode)) {
2305 struct object_id oid;
2306 int sub_head = resolve_gitlink_ref(ce->name, "HEAD", &oid);
2308 * If we are not going to update the submodule, then
2309 * we don't care.
2311 if (!sub_head && oideq(&oid, &ce->oid))
2312 return 0;
2313 return verify_clean_submodule(sub_head ? NULL : oid_to_hex(&oid),
2314 ce, o);
2318 * First let's make sure we do not have a local modification
2319 * in that directory.
2321 namelen = ce_namelen(ce);
2322 for (i = locate_in_src_index(ce, o);
2323 i < o->src_index->cache_nr;
2324 i++) {
2325 struct cache_entry *ce2 = o->src_index->cache[i];
2326 int len = ce_namelen(ce2);
2327 if (len < namelen ||
2328 strncmp(ce->name, ce2->name, namelen) ||
2329 ce2->name[namelen] != '/')
2330 break;
2332 * ce2->name is an entry in the subdirectory to be
2333 * removed.
2335 if (!ce_stage(ce2)) {
2336 if (verify_uptodate(ce2, o))
2337 return -1;
2338 add_entry(o, ce2, CE_REMOVE, 0);
2339 invalidate_ce_path(ce, o);
2340 mark_ce_used(ce2, o);
2342 cnt++;
2345 /* Do not lose a locally present file that is not ignored. */
2346 pathbuf = xstrfmt("%.*s/", namelen, ce->name);
2348 memset(&d, 0, sizeof(d));
2349 if (o->internal.dir)
2350 setup_standard_excludes(&d);
2351 i = read_directory(&d, o->src_index, pathbuf, namelen+1, NULL);
2352 dir_clear(&d);
2353 free(pathbuf);
2354 if (i)
2355 return add_rejected_path(o, ERROR_NOT_UPTODATE_DIR, ce->name);
2357 /* Do not lose startup_info->original_cwd */
2358 if (startup_info->original_cwd &&
2359 !strcmp(startup_info->original_cwd, ce->name))
2360 return add_rejected_path(o, ERROR_CWD_IN_THE_WAY, ce->name);
2362 return cnt;
2366 * This gets called when there was no index entry for the tree entry 'dst',
2367 * but we found a file in the working tree that 'lstat()' said was fine,
2368 * and we're on a case-insensitive filesystem.
2370 * See if we can find a case-insensitive match in the index that also
2371 * matches the stat information, and assume it's that other file!
2373 static int icase_exists(struct unpack_trees_options *o, const char *name, int len, struct stat *st)
2375 const struct cache_entry *src;
2377 src = index_file_exists(o->src_index, name, len, 1);
2378 return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
2381 enum absent_checking_type {
2382 COMPLETELY_ABSENT,
2383 ABSENT_ANY_DIRECTORY
2386 static int check_ok_to_remove(const char *name, int len, int dtype,
2387 const struct cache_entry *ce, struct stat *st,
2388 enum unpack_trees_error_types error_type,
2389 enum absent_checking_type absent_type,
2390 struct unpack_trees_options *o)
2392 const struct cache_entry *result;
2395 * It may be that the 'lstat()' succeeded even though
2396 * target 'ce' was absent, because there is an old
2397 * entry that is different only in case..
2399 * Ignore that lstat() if it matches.
2401 if (ignore_case && icase_exists(o, name, len, st))
2402 return 0;
2404 if (o->internal.dir &&
2405 is_excluded(o->internal.dir, o->src_index, name, &dtype))
2407 * ce->name is explicitly excluded, so it is Ok to
2408 * overwrite it.
2410 return 0;
2411 if (S_ISDIR(st->st_mode)) {
2413 * We are checking out path "foo" and
2414 * found "foo/." in the working tree.
2415 * This is tricky -- if we have modified
2416 * files that are in "foo/" we would lose
2417 * them.
2419 if (verify_clean_subdirectory(ce, o) < 0)
2420 return -1;
2421 return 0;
2424 /* If we only care about directories, then we can remove */
2425 if (absent_type == ABSENT_ANY_DIRECTORY)
2426 return 0;
2429 * The previous round may already have decided to
2430 * delete this path, which is in a subdirectory that
2431 * is being replaced with a blob.
2433 result = index_file_exists(&o->internal.result, name, len, 0);
2434 if (result) {
2435 if (result->ce_flags & CE_REMOVE)
2436 return 0;
2439 return add_rejected_path(o, error_type, name);
2443 * We do not want to remove or overwrite a working tree file that
2444 * is not tracked, unless it is ignored.
2446 static int verify_absent_1(const struct cache_entry *ce,
2447 enum unpack_trees_error_types error_type,
2448 enum absent_checking_type absent_type,
2449 struct unpack_trees_options *o)
2451 int len;
2452 struct stat st;
2454 if (o->index_only || !o->update)
2455 return 0;
2457 if (o->reset == UNPACK_RESET_OVERWRITE_UNTRACKED) {
2458 /* Avoid nuking startup_info->original_cwd... */
2459 if (startup_info->original_cwd &&
2460 !strcmp(startup_info->original_cwd, ce->name))
2461 return add_rejected_path(o, ERROR_CWD_IN_THE_WAY,
2462 ce->name);
2463 /* ...but nuke anything else. */
2464 return 0;
2467 len = check_leading_path(ce->name, ce_namelen(ce), 0);
2468 if (!len)
2469 return 0;
2470 else if (len > 0) {
2471 char *path;
2472 int ret;
2474 path = xmemdupz(ce->name, len);
2475 if (lstat(path, &st))
2476 ret = error_errno("cannot stat '%s'", path);
2477 else {
2478 if (submodule_from_ce(ce))
2479 ret = check_submodule_move_head(ce,
2480 oid_to_hex(&ce->oid),
2481 NULL, o);
2482 else
2483 ret = check_ok_to_remove(path, len, DT_UNKNOWN, NULL,
2484 &st, error_type,
2485 absent_type, o);
2487 free(path);
2488 return ret;
2489 } else if (lstat(ce->name, &st)) {
2490 if (errno != ENOENT)
2491 return error_errno("cannot stat '%s'", ce->name);
2492 return 0;
2493 } else {
2494 if (submodule_from_ce(ce))
2495 return check_submodule_move_head(ce, oid_to_hex(&ce->oid),
2496 NULL, o);
2498 return check_ok_to_remove(ce->name, ce_namelen(ce),
2499 ce_to_dtype(ce), ce, &st,
2500 error_type, absent_type, o);
2504 static int verify_absent(const struct cache_entry *ce,
2505 enum unpack_trees_error_types error_type,
2506 struct unpack_trees_options *o)
2508 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2509 return 0;
2510 return verify_absent_1(ce, error_type, COMPLETELY_ABSENT, o);
2513 static int verify_absent_if_directory(const struct cache_entry *ce,
2514 enum unpack_trees_error_types error_type,
2515 struct unpack_trees_options *o)
2517 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2518 return 0;
2519 return verify_absent_1(ce, error_type, ABSENT_ANY_DIRECTORY, o);
2522 static int verify_absent_sparse(const struct cache_entry *ce,
2523 enum unpack_trees_error_types error_type,
2524 struct unpack_trees_options *o)
2526 return verify_absent_1(ce, error_type, COMPLETELY_ABSENT, o);
2529 static int merged_entry(const struct cache_entry *ce,
2530 const struct cache_entry *old,
2531 struct unpack_trees_options *o)
2533 int update = CE_UPDATE;
2534 struct cache_entry *merge = dup_cache_entry(ce, &o->internal.result);
2536 if (!old) {
2538 * New index entries. In sparse checkout, the following
2539 * verify_absent() will be delayed until after
2540 * traverse_trees() finishes in unpack_trees(), then:
2542 * - CE_NEW_SKIP_WORKTREE will be computed correctly
2543 * - verify_absent() be called again, this time with
2544 * correct CE_NEW_SKIP_WORKTREE
2546 * verify_absent() call here does nothing in sparse
2547 * checkout (i.e. o->skip_sparse_checkout == 0)
2549 update |= CE_ADDED;
2550 merge->ce_flags |= CE_NEW_SKIP_WORKTREE;
2552 if (verify_absent(merge,
2553 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
2554 discard_cache_entry(merge);
2555 return -1;
2557 invalidate_ce_path(merge, o);
2559 if (submodule_from_ce(ce) && file_exists(ce->name)) {
2560 int ret = check_submodule_move_head(ce, NULL,
2561 oid_to_hex(&ce->oid),
2563 if (ret)
2564 return ret;
2567 } else if (!(old->ce_flags & CE_CONFLICTED)) {
2569 * See if we can re-use the old CE directly?
2570 * That way we get the uptodate stat info.
2572 * This also removes the UPDATE flag on a match; otherwise
2573 * we will end up overwriting local changes in the work tree.
2575 if (same(old, merge)) {
2576 copy_cache_entry(merge, old);
2577 update = 0;
2578 } else {
2579 if (verify_uptodate(old, o)) {
2580 discard_cache_entry(merge);
2581 return -1;
2583 /* Migrate old flags over */
2584 update |= old->ce_flags & (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
2585 invalidate_ce_path(old, o);
2588 if (submodule_from_ce(ce) && file_exists(ce->name)) {
2589 int ret = check_submodule_move_head(ce, oid_to_hex(&old->oid),
2590 oid_to_hex(&ce->oid),
2592 if (ret)
2593 return ret;
2595 } else {
2597 * Previously unmerged entry left as an existence
2598 * marker by read_index_unmerged();
2600 if (verify_absent_if_directory(merge,
2601 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
2602 discard_cache_entry(merge);
2603 return -1;
2606 invalidate_ce_path(old, o);
2609 if (do_add_entry(o, merge, update, CE_STAGEMASK) < 0)
2610 return -1;
2611 return 1;
2614 static int merged_sparse_dir(const struct cache_entry * const *src, int n,
2615 struct unpack_trees_options *o)
2617 struct tree_desc t[MAX_UNPACK_TREES + 1];
2618 void * tree_bufs[MAX_UNPACK_TREES + 1];
2619 struct traverse_info info;
2620 int i, ret;
2623 * Create the tree traversal information for traversing into *only* the
2624 * sparse directory.
2626 setup_traverse_info(&info, src[0]->name);
2627 info.fn = unpack_sparse_callback;
2628 info.data = o;
2629 info.show_all_errors = o->internal.show_all_errors;
2630 info.pathspec = o->pathspec;
2632 /* Get the tree descriptors of the sparse directory in each of the merging trees */
2633 for (i = 0; i < n; i++)
2634 tree_bufs[i] = fill_tree_descriptor(o->src_index->repo, &t[i],
2635 src[i] && !is_null_oid(&src[i]->oid) ? &src[i]->oid : NULL);
2637 ret = traverse_trees(o->src_index, n, t, &info);
2639 for (i = 0; i < n; i++)
2640 free(tree_bufs[i]);
2642 return ret;
2645 static int deleted_entry(const struct cache_entry *ce,
2646 const struct cache_entry *old,
2647 struct unpack_trees_options *o)
2649 /* Did it exist in the index? */
2650 if (!old) {
2651 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2652 return -1;
2653 return 0;
2654 } else if (verify_absent_if_directory(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o)) {
2655 return -1;
2658 if (!(old->ce_flags & CE_CONFLICTED) && verify_uptodate(old, o))
2659 return -1;
2660 add_entry(o, ce, CE_REMOVE, 0);
2661 invalidate_ce_path(ce, o);
2662 return 1;
2665 static int keep_entry(const struct cache_entry *ce,
2666 struct unpack_trees_options *o)
2668 add_entry(o, ce, 0, 0);
2669 if (ce_stage(ce))
2670 invalidate_ce_path(ce, o);
2671 return 1;
2674 #if DBRT_DEBUG
2675 static void show_stage_entry(FILE *o,
2676 const char *label, const struct cache_entry *ce)
2678 if (!ce)
2679 fprintf(o, "%s (missing)\n", label);
2680 else
2681 fprintf(o, "%s%06o %s %d\t%s\n",
2682 label,
2683 ce->ce_mode,
2684 oid_to_hex(&ce->oid),
2685 ce_stage(ce),
2686 ce->name);
2688 #endif
2690 int threeway_merge(const struct cache_entry * const *stages,
2691 struct unpack_trees_options *o)
2693 const struct cache_entry *index;
2694 const struct cache_entry *head;
2695 const struct cache_entry *remote = stages[o->head_idx + 1];
2696 int count;
2697 int head_match = 0;
2698 int remote_match = 0;
2700 int df_conflict_head = 0;
2701 int df_conflict_remote = 0;
2703 int any_anc_missing = 0;
2704 int no_anc_exists = 1;
2705 int i;
2707 for (i = 1; i < o->head_idx; i++) {
2708 if (!stages[i] || stages[i] == o->df_conflict_entry)
2709 any_anc_missing = 1;
2710 else
2711 no_anc_exists = 0;
2714 index = stages[0];
2715 head = stages[o->head_idx];
2717 if (head == o->df_conflict_entry) {
2718 df_conflict_head = 1;
2719 head = NULL;
2722 if (remote == o->df_conflict_entry) {
2723 df_conflict_remote = 1;
2724 remote = NULL;
2728 * First, if there's a #16 situation, note that to prevent #13
2729 * and #14.
2731 if (!same(remote, head)) {
2732 for (i = 1; i < o->head_idx; i++) {
2733 if (same(stages[i], head)) {
2734 head_match = i;
2736 if (same(stages[i], remote)) {
2737 remote_match = i;
2743 * We start with cases where the index is allowed to match
2744 * something other than the head: #14(ALT) and #2ALT, where it
2745 * is permitted to match the result instead.
2747 /* #14, #14ALT, #2ALT */
2748 if (remote && !df_conflict_head && head_match && !remote_match) {
2749 if (index && !same(index, remote) && !same(index, head)) {
2750 if (S_ISSPARSEDIR(index->ce_mode))
2751 return merged_sparse_dir(stages, 4, o);
2752 else
2753 return reject_merge(index, o);
2755 return merged_entry(remote, index, o);
2758 * If we have an entry in the index cache, then we want to
2759 * make sure that it matches head.
2761 if (index && !same(index, head)) {
2762 if (S_ISSPARSEDIR(index->ce_mode))
2763 return merged_sparse_dir(stages, 4, o);
2764 else
2765 return reject_merge(index, o);
2768 if (head) {
2769 /* #5ALT, #15 */
2770 if (same(head, remote))
2771 return merged_entry(head, index, o);
2772 /* #13, #3ALT */
2773 if (!df_conflict_remote && remote_match && !head_match)
2774 return merged_entry(head, index, o);
2777 /* #1 */
2778 if (!head && !remote && any_anc_missing)
2779 return 0;
2782 * Under the "aggressive" rule, we resolve mostly trivial
2783 * cases that we historically had git-merge-one-file resolve.
2785 if (o->aggressive) {
2786 int head_deleted = !head;
2787 int remote_deleted = !remote;
2788 const struct cache_entry *ce = NULL;
2790 if (index)
2791 ce = index;
2792 else if (head)
2793 ce = head;
2794 else if (remote)
2795 ce = remote;
2796 else {
2797 for (i = 1; i < o->head_idx; i++) {
2798 if (stages[i] && stages[i] != o->df_conflict_entry) {
2799 ce = stages[i];
2800 break;
2806 * Deleted in both.
2807 * Deleted in one and unchanged in the other.
2809 if ((head_deleted && remote_deleted) ||
2810 (head_deleted && remote && remote_match) ||
2811 (remote_deleted && head && head_match)) {
2812 if (index)
2813 return deleted_entry(index, index, o);
2814 if (ce && !head_deleted) {
2815 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2816 return -1;
2818 return 0;
2821 * Added in both, identically.
2823 if (no_anc_exists && head && remote && same(head, remote))
2824 return merged_entry(head, index, o);
2828 /* Handle "no merge" cases (see t/t1000-read-tree-m-3way.sh) */
2829 if (index) {
2831 * If we've reached the "no merge" cases and we're merging
2832 * a sparse directory, we may have an "edit/edit" conflict that
2833 * can be resolved by individually merging directory contents.
2835 if (S_ISSPARSEDIR(index->ce_mode))
2836 return merged_sparse_dir(stages, 4, o);
2839 * If we're not merging a sparse directory, ensure the index is
2840 * up-to-date to avoid files getting overwritten with conflict
2841 * resolution files
2843 if (verify_uptodate(index, o))
2844 return -1;
2847 o->internal.nontrivial_merge = 1;
2849 /* #2, #3, #4, #6, #7, #9, #10, #11. */
2850 count = 0;
2851 if (!head_match || !remote_match) {
2852 for (i = 1; i < o->head_idx; i++) {
2853 if (stages[i] && stages[i] != o->df_conflict_entry) {
2854 keep_entry(stages[i], o);
2855 count++;
2856 break;
2860 #if DBRT_DEBUG
2861 else {
2862 fprintf(stderr, "read-tree: warning #16 detected\n");
2863 show_stage_entry(stderr, "head ", stages[head_match]);
2864 show_stage_entry(stderr, "remote ", stages[remote_match]);
2866 #endif
2867 if (head) { count += keep_entry(head, o); }
2868 if (remote) { count += keep_entry(remote, o); }
2869 return count;
2873 * Two-way merge.
2875 * The rule is to "carry forward" what is in the index without losing
2876 * information across a "fast-forward", favoring a successful merge
2877 * over a merge failure when it makes sense. For details of the
2878 * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
2881 int twoway_merge(const struct cache_entry * const *src,
2882 struct unpack_trees_options *o)
2884 const struct cache_entry *current = src[0];
2885 const struct cache_entry *oldtree = src[1];
2886 const struct cache_entry *newtree = src[2];
2888 if (o->internal.merge_size != 2)
2889 return error("Cannot do a twoway merge of %d trees",
2890 o->internal.merge_size);
2892 if (oldtree == o->df_conflict_entry)
2893 oldtree = NULL;
2894 if (newtree == o->df_conflict_entry)
2895 newtree = NULL;
2897 if (current) {
2898 if (current->ce_flags & CE_CONFLICTED) {
2899 if (same(oldtree, newtree) || o->reset) {
2900 if (!newtree)
2901 return deleted_entry(current, current, o);
2902 else
2903 return merged_entry(newtree, current, o);
2905 return reject_merge(current, o);
2906 } else if ((!oldtree && !newtree) || /* 4 and 5 */
2907 (!oldtree && newtree &&
2908 same(current, newtree)) || /* 6 and 7 */
2909 (oldtree && newtree &&
2910 same(oldtree, newtree)) || /* 14 and 15 */
2911 (oldtree && newtree &&
2912 !same(oldtree, newtree) && /* 18 and 19 */
2913 same(current, newtree))) {
2914 return keep_entry(current, o);
2915 } else if (oldtree && !newtree && same(current, oldtree)) {
2916 /* 10 or 11 */
2917 return deleted_entry(oldtree, current, o);
2918 } else if (oldtree && newtree &&
2919 same(current, oldtree) && !same(current, newtree)) {
2920 /* 20 or 21 */
2921 return merged_entry(newtree, current, o);
2922 } else if (current && !oldtree && newtree &&
2923 S_ISSPARSEDIR(current->ce_mode) != S_ISSPARSEDIR(newtree->ce_mode) &&
2924 ce_stage(current) == 0) {
2926 * This case is a directory/file conflict across the sparse-index
2927 * boundary. When we are changing from one path to another via
2928 * 'git checkout', then we want to replace one entry with another
2929 * via merged_entry(). If there are staged changes, then we should
2930 * reject the merge instead.
2932 return merged_entry(newtree, current, o);
2933 } else if (S_ISSPARSEDIR(current->ce_mode)) {
2935 * The sparse directories differ, but we don't know whether that's
2936 * because of two different files in the directory being modified
2937 * (can be trivially merged) or if there is a real file conflict.
2938 * Merge the sparse directory by OID to compare file-by-file.
2940 return merged_sparse_dir(src, 3, o);
2941 } else
2942 return reject_merge(current, o);
2944 else if (newtree) {
2945 if (oldtree && !o->initial_checkout) {
2947 * deletion of the path was staged;
2949 if (same(oldtree, newtree))
2950 return 1;
2951 return reject_merge(oldtree, o);
2953 return merged_entry(newtree, current, o);
2955 return deleted_entry(oldtree, current, o);
2959 * Bind merge.
2961 * Keep the index entries at stage0, collapse stage1 but make sure
2962 * stage0 does not have anything there.
2964 int bind_merge(const struct cache_entry * const *src,
2965 struct unpack_trees_options *o)
2967 const struct cache_entry *old = src[0];
2968 const struct cache_entry *a = src[1];
2970 if (o->internal.merge_size != 1)
2971 return error("Cannot do a bind merge of %d trees",
2972 o->internal.merge_size);
2973 if (a && old)
2974 return o->quiet ? -1 :
2975 error(ERRORMSG(o, ERROR_BIND_OVERLAP),
2976 super_prefixed(a->name, o->super_prefix),
2977 super_prefixed(old->name, o->super_prefix));
2978 if (!a)
2979 return keep_entry(old, o);
2980 else
2981 return merged_entry(a, NULL, o);
2985 * One-way merge.
2987 * The rule is:
2988 * - take the stat information from stage0, take the data from stage1
2990 int oneway_merge(const struct cache_entry * const *src,
2991 struct unpack_trees_options *o)
2993 const struct cache_entry *old = src[0];
2994 const struct cache_entry *a = src[1];
2996 if (o->internal.merge_size != 1)
2997 return error("Cannot do a oneway merge of %d trees",
2998 o->internal.merge_size);
3000 if (!a || a == o->df_conflict_entry)
3001 return deleted_entry(old, old, o);
3003 if (old && same(old, a)) {
3004 int update = 0;
3005 if (o->reset && o->update && !ce_uptodate(old) && !ce_skip_worktree(old) &&
3006 !(old->ce_flags & CE_FSMONITOR_VALID)) {
3007 struct stat st;
3008 if (lstat(old->name, &st) ||
3009 ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE))
3010 update |= CE_UPDATE;
3012 if (o->update && S_ISGITLINK(old->ce_mode) &&
3013 should_update_submodules() && !verify_uptodate(old, o))
3014 update |= CE_UPDATE;
3015 add_entry(o, old, update, CE_STAGEMASK);
3016 return 0;
3018 return merged_entry(a, old, o);
3022 * Merge worktree and untracked entries in a stash entry.
3024 * Ignore all index entries. Collapse remaining trees but make sure that they
3025 * don't have any conflicting files.
3027 int stash_worktree_untracked_merge(const struct cache_entry * const *src,
3028 struct unpack_trees_options *o)
3030 const struct cache_entry *worktree = src[1];
3031 const struct cache_entry *untracked = src[2];
3033 if (o->internal.merge_size != 2)
3034 BUG("invalid merge_size: %d", o->internal.merge_size);
3036 if (worktree && untracked)
3037 return error(_("worktree and untracked commit have duplicate entries: %s"),
3038 super_prefixed(worktree->name, o->super_prefix));
3040 return merged_entry(worktree ? worktree : untracked, NULL, o);