cocci: remove 'unused.cocci'
[git.git] / unpack-trees.c
blob3ded68ecb6df517e6eb03ba1e00641a4894d4420
1 #include "cache.h"
2 #include "strvec.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "dir.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "hex.h"
9 #include "tree.h"
10 #include "tree-walk.h"
11 #include "cache-tree.h"
12 #include "unpack-trees.h"
13 #include "progress.h"
14 #include "refs.h"
15 #include "attr.h"
16 #include "split-index.h"
17 #include "sparse-index.h"
18 #include "submodule.h"
19 #include "submodule-config.h"
20 #include "fsmonitor.h"
21 #include "object-store.h"
22 #include "promisor-remote.h"
23 #include "entry.h"
24 #include "parallel-checkout.h"
25 #include "setup.h"
28 * Error messages expected by scripts out of plumbing commands such as
29 * read-tree. Non-scripted Porcelain is not required to use these messages
30 * and in fact are encouraged to reword them to better suit their particular
31 * situation better. See how "git checkout" and "git merge" replaces
32 * them using setup_unpack_trees_porcelain(), for example.
34 static const char *unpack_plumbing_errors[NB_UNPACK_TREES_WARNING_TYPES] = {
35 /* ERROR_WOULD_OVERWRITE */
36 "Entry '%s' would be overwritten by merge. Cannot merge.",
38 /* ERROR_NOT_UPTODATE_FILE */
39 "Entry '%s' not uptodate. Cannot merge.",
41 /* ERROR_NOT_UPTODATE_DIR */
42 "Updating '%s' would lose untracked files in it",
44 /* ERROR_CWD_IN_THE_WAY */
45 "Refusing to remove '%s' since it is the current working directory.",
47 /* ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN */
48 "Untracked working tree file '%s' would be overwritten by merge.",
50 /* ERROR_WOULD_LOSE_UNTRACKED_REMOVED */
51 "Untracked working tree file '%s' would be removed by merge.",
53 /* ERROR_BIND_OVERLAP */
54 "Entry '%s' overlaps with '%s'. Cannot bind.",
56 /* ERROR_WOULD_LOSE_SUBMODULE */
57 "Submodule '%s' cannot checkout new HEAD.",
59 /* NB_UNPACK_TREES_ERROR_TYPES; just a meta value */
60 "",
62 /* WARNING_SPARSE_NOT_UPTODATE_FILE */
63 "Path '%s' not uptodate; will not remove from working tree.",
65 /* WARNING_SPARSE_UNMERGED_FILE */
66 "Path '%s' unmerged; will not remove from working tree.",
68 /* WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN */
69 "Path '%s' already present; will not overwrite with sparse update.",
72 #define ERRORMSG(o,type) \
73 ( ((o) && (o)->internal.msgs[(type)]) \
74 ? ((o)->internal.msgs[(type)]) \
75 : (unpack_plumbing_errors[(type)]) )
77 static const char *super_prefixed(const char *path, const char *super_prefix)
80 * It is necessary and sufficient to have two static buffers
81 * here, as the return value of this function is fed to
82 * error() using the unpack_*_errors[] templates we see above.
84 static struct strbuf buf[2] = {STRBUF_INIT, STRBUF_INIT};
85 static int super_prefix_len = -1;
86 static unsigned idx = ARRAY_SIZE(buf) - 1;
88 if (super_prefix_len < 0) {
89 if (!super_prefix) {
90 super_prefix_len = 0;
91 } else {
92 int i;
93 for (i = 0; i < ARRAY_SIZE(buf); i++)
94 strbuf_addstr(&buf[i], super_prefix);
95 super_prefix_len = buf[0].len;
99 if (!super_prefix_len)
100 return path;
102 if (++idx >= ARRAY_SIZE(buf))
103 idx = 0;
105 strbuf_setlen(&buf[idx], super_prefix_len);
106 strbuf_addstr(&buf[idx], path);
108 return buf[idx].buf;
111 void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,
112 const char *cmd)
114 int i;
115 const char **msgs = opts->internal.msgs;
116 const char *msg;
118 strvec_init(&opts->internal.msgs_to_free);
120 if (!strcmp(cmd, "checkout"))
121 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
122 ? _("Your local changes to the following files would be overwritten by checkout:\n%%s"
123 "Please commit your changes or stash them before you switch branches.")
124 : _("Your local changes to the following files would be overwritten by checkout:\n%%s");
125 else if (!strcmp(cmd, "merge"))
126 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
127 ? _("Your local changes to the following files would be overwritten by merge:\n%%s"
128 "Please commit your changes or stash them before you merge.")
129 : _("Your local changes to the following files would be overwritten by merge:\n%%s");
130 else
131 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
132 ? _("Your local changes to the following files would be overwritten by %s:\n%%s"
133 "Please commit your changes or stash them before you %s.")
134 : _("Your local changes to the following files would be overwritten by %s:\n%%s");
135 msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOT_UPTODATE_FILE] =
136 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
138 msgs[ERROR_NOT_UPTODATE_DIR] =
139 _("Updating the following directories would lose untracked files in them:\n%s");
141 msgs[ERROR_CWD_IN_THE_WAY] =
142 _("Refusing to remove the current working directory:\n%s");
144 if (!strcmp(cmd, "checkout"))
145 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
146 ? _("The following untracked working tree files would be removed by checkout:\n%%s"
147 "Please move or remove them before you switch branches.")
148 : _("The following untracked working tree files would be removed by checkout:\n%%s");
149 else if (!strcmp(cmd, "merge"))
150 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
151 ? _("The following untracked working tree files would be removed by merge:\n%%s"
152 "Please move or remove them before you merge.")
153 : _("The following untracked working tree files would be removed by merge:\n%%s");
154 else
155 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
156 ? _("The following untracked working tree files would be removed by %s:\n%%s"
157 "Please move or remove them before you %s.")
158 : _("The following untracked working tree files would be removed by %s:\n%%s");
159 msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED] =
160 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
162 if (!strcmp(cmd, "checkout"))
163 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
164 ? _("The following untracked working tree files would be overwritten by checkout:\n%%s"
165 "Please move or remove them before you switch branches.")
166 : _("The following untracked working tree files would be overwritten by checkout:\n%%s");
167 else if (!strcmp(cmd, "merge"))
168 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
169 ? _("The following untracked working tree files would be overwritten by merge:\n%%s"
170 "Please move or remove them before you merge.")
171 : _("The following untracked working tree files would be overwritten by merge:\n%%s");
172 else
173 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
174 ? _("The following untracked working tree files would be overwritten by %s:\n%%s"
175 "Please move or remove them before you %s.")
176 : _("The following untracked working tree files would be overwritten by %s:\n%%s");
177 msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN] =
178 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
181 * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
182 * cannot easily display it as a list.
184 msgs[ERROR_BIND_OVERLAP] = _("Entry '%s' overlaps with '%s'. Cannot bind.");
186 msgs[ERROR_WOULD_LOSE_SUBMODULE] =
187 _("Cannot update submodule:\n%s");
189 msgs[WARNING_SPARSE_NOT_UPTODATE_FILE] =
190 _("The following paths are not up to date and were left despite sparse patterns:\n%s");
191 msgs[WARNING_SPARSE_UNMERGED_FILE] =
192 _("The following paths are unmerged and were left despite sparse patterns:\n%s");
193 msgs[WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN] =
194 _("The following paths were already present and thus not updated despite sparse patterns:\n%s");
196 opts->internal.show_all_errors = 1;
197 /* rejected paths may not have a static buffer */
198 for (i = 0; i < ARRAY_SIZE(opts->internal.unpack_rejects); i++)
199 opts->internal.unpack_rejects[i].strdup_strings = 1;
202 void clear_unpack_trees_porcelain(struct unpack_trees_options *opts)
204 strvec_clear(&opts->internal.msgs_to_free);
205 memset(opts->internal.msgs, 0, sizeof(opts->internal.msgs));
208 static int do_add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
209 unsigned int set, unsigned int clear)
211 clear |= CE_HASHED;
213 if (set & CE_REMOVE)
214 set |= CE_WT_REMOVE;
216 ce->ce_flags = (ce->ce_flags & ~clear) | set;
217 return add_index_entry(&o->internal.result, ce,
218 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
221 static void add_entry(struct unpack_trees_options *o,
222 const struct cache_entry *ce,
223 unsigned int set, unsigned int clear)
225 do_add_entry(o, dup_cache_entry(ce, &o->internal.result), set, clear);
229 * add error messages on path <path>
230 * corresponding to the type <e> with the message <msg>
231 * indicating if it should be display in porcelain or not
233 static int add_rejected_path(struct unpack_trees_options *o,
234 enum unpack_trees_error_types e,
235 const char *path)
237 if (o->quiet)
238 return -1;
240 if (!o->internal.show_all_errors)
241 return error(ERRORMSG(o, e), super_prefixed(path,
242 o->super_prefix));
245 * Otherwise, insert in a list for future display by
246 * display_(error|warning)_msgs()
248 string_list_append(&o->internal.unpack_rejects[e], path);
249 return -1;
253 * display all the error messages stored in a nice way
255 static void display_error_msgs(struct unpack_trees_options *o)
257 int e;
258 unsigned error_displayed = 0;
259 for (e = 0; e < NB_UNPACK_TREES_ERROR_TYPES; e++) {
260 struct string_list *rejects = &o->internal.unpack_rejects[e];
262 if (rejects->nr > 0) {
263 int i;
264 struct strbuf path = STRBUF_INIT;
266 error_displayed = 1;
267 for (i = 0; i < rejects->nr; i++)
268 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
269 error(ERRORMSG(o, e), super_prefixed(path.buf,
270 o->super_prefix));
271 strbuf_release(&path);
273 string_list_clear(rejects, 0);
275 if (error_displayed)
276 fprintf(stderr, _("Aborting\n"));
280 * display all the warning messages stored in a nice way
282 static void display_warning_msgs(struct unpack_trees_options *o)
284 int e;
285 unsigned warning_displayed = 0;
286 for (e = NB_UNPACK_TREES_ERROR_TYPES + 1;
287 e < NB_UNPACK_TREES_WARNING_TYPES; e++) {
288 struct string_list *rejects = &o->internal.unpack_rejects[e];
290 if (rejects->nr > 0) {
291 int i;
292 struct strbuf path = STRBUF_INIT;
294 warning_displayed = 1;
295 for (i = 0; i < rejects->nr; i++)
296 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
297 warning(ERRORMSG(o, e), super_prefixed(path.buf,
298 o->super_prefix));
299 strbuf_release(&path);
301 string_list_clear(rejects, 0);
303 if (warning_displayed)
304 fprintf(stderr, _("After fixing the above paths, you may want to run `git sparse-checkout reapply`.\n"));
306 static int check_submodule_move_head(const struct cache_entry *ce,
307 const char *old_id,
308 const char *new_id,
309 struct unpack_trees_options *o)
311 unsigned flags = SUBMODULE_MOVE_HEAD_DRY_RUN;
312 const struct submodule *sub = submodule_from_ce(ce);
314 if (!sub)
315 return 0;
317 if (o->reset)
318 flags |= SUBMODULE_MOVE_HEAD_FORCE;
320 if (submodule_move_head(ce->name, o->super_prefix, old_id, new_id,
321 flags))
322 return add_rejected_path(o, ERROR_WOULD_LOSE_SUBMODULE, ce->name);
323 return 0;
327 * Perform the loading of the repository's gitmodules file. This function is
328 * used by 'check_update()' to perform loading of the gitmodules file in two
329 * different situations:
330 * (1) before removing entries from the working tree if the gitmodules file has
331 * been marked for removal. This situation is specified by 'state' == NULL.
332 * (2) before checking out entries to the working tree if the gitmodules file
333 * has been marked for update. This situation is specified by 'state' != NULL.
335 static void load_gitmodules_file(struct index_state *index,
336 struct checkout *state)
338 int pos = index_name_pos(index, GITMODULES_FILE, strlen(GITMODULES_FILE));
340 if (pos >= 0) {
341 struct cache_entry *ce = index->cache[pos];
342 if (!state && ce->ce_flags & CE_WT_REMOVE) {
343 repo_read_gitmodules(the_repository, 0);
344 } else if (state && (ce->ce_flags & CE_UPDATE)) {
345 submodule_free(the_repository);
346 checkout_entry(ce, state, NULL, NULL);
347 repo_read_gitmodules(the_repository, 0);
352 static struct progress *get_progress(struct unpack_trees_options *o,
353 struct index_state *index)
355 unsigned cnt = 0, total = 0;
357 if (!o->update || !o->verbose_update)
358 return NULL;
360 for (; cnt < index->cache_nr; cnt++) {
361 const struct cache_entry *ce = index->cache[cnt];
362 if (ce->ce_flags & (CE_UPDATE | CE_WT_REMOVE))
363 total++;
366 return start_delayed_progress(_("Updating files"), total);
369 static void setup_collided_checkout_detection(struct checkout *state,
370 struct index_state *index)
372 int i;
374 state->clone = 1;
375 for (i = 0; i < index->cache_nr; i++)
376 index->cache[i]->ce_flags &= ~CE_MATCHED;
379 static void report_collided_checkout(struct index_state *index)
381 struct string_list list = STRING_LIST_INIT_NODUP;
382 int i;
384 for (i = 0; i < index->cache_nr; i++) {
385 struct cache_entry *ce = index->cache[i];
387 if (!(ce->ce_flags & CE_MATCHED))
388 continue;
390 string_list_append(&list, ce->name);
391 ce->ce_flags &= ~CE_MATCHED;
394 list.cmp = fspathcmp;
395 string_list_sort(&list);
397 if (list.nr) {
398 warning(_("the following paths have collided (e.g. case-sensitive paths\n"
399 "on a case-insensitive filesystem) and only one from the same\n"
400 "colliding group is in the working tree:\n"));
402 for (i = 0; i < list.nr; i++)
403 fprintf(stderr, " '%s'\n", list.items[i].string);
406 string_list_clear(&list, 0);
409 static int must_checkout(const struct cache_entry *ce)
411 return ce->ce_flags & CE_UPDATE;
414 static int check_updates(struct unpack_trees_options *o,
415 struct index_state *index)
417 unsigned cnt = 0;
418 int errs = 0;
419 struct progress *progress;
420 struct checkout state = CHECKOUT_INIT;
421 int i, pc_workers, pc_threshold;
423 trace_performance_enter();
424 state.super_prefix = o->super_prefix;
425 state.force = 1;
426 state.quiet = 1;
427 state.refresh_cache = 1;
428 state.istate = index;
429 clone_checkout_metadata(&state.meta, &o->meta, NULL);
431 if (!o->update || o->dry_run) {
432 remove_marked_cache_entries(index, 0);
433 trace_performance_leave("check_updates");
434 return 0;
437 if (o->clone)
438 setup_collided_checkout_detection(&state, index);
440 progress = get_progress(o, index);
442 /* Start with clean cache to avoid using any possibly outdated info. */
443 invalidate_lstat_cache();
445 git_attr_set_direction(GIT_ATTR_CHECKOUT);
447 if (should_update_submodules())
448 load_gitmodules_file(index, NULL);
450 for (i = 0; i < index->cache_nr; i++) {
451 const struct cache_entry *ce = index->cache[i];
453 if (ce->ce_flags & CE_WT_REMOVE) {
454 display_progress(progress, ++cnt);
455 unlink_entry(ce, o->super_prefix);
459 remove_marked_cache_entries(index, 0);
460 remove_scheduled_dirs();
462 if (should_update_submodules())
463 load_gitmodules_file(index, &state);
465 if (repo_has_promisor_remote(the_repository))
467 * Prefetch the objects that are to be checked out in the loop
468 * below.
470 prefetch_cache_entries(index, must_checkout);
472 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
474 enable_delayed_checkout(&state);
475 if (pc_workers > 1)
476 init_parallel_checkout();
477 for (i = 0; i < index->cache_nr; i++) {
478 struct cache_entry *ce = index->cache[i];
480 if (must_checkout(ce)) {
481 size_t last_pc_queue_size = pc_queue_size();
483 if (ce->ce_flags & CE_WT_REMOVE)
484 BUG("both update and delete flags are set on %s",
485 ce->name);
486 ce->ce_flags &= ~CE_UPDATE;
487 errs |= checkout_entry(ce, &state, NULL, NULL);
489 if (last_pc_queue_size == pc_queue_size())
490 display_progress(progress, ++cnt);
493 if (pc_workers > 1)
494 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
495 progress, &cnt);
496 stop_progress(&progress);
497 errs |= finish_delayed_checkout(&state, o->verbose_update);
498 git_attr_set_direction(GIT_ATTR_CHECKIN);
500 if (o->clone)
501 report_collided_checkout(index);
503 trace_performance_leave("check_updates");
504 return errs != 0;
507 static int verify_uptodate_sparse(const struct cache_entry *ce,
508 struct unpack_trees_options *o);
509 static int verify_absent_sparse(const struct cache_entry *ce,
510 enum unpack_trees_error_types,
511 struct unpack_trees_options *o);
513 static int apply_sparse_checkout(struct index_state *istate,
514 struct cache_entry *ce,
515 struct unpack_trees_options *o)
517 int was_skip_worktree = ce_skip_worktree(ce);
519 if (ce->ce_flags & CE_NEW_SKIP_WORKTREE)
520 ce->ce_flags |= CE_SKIP_WORKTREE;
521 else
522 ce->ce_flags &= ~CE_SKIP_WORKTREE;
523 if (was_skip_worktree != ce_skip_worktree(ce)) {
524 ce->ce_flags |= CE_UPDATE_IN_BASE;
525 mark_fsmonitor_invalid(istate, ce);
526 istate->cache_changed |= CE_ENTRY_CHANGED;
530 * if (!was_skip_worktree && !ce_skip_worktree()) {
531 * This is perfectly normal. Move on;
536 * Merge strategies may set CE_UPDATE|CE_REMOVE outside checkout
537 * area as a result of ce_skip_worktree() shortcuts in
538 * verify_absent() and verify_uptodate().
539 * Make sure they don't modify worktree if they are already
540 * outside checkout area
542 if (was_skip_worktree && ce_skip_worktree(ce)) {
543 ce->ce_flags &= ~CE_UPDATE;
546 * By default, when CE_REMOVE is on, CE_WT_REMOVE is also
547 * on to get that file removed from both index and worktree.
548 * If that file is already outside worktree area, don't
549 * bother remove it.
551 if (ce->ce_flags & CE_REMOVE)
552 ce->ce_flags &= ~CE_WT_REMOVE;
555 if (!was_skip_worktree && ce_skip_worktree(ce)) {
557 * If CE_UPDATE is set, verify_uptodate() must be called already
558 * also stat info may have lost after merged_entry() so calling
559 * verify_uptodate() again may fail
561 if (!(ce->ce_flags & CE_UPDATE) &&
562 verify_uptodate_sparse(ce, o)) {
563 ce->ce_flags &= ~CE_SKIP_WORKTREE;
564 return -1;
566 ce->ce_flags |= CE_WT_REMOVE;
567 ce->ce_flags &= ~CE_UPDATE;
569 if (was_skip_worktree && !ce_skip_worktree(ce)) {
570 if (verify_absent_sparse(ce, WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN, o))
571 return -1;
572 ce->ce_flags |= CE_UPDATE;
574 return 0;
577 static int warn_conflicted_path(struct index_state *istate,
578 int i,
579 struct unpack_trees_options *o)
581 char *conflicting_path = istate->cache[i]->name;
582 int count = 0;
584 add_rejected_path(o, WARNING_SPARSE_UNMERGED_FILE, conflicting_path);
586 /* Find out how many higher stage entries are at same path */
587 while ((++count) + i < istate->cache_nr &&
588 !strcmp(conflicting_path, istate->cache[count + i]->name))
589 ; /* do nothing */
591 return count;
594 static inline int call_unpack_fn(const struct cache_entry * const *src,
595 struct unpack_trees_options *o)
597 int ret = o->fn(src, o);
598 if (ret > 0)
599 ret = 0;
600 return ret;
603 static void mark_ce_used(struct cache_entry *ce, struct unpack_trees_options *o)
605 ce->ce_flags |= CE_UNPACKED;
607 if (o->internal.cache_bottom < o->src_index->cache_nr &&
608 o->src_index->cache[o->internal.cache_bottom] == ce) {
609 int bottom = o->internal.cache_bottom;
611 while (bottom < o->src_index->cache_nr &&
612 o->src_index->cache[bottom]->ce_flags & CE_UNPACKED)
613 bottom++;
614 o->internal.cache_bottom = bottom;
618 static void mark_all_ce_unused(struct index_state *index)
620 int i;
621 for (i = 0; i < index->cache_nr; i++)
622 index->cache[i]->ce_flags &= ~(CE_UNPACKED | CE_ADDED | CE_NEW_SKIP_WORKTREE);
625 static int locate_in_src_index(const struct cache_entry *ce,
626 struct unpack_trees_options *o)
628 struct index_state *index = o->src_index;
629 int len = ce_namelen(ce);
630 int pos = index_name_pos(index, ce->name, len);
631 if (pos < 0)
632 pos = -1 - pos;
633 return pos;
637 * We call unpack_index_entry() with an unmerged cache entry
638 * only in diff-index, and it wants a single callback. Skip
639 * the other unmerged entry with the same name.
641 static void mark_ce_used_same_name(struct cache_entry *ce,
642 struct unpack_trees_options *o)
644 struct index_state *index = o->src_index;
645 int len = ce_namelen(ce);
646 int pos;
648 for (pos = locate_in_src_index(ce, o); pos < index->cache_nr; pos++) {
649 struct cache_entry *next = index->cache[pos];
650 if (len != ce_namelen(next) ||
651 memcmp(ce->name, next->name, len))
652 break;
653 mark_ce_used(next, o);
657 static struct cache_entry *next_cache_entry(struct unpack_trees_options *o)
659 const struct index_state *index = o->src_index;
660 int pos = o->internal.cache_bottom;
662 while (pos < index->cache_nr) {
663 struct cache_entry *ce = index->cache[pos];
664 if (!(ce->ce_flags & CE_UNPACKED))
665 return ce;
666 pos++;
668 return NULL;
671 static void add_same_unmerged(const struct cache_entry *ce,
672 struct unpack_trees_options *o)
674 struct index_state *index = o->src_index;
675 int len = ce_namelen(ce);
676 int pos = index_name_pos(index, ce->name, len);
678 if (0 <= pos)
679 die("programming error in a caller of mark_ce_used_same_name");
680 for (pos = -pos - 1; pos < index->cache_nr; pos++) {
681 struct cache_entry *next = index->cache[pos];
682 if (len != ce_namelen(next) ||
683 memcmp(ce->name, next->name, len))
684 break;
685 add_entry(o, next, 0, 0);
686 mark_ce_used(next, o);
690 static int unpack_index_entry(struct cache_entry *ce,
691 struct unpack_trees_options *o)
693 const struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
694 int ret;
696 src[0] = ce;
698 mark_ce_used(ce, o);
699 if (ce_stage(ce)) {
700 if (o->skip_unmerged) {
701 add_entry(o, ce, 0, 0);
702 return 0;
705 ret = call_unpack_fn(src, o);
706 if (ce_stage(ce))
707 mark_ce_used_same_name(ce, o);
708 return ret;
711 static int find_cache_pos(struct traverse_info *, const char *p, size_t len);
713 static void restore_cache_bottom(struct traverse_info *info, int bottom)
715 struct unpack_trees_options *o = info->data;
717 if (o->diff_index_cached)
718 return;
719 o->internal.cache_bottom = bottom;
722 static int switch_cache_bottom(struct traverse_info *info)
724 struct unpack_trees_options *o = info->data;
725 int ret, pos;
727 if (o->diff_index_cached)
728 return 0;
729 ret = o->internal.cache_bottom;
730 pos = find_cache_pos(info->prev, info->name, info->namelen);
732 if (pos < -1)
733 o->internal.cache_bottom = -2 - pos;
734 else if (pos < 0)
735 o->internal.cache_bottom = o->src_index->cache_nr;
736 return ret;
739 static inline int are_same_oid(struct name_entry *name_j, struct name_entry *name_k)
741 return !is_null_oid(&name_j->oid) && !is_null_oid(&name_k->oid) && oideq(&name_j->oid, &name_k->oid);
744 static int all_trees_same_as_cache_tree(int n, unsigned long dirmask,
745 struct name_entry *names,
746 struct traverse_info *info)
748 struct unpack_trees_options *o = info->data;
749 int i;
751 if (!o->merge || dirmask != ((1 << n) - 1))
752 return 0;
754 for (i = 1; i < n; i++)
755 if (!are_same_oid(names, names + i))
756 return 0;
758 return cache_tree_matches_traversal(o->src_index->cache_tree, names, info);
761 static int index_pos_by_traverse_info(struct name_entry *names,
762 struct traverse_info *info)
764 struct unpack_trees_options *o = info->data;
765 struct strbuf name = STRBUF_INIT;
766 int pos;
768 strbuf_make_traverse_path(&name, info, names->path, names->pathlen);
769 strbuf_addch(&name, '/');
770 pos = index_name_pos(o->src_index, name.buf, name.len);
771 if (pos >= 0) {
772 if (!o->src_index->sparse_index ||
773 !(o->src_index->cache[pos]->ce_flags & CE_SKIP_WORKTREE))
774 BUG("This is a directory and should not exist in index");
775 } else {
776 pos = -pos - 1;
778 if (pos >= o->src_index->cache_nr ||
779 !starts_with(o->src_index->cache[pos]->name, name.buf) ||
780 (pos > 0 && starts_with(o->src_index->cache[pos-1]->name, name.buf)))
781 BUG("pos %d doesn't point to the first entry of %s in index",
782 pos, name.buf);
783 strbuf_release(&name);
784 return pos;
788 * Fast path if we detect that all trees are the same as cache-tree at this
789 * path. We'll walk these trees in an iterative loop using cache-tree/index
790 * instead of ODB since we already know what these trees contain.
792 static int traverse_by_cache_tree(int pos, int nr_entries, int nr_names,
793 struct traverse_info *info)
795 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
796 struct unpack_trees_options *o = info->data;
797 struct cache_entry *tree_ce = NULL;
798 int ce_len = 0;
799 int i, d;
801 if (!o->merge)
802 BUG("We need cache-tree to do this optimization");
805 * Do what unpack_callback() and unpack_single_entry() normally
806 * do. But we walk all paths in an iterative loop instead.
808 * D/F conflicts and higher stage entries are not a concern
809 * because cache-tree would be invalidated and we would never
810 * get here in the first place.
812 for (i = 0; i < nr_entries; i++) {
813 int new_ce_len, len, rc;
815 src[0] = o->src_index->cache[pos + i];
817 len = ce_namelen(src[0]);
818 new_ce_len = cache_entry_size(len);
820 if (new_ce_len > ce_len) {
821 new_ce_len <<= 1;
822 tree_ce = xrealloc(tree_ce, new_ce_len);
823 memset(tree_ce, 0, new_ce_len);
824 ce_len = new_ce_len;
826 tree_ce->ce_flags = create_ce_flags(0);
828 for (d = 1; d <= nr_names; d++)
829 src[d] = tree_ce;
832 tree_ce->ce_mode = src[0]->ce_mode;
833 tree_ce->ce_namelen = len;
834 oidcpy(&tree_ce->oid, &src[0]->oid);
835 memcpy(tree_ce->name, src[0]->name, len + 1);
837 rc = call_unpack_fn((const struct cache_entry * const *)src, o);
838 if (rc < 0) {
839 free(tree_ce);
840 return rc;
843 mark_ce_used(src[0], o);
845 free(tree_ce);
846 if (o->internal.debug_unpack)
847 printf("Unpacked %d entries from %s to %s using cache-tree\n",
848 nr_entries,
849 o->src_index->cache[pos]->name,
850 o->src_index->cache[pos + nr_entries - 1]->name);
851 return 0;
854 static int traverse_trees_recursive(int n, unsigned long dirmask,
855 unsigned long df_conflicts,
856 struct name_entry *names,
857 struct traverse_info *info)
859 struct unpack_trees_options *o = info->data;
860 int i, ret, bottom;
861 int nr_buf = 0;
862 struct tree_desc t[MAX_UNPACK_TREES];
863 void *buf[MAX_UNPACK_TREES];
864 struct traverse_info newinfo;
865 struct name_entry *p;
866 int nr_entries;
868 nr_entries = all_trees_same_as_cache_tree(n, dirmask, names, info);
869 if (nr_entries > 0) {
870 int pos = index_pos_by_traverse_info(names, info);
872 if (!o->merge || df_conflicts)
873 BUG("Wrong condition to get here buddy");
876 * All entries up to 'pos' must have been processed
877 * (i.e. marked CE_UNPACKED) at this point. But to be safe,
878 * save and restore cache_bottom anyway to not miss
879 * unprocessed entries before 'pos'.
881 bottom = o->internal.cache_bottom;
882 ret = traverse_by_cache_tree(pos, nr_entries, n, info);
883 o->internal.cache_bottom = bottom;
884 return ret;
887 p = names;
888 while (!p->mode)
889 p++;
891 newinfo = *info;
892 newinfo.prev = info;
893 newinfo.pathspec = info->pathspec;
894 newinfo.name = p->path;
895 newinfo.namelen = p->pathlen;
896 newinfo.mode = p->mode;
897 newinfo.pathlen = st_add3(newinfo.pathlen, tree_entry_len(p), 1);
898 newinfo.df_conflicts |= df_conflicts;
901 * Fetch the tree from the ODB for each peer directory in the
902 * n commits.
904 * For 2- and 3-way traversals, we try to avoid hitting the
905 * ODB twice for the same OID. This should yield a nice speed
906 * up in checkouts and merges when the commits are similar.
908 * We don't bother doing the full O(n^2) search for larger n,
909 * because wider traversals don't happen that often and we
910 * avoid the search setup.
912 * When 2 peer OIDs are the same, we just copy the tree
913 * descriptor data. This implicitly borrows the buffer
914 * data from the earlier cell.
916 for (i = 0; i < n; i++, dirmask >>= 1) {
917 if (i > 0 && are_same_oid(&names[i], &names[i - 1]))
918 t[i] = t[i - 1];
919 else if (i > 1 && are_same_oid(&names[i], &names[i - 2]))
920 t[i] = t[i - 2];
921 else {
922 const struct object_id *oid = NULL;
923 if (dirmask & 1)
924 oid = &names[i].oid;
925 buf[nr_buf++] = fill_tree_descriptor(the_repository, t + i, oid);
929 bottom = switch_cache_bottom(&newinfo);
930 ret = traverse_trees(o->src_index, n, t, &newinfo);
931 restore_cache_bottom(&newinfo, bottom);
933 for (i = 0; i < nr_buf; i++)
934 free(buf[i]);
936 return ret;
940 * Compare the traverse-path to the cache entry without actually
941 * having to generate the textual representation of the traverse
942 * path.
944 * NOTE! This *only* compares up to the size of the traverse path
945 * itself - the caller needs to do the final check for the cache
946 * entry having more data at the end!
948 static int do_compare_entry_piecewise(const struct cache_entry *ce,
949 const struct traverse_info *info,
950 const char *name, size_t namelen,
951 unsigned mode)
953 int pathlen, ce_len;
954 const char *ce_name;
956 if (info->prev) {
957 int cmp = do_compare_entry_piecewise(ce, info->prev,
958 info->name, info->namelen,
959 info->mode);
960 if (cmp)
961 return cmp;
963 pathlen = info->pathlen;
964 ce_len = ce_namelen(ce);
966 /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
967 if (ce_len < pathlen)
968 return -1;
970 ce_len -= pathlen;
971 ce_name = ce->name + pathlen;
973 return df_name_compare(ce_name, ce_len, S_IFREG, name, namelen, mode);
976 static int do_compare_entry(const struct cache_entry *ce,
977 const struct traverse_info *info,
978 const char *name, size_t namelen,
979 unsigned mode)
981 int pathlen, ce_len;
982 const char *ce_name;
983 int cmp;
984 unsigned ce_mode;
987 * If we have not precomputed the traverse path, it is quicker
988 * to avoid doing so. But if we have precomputed it,
989 * it is quicker to use the precomputed version.
991 if (!info->traverse_path)
992 return do_compare_entry_piecewise(ce, info, name, namelen, mode);
994 cmp = strncmp(ce->name, info->traverse_path, info->pathlen);
995 if (cmp)
996 return cmp;
998 pathlen = info->pathlen;
999 ce_len = ce_namelen(ce);
1001 if (ce_len < pathlen)
1002 return -1;
1004 ce_len -= pathlen;
1005 ce_name = ce->name + pathlen;
1007 ce_mode = S_ISSPARSEDIR(ce->ce_mode) ? S_IFDIR : S_IFREG;
1008 return df_name_compare(ce_name, ce_len, ce_mode, name, namelen, mode);
1011 static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
1013 int cmp = do_compare_entry(ce, info, n->path, n->pathlen, n->mode);
1014 if (cmp)
1015 return cmp;
1018 * At this point, we know that we have a prefix match. If ce
1019 * is a sparse directory, then allow an exact match. This only
1020 * works when the input name is a directory, since ce->name
1021 * ends in a directory separator.
1023 if (S_ISSPARSEDIR(ce->ce_mode) &&
1024 ce->ce_namelen == traverse_path_len(info, tree_entry_len(n)) + 1)
1025 return 0;
1028 * Even if the beginning compared identically, the ce should
1029 * compare as bigger than a directory leading up to it!
1031 return ce_namelen(ce) > traverse_path_len(info, tree_entry_len(n));
1034 static int ce_in_traverse_path(const struct cache_entry *ce,
1035 const struct traverse_info *info)
1037 if (!info->prev)
1038 return 1;
1039 if (do_compare_entry(ce, info->prev,
1040 info->name, info->namelen, info->mode))
1041 return 0;
1043 * If ce (blob) is the same name as the path (which is a tree
1044 * we will be descending into), it won't be inside it.
1046 return (info->pathlen < ce_namelen(ce));
1049 static struct cache_entry *create_ce_entry(const struct traverse_info *info,
1050 const struct name_entry *n,
1051 int stage,
1052 struct index_state *istate,
1053 int is_transient,
1054 int is_sparse_directory)
1056 size_t len = traverse_path_len(info, tree_entry_len(n));
1057 size_t alloc_len = is_sparse_directory ? len + 1 : len;
1058 struct cache_entry *ce =
1059 is_transient ?
1060 make_empty_transient_cache_entry(alloc_len, NULL) :
1061 make_empty_cache_entry(istate, alloc_len);
1063 ce->ce_mode = create_ce_mode(n->mode);
1064 ce->ce_flags = create_ce_flags(stage);
1065 ce->ce_namelen = len;
1066 oidcpy(&ce->oid, &n->oid);
1067 /* len+1 because the cache_entry allocates space for NUL */
1068 make_traverse_path(ce->name, len + 1, info, n->path, n->pathlen);
1070 if (is_sparse_directory) {
1071 ce->name[len] = '/';
1072 ce->name[len + 1] = '\0';
1073 ce->ce_namelen++;
1074 ce->ce_flags |= CE_SKIP_WORKTREE;
1077 return ce;
1081 * Determine whether the path specified by 'p' should be unpacked as a new
1082 * sparse directory in a sparse index. A new sparse directory 'A/':
1083 * - must be outside the sparse cone.
1084 * - must not already be in the index (i.e., no index entry with name 'A/'
1085 * exists).
1086 * - must not have any child entries in the index (i.e., no index entry
1087 * 'A/<something>' exists).
1088 * If 'p' meets the above requirements, return 1; otherwise, return 0.
1090 static int entry_is_new_sparse_dir(const struct traverse_info *info,
1091 const struct name_entry *p)
1093 int res, pos;
1094 struct strbuf dirpath = STRBUF_INIT;
1095 struct unpack_trees_options *o = info->data;
1097 if (!S_ISDIR(p->mode))
1098 return 0;
1101 * If the path is inside the sparse cone, it can't be a sparse directory.
1103 strbuf_add(&dirpath, info->traverse_path, info->pathlen);
1104 strbuf_add(&dirpath, p->path, p->pathlen);
1105 strbuf_addch(&dirpath, '/');
1106 if (path_in_cone_mode_sparse_checkout(dirpath.buf, o->src_index)) {
1107 res = 0;
1108 goto cleanup;
1111 pos = index_name_pos_sparse(o->src_index, dirpath.buf, dirpath.len);
1112 if (pos >= 0) {
1113 /* Path is already in the index, not a new sparse dir */
1114 res = 0;
1115 goto cleanup;
1118 /* Where would this sparse dir be inserted into the index? */
1119 pos = -pos - 1;
1120 if (pos >= o->src_index->cache_nr) {
1122 * Sparse dir would be inserted at the end of the index, so we
1123 * know it has no child entries.
1125 res = 1;
1126 goto cleanup;
1130 * If the dir has child entries in the index, the first would be at the
1131 * position the sparse directory would be inserted. If the entry at this
1132 * position is inside the dir, not a new sparse dir.
1134 res = strncmp(o->src_index->cache[pos]->name, dirpath.buf, dirpath.len);
1136 cleanup:
1137 strbuf_release(&dirpath);
1138 return res;
1142 * Note that traverse_by_cache_tree() duplicates some logic in this function
1143 * without actually calling it. If you change the logic here you may need to
1144 * check and change there as well.
1146 static int unpack_single_entry(int n, unsigned long mask,
1147 unsigned long dirmask,
1148 struct cache_entry **src,
1149 const struct name_entry *names,
1150 const struct traverse_info *info,
1151 int *is_new_sparse_dir)
1153 int i;
1154 struct unpack_trees_options *o = info->data;
1155 unsigned long conflicts = info->df_conflicts | dirmask;
1156 const struct name_entry *p = names;
1158 *is_new_sparse_dir = 0;
1159 if (mask == dirmask && !src[0]) {
1161 * If we're not in a sparse index, we can't unpack a directory
1162 * without recursing into it, so we return.
1164 if (!o->src_index->sparse_index)
1165 return 0;
1167 /* Find first entry with a real name (we could use "mask" too) */
1168 while (!p->mode)
1169 p++;
1172 * If the directory is completely missing from the index but
1173 * would otherwise be a sparse directory, we should unpack it.
1174 * If not, we'll return and continue recursively traversing the
1175 * tree.
1177 *is_new_sparse_dir = entry_is_new_sparse_dir(info, p);
1178 if (!*is_new_sparse_dir)
1179 return 0;
1183 * When we are unpacking a sparse directory, then this isn't necessarily
1184 * a directory-file conflict.
1186 if (mask == dirmask &&
1187 (*is_new_sparse_dir || (src[0] && S_ISSPARSEDIR(src[0]->ce_mode))))
1188 conflicts = 0;
1191 * Ok, we've filled in up to any potential index entry in src[0],
1192 * now do the rest.
1194 for (i = 0; i < n; i++) {
1195 int stage;
1196 unsigned int bit = 1ul << i;
1197 if (conflicts & bit) {
1198 src[i + o->merge] = o->df_conflict_entry;
1199 continue;
1201 if (!(mask & bit))
1202 continue;
1203 if (!o->merge)
1204 stage = 0;
1205 else if (i + 1 < o->head_idx)
1206 stage = 1;
1207 else if (i + 1 > o->head_idx)
1208 stage = 3;
1209 else
1210 stage = 2;
1213 * If the merge bit is set, then the cache entries are
1214 * discarded in the following block. In this case,
1215 * construct "transient" cache_entries, as they are
1216 * not stored in the index. otherwise construct the
1217 * cache entry from the index aware logic.
1219 src[i + o->merge] = create_ce_entry(info, names + i, stage,
1220 &o->internal.result,
1221 o->merge, bit & dirmask);
1224 if (o->merge) {
1225 int rc = call_unpack_fn((const struct cache_entry * const *)src,
1227 for (i = 0; i < n; i++) {
1228 struct cache_entry *ce = src[i + o->merge];
1229 if (ce != o->df_conflict_entry)
1230 discard_cache_entry(ce);
1232 return rc;
1235 for (i = 0; i < n; i++)
1236 if (src[i] && src[i] != o->df_conflict_entry)
1237 if (do_add_entry(o, src[i], 0, 0))
1238 return -1;
1240 return 0;
1243 static int unpack_failed(struct unpack_trees_options *o, const char *message)
1245 discard_index(&o->internal.result);
1246 if (!o->quiet && !o->exiting_early) {
1247 if (message)
1248 return error("%s", message);
1249 return -1;
1251 return -1;
1255 * The tree traversal is looking at name p. If we have a matching entry,
1256 * return it. If name p is a directory in the index, do not return
1257 * anything, as we will want to match it when the traversal descends into
1258 * the directory.
1260 static int find_cache_pos(struct traverse_info *info,
1261 const char *p, size_t p_len)
1263 int pos;
1264 struct unpack_trees_options *o = info->data;
1265 struct index_state *index = o->src_index;
1266 int pfxlen = info->pathlen;
1268 for (pos = o->internal.cache_bottom; pos < index->cache_nr; pos++) {
1269 const struct cache_entry *ce = index->cache[pos];
1270 const char *ce_name, *ce_slash;
1271 int cmp, ce_len;
1273 if (ce->ce_flags & CE_UNPACKED) {
1275 * cache_bottom entry is already unpacked, so
1276 * we can never match it; don't check it
1277 * again.
1279 if (pos == o->internal.cache_bottom)
1280 ++o->internal.cache_bottom;
1281 continue;
1283 if (!ce_in_traverse_path(ce, info)) {
1285 * Check if we can skip future cache checks
1286 * (because we're already past all possible
1287 * entries in the traverse path).
1289 if (info->traverse_path) {
1290 if (strncmp(ce->name, info->traverse_path,
1291 info->pathlen) > 0)
1292 break;
1294 continue;
1296 ce_name = ce->name + pfxlen;
1297 ce_slash = strchr(ce_name, '/');
1298 if (ce_slash)
1299 ce_len = ce_slash - ce_name;
1300 else
1301 ce_len = ce_namelen(ce) - pfxlen;
1302 cmp = name_compare(p, p_len, ce_name, ce_len);
1304 * Exact match; if we have a directory we need to
1305 * delay returning it.
1307 if (!cmp)
1308 return ce_slash ? -2 - pos : pos;
1309 if (0 < cmp)
1310 continue; /* keep looking */
1312 * ce_name sorts after p->path; could it be that we
1313 * have files under p->path directory in the index?
1314 * E.g. ce_name == "t-i", and p->path == "t"; we may
1315 * have "t/a" in the index.
1317 if (p_len < ce_len && !memcmp(ce_name, p, p_len) &&
1318 ce_name[p_len] < '/')
1319 continue; /* keep looking */
1320 break;
1322 return -1;
1326 * Given a sparse directory entry 'ce', compare ce->name to
1327 * info->traverse_path + p->path + '/' if info->traverse_path
1328 * is non-empty.
1330 * Compare ce->name to p->path + '/' otherwise. Note that
1331 * ce->name must end in a trailing '/' because it is a sparse
1332 * directory entry.
1334 static int sparse_dir_matches_path(const struct cache_entry *ce,
1335 struct traverse_info *info,
1336 const struct name_entry *p)
1338 assert(S_ISSPARSEDIR(ce->ce_mode));
1339 assert(ce->name[ce->ce_namelen - 1] == '/');
1341 if (info->pathlen)
1342 return ce->ce_namelen == info->pathlen + p->pathlen + 1 &&
1343 ce->name[info->pathlen - 1] == '/' &&
1344 !strncmp(ce->name, info->traverse_path, info->pathlen) &&
1345 !strncmp(ce->name + info->pathlen, p->path, p->pathlen);
1346 return ce->ce_namelen == p->pathlen + 1 &&
1347 !strncmp(ce->name, p->path, p->pathlen);
1350 static struct cache_entry *find_cache_entry(struct traverse_info *info,
1351 const struct name_entry *p)
1353 const char *path;
1354 int pos = find_cache_pos(info, p->path, p->pathlen);
1355 struct unpack_trees_options *o = info->data;
1357 if (0 <= pos)
1358 return o->src_index->cache[pos];
1361 * Check for a sparse-directory entry named "path/".
1362 * Due to the input p->path not having a trailing
1363 * slash, the negative 'pos' value overshoots the
1364 * expected position, hence "-2" instead of "-1".
1366 pos = -pos - 2;
1368 if (pos < 0 || pos >= o->src_index->cache_nr)
1369 return NULL;
1372 * Due to lexicographic sorting and sparse directory
1373 * entries ending with a trailing slash, our path as a
1374 * sparse directory (e.g "subdir/") and our path as a
1375 * file (e.g. "subdir") might be separated by other
1376 * paths (e.g. "subdir-").
1378 while (pos >= 0) {
1379 struct cache_entry *ce = o->src_index->cache[pos];
1381 if (!skip_prefix(ce->name, info->traverse_path, &path) ||
1382 strncmp(path, p->path, p->pathlen) ||
1383 path[p->pathlen] != '/')
1384 return NULL;
1386 if (S_ISSPARSEDIR(ce->ce_mode) &&
1387 sparse_dir_matches_path(ce, info, p))
1388 return ce;
1390 pos--;
1393 return NULL;
1396 static void debug_path(struct traverse_info *info)
1398 if (info->prev) {
1399 debug_path(info->prev);
1400 if (*info->prev->name)
1401 putchar('/');
1403 printf("%s", info->name);
1406 static void debug_name_entry(int i, struct name_entry *n)
1408 printf("ent#%d %06o %s\n", i,
1409 n->path ? n->mode : 0,
1410 n->path ? n->path : "(missing)");
1413 static void debug_unpack_callback(int n,
1414 unsigned long mask,
1415 unsigned long dirmask,
1416 struct name_entry *names,
1417 struct traverse_info *info)
1419 int i;
1420 printf("* unpack mask %lu, dirmask %lu, cnt %d ",
1421 mask, dirmask, n);
1422 debug_path(info);
1423 putchar('\n');
1424 for (i = 0; i < n; i++)
1425 debug_name_entry(i, names + i);
1429 * Returns true if and only if the given cache_entry is a
1430 * sparse-directory entry that matches the given name_entry
1431 * from the tree walk at the given traverse_info.
1433 static int is_sparse_directory_entry(struct cache_entry *ce,
1434 const struct name_entry *name,
1435 struct traverse_info *info)
1437 if (!ce || !name || !S_ISSPARSEDIR(ce->ce_mode))
1438 return 0;
1440 return sparse_dir_matches_path(ce, info, name);
1443 static int unpack_sparse_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1445 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1446 struct unpack_trees_options *o = info->data;
1447 int ret, is_new_sparse_dir;
1449 assert(o->merge);
1452 * Unlike in 'unpack_callback', where src[0] is derived from the index when
1453 * merging, src[0] is a transient cache entry derived from the first tree
1454 * provided. Create the temporary entry as if it came from a non-sparse index.
1456 if (!is_null_oid(&names[0].oid)) {
1457 src[0] = create_ce_entry(info, &names[0], 0,
1458 &o->internal.result, 1,
1459 dirmask & (1ul << 0));
1460 src[0]->ce_flags |= (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1464 * 'unpack_single_entry' assumes that src[0] is derived directly from
1465 * the index, rather than from an entry in 'names'. This is *not* true when
1466 * merging a sparse directory, in which case names[0] is the "index" source
1467 * entry. To match the expectations of 'unpack_single_entry', shift past the
1468 * "index" tree (i.e., names[0]) and adjust 'names', 'n', 'mask', and
1469 * 'dirmask' accordingly.
1471 ret = unpack_single_entry(n - 1, mask >> 1, dirmask >> 1, src, names + 1, info, &is_new_sparse_dir);
1473 if (src[0])
1474 discard_cache_entry(src[0]);
1476 return ret >= 0 ? mask : -1;
1480 * Note that traverse_by_cache_tree() duplicates some logic in this function
1481 * without actually calling it. If you change the logic here you may need to
1482 * check and change there as well.
1484 static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1486 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1487 struct unpack_trees_options *o = info->data;
1488 const struct name_entry *p = names;
1489 int is_new_sparse_dir;
1491 /* Find first entry with a real name (we could use "mask" too) */
1492 while (!p->mode)
1493 p++;
1495 if (o->internal.debug_unpack)
1496 debug_unpack_callback(n, mask, dirmask, names, info);
1498 /* Are we supposed to look at the index too? */
1499 if (o->merge) {
1500 while (1) {
1501 int cmp;
1502 struct cache_entry *ce;
1504 if (o->diff_index_cached)
1505 ce = next_cache_entry(o);
1506 else
1507 ce = find_cache_entry(info, p);
1509 if (!ce)
1510 break;
1511 cmp = compare_entry(ce, info, p);
1512 if (cmp < 0) {
1513 if (unpack_index_entry(ce, o) < 0)
1514 return unpack_failed(o, NULL);
1515 continue;
1517 if (!cmp) {
1518 if (ce_stage(ce)) {
1520 * If we skip unmerged index
1521 * entries, we'll skip this
1522 * entry *and* the tree
1523 * entries associated with it!
1525 if (o->skip_unmerged) {
1526 add_same_unmerged(ce, o);
1527 return mask;
1530 src[0] = ce;
1532 break;
1536 if (unpack_single_entry(n, mask, dirmask, src, names, info, &is_new_sparse_dir))
1537 return -1;
1539 if (o->merge && src[0]) {
1540 if (ce_stage(src[0]))
1541 mark_ce_used_same_name(src[0], o);
1542 else
1543 mark_ce_used(src[0], o);
1546 /* Now handle any directories.. */
1547 if (dirmask) {
1548 /* special case: "diff-index --cached" looking at a tree */
1549 if (o->diff_index_cached &&
1550 n == 1 && dirmask == 1 && S_ISDIR(names->mode)) {
1551 int matches;
1552 matches = cache_tree_matches_traversal(o->src_index->cache_tree,
1553 names, info);
1555 * Everything under the name matches; skip the
1556 * entire hierarchy. diff_index_cached codepath
1557 * special cases D/F conflicts in such a way that
1558 * it does not do any look-ahead, so this is safe.
1560 if (matches) {
1562 * Only increment the cache_bottom if the
1563 * directory isn't a sparse directory index
1564 * entry (if it is, it was already incremented)
1565 * in 'mark_ce_used()'
1567 if (!src[0] || !S_ISSPARSEDIR(src[0]->ce_mode))
1568 o->internal.cache_bottom += matches;
1569 return mask;
1573 if (!is_sparse_directory_entry(src[0], p, info) &&
1574 !is_new_sparse_dir &&
1575 traverse_trees_recursive(n, dirmask, mask & ~dirmask,
1576 names, info) < 0) {
1577 return -1;
1580 return mask;
1583 return mask;
1586 static int clear_ce_flags_1(struct index_state *istate,
1587 struct cache_entry **cache, int nr,
1588 struct strbuf *prefix,
1589 int select_mask, int clear_mask,
1590 struct pattern_list *pl,
1591 enum pattern_match_result default_match,
1592 int progress_nr);
1594 /* Whole directory matching */
1595 static int clear_ce_flags_dir(struct index_state *istate,
1596 struct cache_entry **cache, int nr,
1597 struct strbuf *prefix,
1598 char *basename,
1599 int select_mask, int clear_mask,
1600 struct pattern_list *pl,
1601 enum pattern_match_result default_match,
1602 int progress_nr)
1604 struct cache_entry **cache_end;
1605 int dtype = DT_DIR;
1606 int rc;
1607 enum pattern_match_result ret, orig_ret;
1608 orig_ret = path_matches_pattern_list(prefix->buf, prefix->len,
1609 basename, &dtype, pl, istate);
1611 strbuf_addch(prefix, '/');
1613 /* If undecided, use matching result of parent dir in defval */
1614 if (orig_ret == UNDECIDED)
1615 ret = default_match;
1616 else
1617 ret = orig_ret;
1619 for (cache_end = cache; cache_end != cache + nr; cache_end++) {
1620 struct cache_entry *ce = *cache_end;
1621 if (strncmp(ce->name, prefix->buf, prefix->len))
1622 break;
1625 if (pl->use_cone_patterns && orig_ret == MATCHED_RECURSIVE) {
1626 struct cache_entry **ce = cache;
1627 rc = cache_end - cache;
1629 while (ce < cache_end) {
1630 (*ce)->ce_flags &= ~clear_mask;
1631 ce++;
1633 } else if (pl->use_cone_patterns && orig_ret == NOT_MATCHED) {
1634 rc = cache_end - cache;
1635 } else {
1636 rc = clear_ce_flags_1(istate, cache, cache_end - cache,
1637 prefix,
1638 select_mask, clear_mask,
1639 pl, ret,
1640 progress_nr);
1643 strbuf_setlen(prefix, prefix->len - 1);
1644 return rc;
1648 * Traverse the index, find every entry that matches according to
1649 * o->pl. Do "ce_flags &= ~clear_mask" on those entries. Return the
1650 * number of traversed entries.
1652 * If select_mask is non-zero, only entries whose ce_flags has on of
1653 * those bits enabled are traversed.
1655 * cache : pointer to an index entry
1656 * prefix_len : an offset to its path
1658 * The current path ("prefix") including the trailing '/' is
1659 * cache[0]->name[0..(prefix_len-1)]
1660 * Top level path has prefix_len zero.
1662 static int clear_ce_flags_1(struct index_state *istate,
1663 struct cache_entry **cache, int nr,
1664 struct strbuf *prefix,
1665 int select_mask, int clear_mask,
1666 struct pattern_list *pl,
1667 enum pattern_match_result default_match,
1668 int progress_nr)
1670 struct cache_entry **cache_end = nr ? cache + nr : cache;
1673 * Process all entries that have the given prefix and meet
1674 * select_mask condition
1676 while(cache != cache_end) {
1677 struct cache_entry *ce = *cache;
1678 const char *name, *slash;
1679 int len, dtype;
1680 enum pattern_match_result ret;
1682 display_progress(istate->progress, progress_nr);
1684 if (select_mask && !(ce->ce_flags & select_mask)) {
1685 cache++;
1686 progress_nr++;
1687 continue;
1690 if (prefix->len && strncmp(ce->name, prefix->buf, prefix->len))
1691 break;
1693 name = ce->name + prefix->len;
1694 slash = strchr(name, '/');
1696 /* If it's a directory, try whole directory match first */
1697 if (slash) {
1698 int processed;
1700 len = slash - name;
1701 strbuf_add(prefix, name, len);
1703 processed = clear_ce_flags_dir(istate, cache, cache_end - cache,
1704 prefix,
1705 prefix->buf + prefix->len - len,
1706 select_mask, clear_mask,
1707 pl, default_match,
1708 progress_nr);
1710 /* clear_c_f_dir eats a whole dir already? */
1711 if (processed) {
1712 cache += processed;
1713 progress_nr += processed;
1714 strbuf_setlen(prefix, prefix->len - len);
1715 continue;
1718 strbuf_addch(prefix, '/');
1719 processed = clear_ce_flags_1(istate, cache, cache_end - cache,
1720 prefix,
1721 select_mask, clear_mask, pl,
1722 default_match, progress_nr);
1724 cache += processed;
1725 progress_nr += processed;
1727 strbuf_setlen(prefix, prefix->len - len - 1);
1728 continue;
1731 /* Non-directory */
1732 dtype = ce_to_dtype(ce);
1733 ret = path_matches_pattern_list(ce->name,
1734 ce_namelen(ce),
1735 name, &dtype, pl, istate);
1736 if (ret == UNDECIDED)
1737 ret = default_match;
1738 if (ret == MATCHED || ret == MATCHED_RECURSIVE)
1739 ce->ce_flags &= ~clear_mask;
1740 cache++;
1741 progress_nr++;
1744 display_progress(istate->progress, progress_nr);
1745 return nr - (cache_end - cache);
1748 static int clear_ce_flags(struct index_state *istate,
1749 int select_mask, int clear_mask,
1750 struct pattern_list *pl,
1751 int show_progress)
1753 static struct strbuf prefix = STRBUF_INIT;
1754 char label[100];
1755 int rval;
1757 strbuf_reset(&prefix);
1758 if (show_progress)
1759 istate->progress = start_delayed_progress(
1760 _("Updating index flags"),
1761 istate->cache_nr);
1763 xsnprintf(label, sizeof(label), "clear_ce_flags(0x%08lx,0x%08lx)",
1764 (unsigned long)select_mask, (unsigned long)clear_mask);
1765 trace2_region_enter("unpack_trees", label, the_repository);
1766 rval = clear_ce_flags_1(istate,
1767 istate->cache,
1768 istate->cache_nr,
1769 &prefix,
1770 select_mask, clear_mask,
1771 pl, 0, 0);
1772 trace2_region_leave("unpack_trees", label, the_repository);
1774 stop_progress(&istate->progress);
1775 return rval;
1779 * Set/Clear CE_NEW_SKIP_WORKTREE according to $GIT_DIR/info/sparse-checkout
1781 static void mark_new_skip_worktree(struct pattern_list *pl,
1782 struct index_state *istate,
1783 int select_flag, int skip_wt_flag,
1784 int show_progress)
1786 int i;
1789 * 1. Pretend the narrowest worktree: only unmerged entries
1790 * are checked out
1792 for (i = 0; i < istate->cache_nr; i++) {
1793 struct cache_entry *ce = istate->cache[i];
1795 if (select_flag && !(ce->ce_flags & select_flag))
1796 continue;
1798 if (!ce_stage(ce) && !(ce->ce_flags & CE_CONFLICTED))
1799 ce->ce_flags |= skip_wt_flag;
1800 else
1801 ce->ce_flags &= ~skip_wt_flag;
1805 * 2. Widen worktree according to sparse-checkout file.
1806 * Matched entries will have skip_wt_flag cleared (i.e. "in")
1808 clear_ce_flags(istate, select_flag, skip_wt_flag, pl, show_progress);
1811 static void populate_from_existing_patterns(struct unpack_trees_options *o,
1812 struct pattern_list *pl)
1814 if (get_sparse_checkout_patterns(pl) < 0)
1815 o->skip_sparse_checkout = 1;
1816 else
1817 o->internal.pl = pl;
1820 static void update_sparsity_for_prefix(const char *prefix,
1821 struct index_state *istate)
1823 int prefix_len = strlen(prefix);
1824 struct strbuf ce_prefix = STRBUF_INIT;
1826 if (!istate->sparse_index)
1827 return;
1829 while (prefix_len > 0 && prefix[prefix_len - 1] == '/')
1830 prefix_len--;
1832 if (prefix_len <= 0)
1833 BUG("Invalid prefix passed to update_sparsity_for_prefix");
1835 strbuf_grow(&ce_prefix, prefix_len + 1);
1836 strbuf_add(&ce_prefix, prefix, prefix_len);
1837 strbuf_addch(&ce_prefix, '/');
1840 * If the prefix points to a sparse directory or a path inside a sparse
1841 * directory, the index should be expanded. This is accomplished in one
1842 * of two ways:
1843 * - if the prefix is inside a sparse directory, it will be expanded by
1844 * the 'ensure_full_index(...)' call in 'index_name_pos(...)'.
1845 * - if the prefix matches an existing sparse directory entry,
1846 * 'index_name_pos(...)' will return its index position, triggering
1847 * the 'ensure_full_index(...)' below.
1849 if (!path_in_cone_mode_sparse_checkout(ce_prefix.buf, istate) &&
1850 index_name_pos(istate, ce_prefix.buf, ce_prefix.len) >= 0)
1851 ensure_full_index(istate);
1853 strbuf_release(&ce_prefix);
1856 static int verify_absent(const struct cache_entry *,
1857 enum unpack_trees_error_types,
1858 struct unpack_trees_options *);
1860 * N-way merge "len" trees. Returns 0 on success, -1 on failure to manipulate the
1861 * resulting index, -2 on failure to reflect the changes to the work tree.
1863 * CE_ADDED, CE_UNPACKED and CE_NEW_SKIP_WORKTREE are used internally
1865 int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
1867 struct repository *repo = the_repository;
1868 int i, ret;
1869 static struct cache_entry *dfc;
1870 struct pattern_list pl;
1871 int free_pattern_list = 0;
1872 struct dir_struct dir = DIR_INIT;
1874 if (o->reset == UNPACK_RESET_INVALID)
1875 BUG("o->reset had a value of 1; should be UNPACK_TREES_*_UNTRACKED");
1877 if (len > MAX_UNPACK_TREES)
1878 die("unpack_trees takes at most %d trees", MAX_UNPACK_TREES);
1879 if (o->internal.dir)
1880 BUG("o->internal.dir is for internal use only");
1881 if (o->internal.pl)
1882 BUG("o->internal.pl is for internal use only");
1883 if (o->df_conflict_entry)
1884 BUG("o->df_conflict_entry is an output only field");
1886 trace_performance_enter();
1887 trace2_region_enter("unpack_trees", "unpack_trees", the_repository);
1889 prepare_repo_settings(repo);
1890 if (repo->settings.command_requires_full_index) {
1891 ensure_full_index(o->src_index);
1892 if (o->dst_index)
1893 ensure_full_index(o->dst_index);
1896 if (o->reset == UNPACK_RESET_OVERWRITE_UNTRACKED &&
1897 o->preserve_ignored)
1898 BUG("UNPACK_RESET_OVERWRITE_UNTRACKED incompatible with preserved ignored files");
1900 if (!o->preserve_ignored) {
1901 o->internal.dir = &dir;
1902 o->internal.dir->flags |= DIR_SHOW_IGNORED;
1903 setup_standard_excludes(o->internal.dir);
1906 if (o->prefix)
1907 update_sparsity_for_prefix(o->prefix, o->src_index);
1909 if (!core_apply_sparse_checkout || !o->update)
1910 o->skip_sparse_checkout = 1;
1911 if (!o->skip_sparse_checkout) {
1912 memset(&pl, 0, sizeof(pl));
1913 free_pattern_list = 1;
1914 populate_from_existing_patterns(o, &pl);
1917 index_state_init(&o->internal.result, o->src_index->repo);
1918 o->internal.result.initialized = 1;
1919 o->internal.result.timestamp.sec = o->src_index->timestamp.sec;
1920 o->internal.result.timestamp.nsec = o->src_index->timestamp.nsec;
1921 o->internal.result.version = o->src_index->version;
1922 if (!o->src_index->split_index) {
1923 o->internal.result.split_index = NULL;
1924 } else if (o->src_index == o->dst_index) {
1926 * o->dst_index (and thus o->src_index) will be discarded
1927 * and overwritten with o->internal.result at the end of
1928 * this function, so just use src_index's split_index to
1929 * avoid having to create a new one.
1931 o->internal.result.split_index = o->src_index->split_index;
1932 if (o->src_index->cache_changed & SPLIT_INDEX_ORDERED)
1933 o->internal.result.cache_changed |= SPLIT_INDEX_ORDERED;
1934 o->internal.result.split_index->refcount++;
1935 } else {
1936 o->internal.result.split_index =
1937 init_split_index(&o->internal.result);
1939 oidcpy(&o->internal.result.oid, &o->src_index->oid);
1940 o->internal.merge_size = len;
1941 mark_all_ce_unused(o->src_index);
1943 o->internal.result.fsmonitor_last_update =
1944 xstrdup_or_null(o->src_index->fsmonitor_last_update);
1945 o->internal.result.fsmonitor_has_run_once = o->src_index->fsmonitor_has_run_once;
1947 if (!o->src_index->initialized &&
1948 !repo->settings.command_requires_full_index &&
1949 is_sparse_index_allowed(&o->internal.result, 0))
1950 o->internal.result.sparse_index = 1;
1953 * Sparse checkout loop #1: set NEW_SKIP_WORKTREE on existing entries
1955 if (!o->skip_sparse_checkout)
1956 mark_new_skip_worktree(o->internal.pl, o->src_index, 0,
1957 CE_NEW_SKIP_WORKTREE, o->verbose_update);
1959 if (!dfc)
1960 dfc = xcalloc(1, cache_entry_size(0));
1961 o->df_conflict_entry = dfc;
1963 if (len) {
1964 const char *prefix = o->prefix ? o->prefix : "";
1965 struct traverse_info info;
1967 setup_traverse_info(&info, prefix);
1968 info.fn = unpack_callback;
1969 info.data = o;
1970 info.show_all_errors = o->internal.show_all_errors;
1971 info.pathspec = o->pathspec;
1973 if (o->prefix) {
1975 * Unpack existing index entries that sort before the
1976 * prefix the tree is spliced into. Note that o->merge
1977 * is always true in this case.
1979 while (1) {
1980 struct cache_entry *ce = next_cache_entry(o);
1981 if (!ce)
1982 break;
1983 if (ce_in_traverse_path(ce, &info))
1984 break;
1985 if (unpack_index_entry(ce, o) < 0)
1986 goto return_failed;
1990 trace_performance_enter();
1991 trace2_region_enter("unpack_trees", "traverse_trees", the_repository);
1992 ret = traverse_trees(o->src_index, len, t, &info);
1993 trace2_region_leave("unpack_trees", "traverse_trees", the_repository);
1994 trace_performance_leave("traverse_trees");
1995 if (ret < 0)
1996 goto return_failed;
1999 /* Any left-over entries in the index? */
2000 if (o->merge) {
2001 while (1) {
2002 struct cache_entry *ce = next_cache_entry(o);
2003 if (!ce)
2004 break;
2005 if (unpack_index_entry(ce, o) < 0)
2006 goto return_failed;
2009 mark_all_ce_unused(o->src_index);
2011 if (o->trivial_merges_only && o->internal.nontrivial_merge) {
2012 ret = unpack_failed(o, "Merge requires file-level merging");
2013 goto done;
2016 if (!o->skip_sparse_checkout) {
2018 * Sparse checkout loop #2: set NEW_SKIP_WORKTREE on entries not in loop #1
2019 * If they will have NEW_SKIP_WORKTREE, also set CE_SKIP_WORKTREE
2020 * so apply_sparse_checkout() won't attempt to remove it from worktree
2022 mark_new_skip_worktree(o->internal.pl, &o->internal.result,
2023 CE_ADDED, CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE,
2024 o->verbose_update);
2026 ret = 0;
2027 for (i = 0; i < o->internal.result.cache_nr; i++) {
2028 struct cache_entry *ce = o->internal.result.cache[i];
2031 * Entries marked with CE_ADDED in merged_entry() do not have
2032 * verify_absent() check (the check is effectively disabled
2033 * because CE_NEW_SKIP_WORKTREE is set unconditionally).
2035 * Do the real check now because we have had
2036 * correct CE_NEW_SKIP_WORKTREE
2038 if (ce->ce_flags & CE_ADDED &&
2039 verify_absent(ce, WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN, o))
2040 ret = 1;
2042 if (apply_sparse_checkout(&o->internal.result, ce, o))
2043 ret = 1;
2045 if (ret == 1) {
2047 * Inability to sparsify or de-sparsify individual
2048 * paths is not an error, but just a warning.
2050 if (o->internal.show_all_errors)
2051 display_warning_msgs(o);
2052 ret = 0;
2056 ret = check_updates(o, &o->internal.result) ? (-2) : 0;
2057 if (o->dst_index) {
2058 move_index_extensions(&o->internal.result, o->src_index);
2059 if (!ret) {
2060 if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0))
2061 cache_tree_verify(the_repository,
2062 &o->internal.result);
2063 if (!o->skip_cache_tree_update &&
2064 !cache_tree_fully_valid(o->internal.result.cache_tree))
2065 cache_tree_update(&o->internal.result,
2066 WRITE_TREE_SILENT |
2067 WRITE_TREE_REPAIR);
2070 o->internal.result.updated_workdir = 1;
2071 discard_index(o->dst_index);
2072 *o->dst_index = o->internal.result;
2073 } else {
2074 discard_index(&o->internal.result);
2076 o->src_index = NULL;
2078 done:
2079 if (free_pattern_list)
2080 clear_pattern_list(&pl);
2081 if (o->internal.dir) {
2082 dir_clear(o->internal.dir);
2083 o->internal.dir = NULL;
2085 trace2_region_leave("unpack_trees", "unpack_trees", the_repository);
2086 trace_performance_leave("unpack_trees");
2087 return ret;
2089 return_failed:
2090 if (o->internal.show_all_errors)
2091 display_error_msgs(o);
2092 mark_all_ce_unused(o->src_index);
2093 ret = unpack_failed(o, NULL);
2094 if (o->exiting_early)
2095 ret = 0;
2096 goto done;
2100 * Update SKIP_WORKTREE bits according to sparsity patterns, and update
2101 * working directory to match.
2103 * CE_NEW_SKIP_WORKTREE is used internally.
2105 enum update_sparsity_result update_sparsity(struct unpack_trees_options *o,
2106 struct pattern_list *pl)
2108 enum update_sparsity_result ret = UPDATE_SPARSITY_SUCCESS;
2109 int i;
2110 unsigned old_show_all_errors;
2111 int free_pattern_list = 0;
2113 old_show_all_errors = o->internal.show_all_errors;
2114 o->internal.show_all_errors = 1;
2115 index_state_init(&o->internal.result, o->src_index->repo);
2117 /* Sanity checks */
2118 if (!o->update || o->index_only || o->skip_sparse_checkout)
2119 BUG("update_sparsity() is for reflecting sparsity patterns in working directory");
2120 if (o->src_index != o->dst_index || o->fn)
2121 BUG("update_sparsity() called wrong");
2123 trace_performance_enter();
2125 /* If we weren't given patterns, use the recorded ones */
2126 if (!pl) {
2127 free_pattern_list = 1;
2128 pl = xcalloc(1, sizeof(*pl));
2129 populate_from_existing_patterns(o, pl);
2131 o->internal.pl = pl;
2133 /* Expand sparse directories as needed */
2134 expand_index(o->src_index, o->internal.pl);
2136 /* Set NEW_SKIP_WORKTREE on existing entries. */
2137 mark_all_ce_unused(o->src_index);
2138 mark_new_skip_worktree(o->internal.pl, o->src_index, 0,
2139 CE_NEW_SKIP_WORKTREE, o->verbose_update);
2141 /* Then loop over entries and update/remove as needed */
2142 ret = UPDATE_SPARSITY_SUCCESS;
2143 for (i = 0; i < o->src_index->cache_nr; i++) {
2144 struct cache_entry *ce = o->src_index->cache[i];
2147 if (ce_stage(ce)) {
2148 /* -1 because for loop will increment by 1 */
2149 i += warn_conflicted_path(o->src_index, i, o) - 1;
2150 ret = UPDATE_SPARSITY_WARNINGS;
2151 continue;
2154 if (apply_sparse_checkout(o->src_index, ce, o))
2155 ret = UPDATE_SPARSITY_WARNINGS;
2158 if (check_updates(o, o->src_index))
2159 ret = UPDATE_SPARSITY_WORKTREE_UPDATE_FAILURES;
2161 display_warning_msgs(o);
2162 o->internal.show_all_errors = old_show_all_errors;
2163 if (free_pattern_list) {
2164 clear_pattern_list(pl);
2165 free(pl);
2166 o->internal.pl = NULL;
2168 trace_performance_leave("update_sparsity");
2169 return ret;
2172 /* Here come the merge functions */
2174 static int reject_merge(const struct cache_entry *ce,
2175 struct unpack_trees_options *o)
2177 return add_rejected_path(o, ERROR_WOULD_OVERWRITE, ce->name);
2180 static int same(const struct cache_entry *a, const struct cache_entry *b)
2182 if (!!a != !!b)
2183 return 0;
2184 if (!a && !b)
2185 return 1;
2186 if ((a->ce_flags | b->ce_flags) & CE_CONFLICTED)
2187 return 0;
2188 return a->ce_mode == b->ce_mode &&
2189 oideq(&a->oid, &b->oid);
2194 * When a CE gets turned into an unmerged entry, we
2195 * want it to be up-to-date
2197 static int verify_uptodate_1(const struct cache_entry *ce,
2198 struct unpack_trees_options *o,
2199 enum unpack_trees_error_types error_type)
2201 struct stat st;
2203 if (o->index_only)
2204 return 0;
2207 * CE_VALID and CE_SKIP_WORKTREE cheat, we better check again
2208 * if this entry is truly up-to-date because this file may be
2209 * overwritten.
2211 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2212 ; /* keep checking */
2213 else if (o->reset || ce_uptodate(ce))
2214 return 0;
2216 if (!lstat(ce->name, &st)) {
2217 int flags = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE;
2218 unsigned changed = ie_match_stat(o->src_index, ce, &st, flags);
2220 if (submodule_from_ce(ce)) {
2221 int r = check_submodule_move_head(ce,
2222 "HEAD", oid_to_hex(&ce->oid), o);
2223 if (r)
2224 return add_rejected_path(o, error_type, ce->name);
2225 return 0;
2228 if (!changed)
2229 return 0;
2231 * Historic default policy was to allow submodule to be out
2232 * of sync wrt the superproject index. If the submodule was
2233 * not considered interesting above, we don't care here.
2235 if (S_ISGITLINK(ce->ce_mode))
2236 return 0;
2238 errno = 0;
2240 if (errno == ENOENT)
2241 return 0;
2242 return add_rejected_path(o, error_type, ce->name);
2245 int verify_uptodate(const struct cache_entry *ce,
2246 struct unpack_trees_options *o)
2248 if (!o->skip_sparse_checkout &&
2249 (ce->ce_flags & CE_SKIP_WORKTREE) &&
2250 (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2251 return 0;
2252 return verify_uptodate_1(ce, o, ERROR_NOT_UPTODATE_FILE);
2255 static int verify_uptodate_sparse(const struct cache_entry *ce,
2256 struct unpack_trees_options *o)
2258 return verify_uptodate_1(ce, o, WARNING_SPARSE_NOT_UPTODATE_FILE);
2262 * TODO: We should actually invalidate o->internal.result, not src_index [1].
2263 * But since cache tree and untracked cache both are not copied to
2264 * o->internal.result until unpacking is complete, we invalidate them on
2265 * src_index instead with the assumption that they will be copied to
2266 * dst_index at the end.
2268 * [1] src_index->cache_tree is also used in unpack_callback() so if
2269 * we invalidate o->internal.result, we need to update it to use
2270 * o->internal.result.cache_tree as well.
2272 static void invalidate_ce_path(const struct cache_entry *ce,
2273 struct unpack_trees_options *o)
2275 if (!ce)
2276 return;
2277 cache_tree_invalidate_path(o->src_index, ce->name);
2278 untracked_cache_invalidate_path(o->src_index, ce->name, 1);
2282 * Check that checking out ce->sha1 in subdir ce->name is not
2283 * going to overwrite any working files.
2285 static int verify_clean_submodule(const char *old_sha1,
2286 const struct cache_entry *ce,
2287 struct unpack_trees_options *o)
2289 if (!submodule_from_ce(ce))
2290 return 0;
2292 return check_submodule_move_head(ce, old_sha1,
2293 oid_to_hex(&ce->oid), o);
2296 static int verify_clean_subdirectory(const struct cache_entry *ce,
2297 struct unpack_trees_options *o)
2300 * we are about to extract "ce->name"; we would not want to lose
2301 * anything in the existing directory there.
2303 int namelen;
2304 int i;
2305 struct dir_struct d;
2306 char *pathbuf;
2307 int cnt = 0;
2309 if (S_ISGITLINK(ce->ce_mode)) {
2310 struct object_id oid;
2311 int sub_head = resolve_gitlink_ref(ce->name, "HEAD", &oid);
2313 * If we are not going to update the submodule, then
2314 * we don't care.
2316 if (!sub_head && oideq(&oid, &ce->oid))
2317 return 0;
2318 return verify_clean_submodule(sub_head ? NULL : oid_to_hex(&oid),
2319 ce, o);
2323 * First let's make sure we do not have a local modification
2324 * in that directory.
2326 namelen = ce_namelen(ce);
2327 for (i = locate_in_src_index(ce, o);
2328 i < o->src_index->cache_nr;
2329 i++) {
2330 struct cache_entry *ce2 = o->src_index->cache[i];
2331 int len = ce_namelen(ce2);
2332 if (len < namelen ||
2333 strncmp(ce->name, ce2->name, namelen) ||
2334 ce2->name[namelen] != '/')
2335 break;
2337 * ce2->name is an entry in the subdirectory to be
2338 * removed.
2340 if (!ce_stage(ce2)) {
2341 if (verify_uptodate(ce2, o))
2342 return -1;
2343 add_entry(o, ce2, CE_REMOVE, 0);
2344 invalidate_ce_path(ce, o);
2345 mark_ce_used(ce2, o);
2347 cnt++;
2350 /* Do not lose a locally present file that is not ignored. */
2351 pathbuf = xstrfmt("%.*s/", namelen, ce->name);
2353 memset(&d, 0, sizeof(d));
2354 if (o->internal.dir)
2355 setup_standard_excludes(&d);
2356 i = read_directory(&d, o->src_index, pathbuf, namelen+1, NULL);
2357 dir_clear(&d);
2358 free(pathbuf);
2359 if (i)
2360 return add_rejected_path(o, ERROR_NOT_UPTODATE_DIR, ce->name);
2362 /* Do not lose startup_info->original_cwd */
2363 if (startup_info->original_cwd &&
2364 !strcmp(startup_info->original_cwd, ce->name))
2365 return add_rejected_path(o, ERROR_CWD_IN_THE_WAY, ce->name);
2367 return cnt;
2371 * This gets called when there was no index entry for the tree entry 'dst',
2372 * but we found a file in the working tree that 'lstat()' said was fine,
2373 * and we're on a case-insensitive filesystem.
2375 * See if we can find a case-insensitive match in the index that also
2376 * matches the stat information, and assume it's that other file!
2378 static int icase_exists(struct unpack_trees_options *o, const char *name, int len, struct stat *st)
2380 const struct cache_entry *src;
2382 src = index_file_exists(o->src_index, name, len, 1);
2383 return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
2386 enum absent_checking_type {
2387 COMPLETELY_ABSENT,
2388 ABSENT_ANY_DIRECTORY
2391 static int check_ok_to_remove(const char *name, int len, int dtype,
2392 const struct cache_entry *ce, struct stat *st,
2393 enum unpack_trees_error_types error_type,
2394 enum absent_checking_type absent_type,
2395 struct unpack_trees_options *o)
2397 const struct cache_entry *result;
2400 * It may be that the 'lstat()' succeeded even though
2401 * target 'ce' was absent, because there is an old
2402 * entry that is different only in case..
2404 * Ignore that lstat() if it matches.
2406 if (ignore_case && icase_exists(o, name, len, st))
2407 return 0;
2409 if (o->internal.dir &&
2410 is_excluded(o->internal.dir, o->src_index, name, &dtype))
2412 * ce->name is explicitly excluded, so it is Ok to
2413 * overwrite it.
2415 return 0;
2416 if (S_ISDIR(st->st_mode)) {
2418 * We are checking out path "foo" and
2419 * found "foo/." in the working tree.
2420 * This is tricky -- if we have modified
2421 * files that are in "foo/" we would lose
2422 * them.
2424 if (verify_clean_subdirectory(ce, o) < 0)
2425 return -1;
2426 return 0;
2429 /* If we only care about directories, then we can remove */
2430 if (absent_type == ABSENT_ANY_DIRECTORY)
2431 return 0;
2434 * The previous round may already have decided to
2435 * delete this path, which is in a subdirectory that
2436 * is being replaced with a blob.
2438 result = index_file_exists(&o->internal.result, name, len, 0);
2439 if (result) {
2440 if (result->ce_flags & CE_REMOVE)
2441 return 0;
2444 return add_rejected_path(o, error_type, name);
2448 * We do not want to remove or overwrite a working tree file that
2449 * is not tracked, unless it is ignored.
2451 static int verify_absent_1(const struct cache_entry *ce,
2452 enum unpack_trees_error_types error_type,
2453 enum absent_checking_type absent_type,
2454 struct unpack_trees_options *o)
2456 int len;
2457 struct stat st;
2459 if (o->index_only || !o->update)
2460 return 0;
2462 if (o->reset == UNPACK_RESET_OVERWRITE_UNTRACKED) {
2463 /* Avoid nuking startup_info->original_cwd... */
2464 if (startup_info->original_cwd &&
2465 !strcmp(startup_info->original_cwd, ce->name))
2466 return add_rejected_path(o, ERROR_CWD_IN_THE_WAY,
2467 ce->name);
2468 /* ...but nuke anything else. */
2469 return 0;
2472 len = check_leading_path(ce->name, ce_namelen(ce), 0);
2473 if (!len)
2474 return 0;
2475 else if (len > 0) {
2476 char *path;
2477 int ret;
2479 path = xmemdupz(ce->name, len);
2480 if (lstat(path, &st))
2481 ret = error_errno("cannot stat '%s'", path);
2482 else {
2483 if (submodule_from_ce(ce))
2484 ret = check_submodule_move_head(ce,
2485 oid_to_hex(&ce->oid),
2486 NULL, o);
2487 else
2488 ret = check_ok_to_remove(path, len, DT_UNKNOWN, NULL,
2489 &st, error_type,
2490 absent_type, o);
2492 free(path);
2493 return ret;
2494 } else if (lstat(ce->name, &st)) {
2495 if (errno != ENOENT)
2496 return error_errno("cannot stat '%s'", ce->name);
2497 return 0;
2498 } else {
2499 if (submodule_from_ce(ce))
2500 return check_submodule_move_head(ce, oid_to_hex(&ce->oid),
2501 NULL, o);
2503 return check_ok_to_remove(ce->name, ce_namelen(ce),
2504 ce_to_dtype(ce), ce, &st,
2505 error_type, absent_type, o);
2509 static int verify_absent(const struct cache_entry *ce,
2510 enum unpack_trees_error_types error_type,
2511 struct unpack_trees_options *o)
2513 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2514 return 0;
2515 return verify_absent_1(ce, error_type, COMPLETELY_ABSENT, o);
2518 static int verify_absent_if_directory(const struct cache_entry *ce,
2519 enum unpack_trees_error_types error_type,
2520 struct unpack_trees_options *o)
2522 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2523 return 0;
2524 return verify_absent_1(ce, error_type, ABSENT_ANY_DIRECTORY, o);
2527 static int verify_absent_sparse(const struct cache_entry *ce,
2528 enum unpack_trees_error_types error_type,
2529 struct unpack_trees_options *o)
2531 return verify_absent_1(ce, error_type, COMPLETELY_ABSENT, o);
2534 static int merged_entry(const struct cache_entry *ce,
2535 const struct cache_entry *old,
2536 struct unpack_trees_options *o)
2538 int update = CE_UPDATE;
2539 struct cache_entry *merge = dup_cache_entry(ce, &o->internal.result);
2541 if (!old) {
2543 * New index entries. In sparse checkout, the following
2544 * verify_absent() will be delayed until after
2545 * traverse_trees() finishes in unpack_trees(), then:
2547 * - CE_NEW_SKIP_WORKTREE will be computed correctly
2548 * - verify_absent() be called again, this time with
2549 * correct CE_NEW_SKIP_WORKTREE
2551 * verify_absent() call here does nothing in sparse
2552 * checkout (i.e. o->skip_sparse_checkout == 0)
2554 update |= CE_ADDED;
2555 merge->ce_flags |= CE_NEW_SKIP_WORKTREE;
2557 if (verify_absent(merge,
2558 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
2559 discard_cache_entry(merge);
2560 return -1;
2562 invalidate_ce_path(merge, o);
2564 if (submodule_from_ce(ce) && file_exists(ce->name)) {
2565 int ret = check_submodule_move_head(ce, NULL,
2566 oid_to_hex(&ce->oid),
2568 if (ret)
2569 return ret;
2572 } else if (!(old->ce_flags & CE_CONFLICTED)) {
2574 * See if we can re-use the old CE directly?
2575 * That way we get the uptodate stat info.
2577 * This also removes the UPDATE flag on a match; otherwise
2578 * we will end up overwriting local changes in the work tree.
2580 if (same(old, merge)) {
2581 copy_cache_entry(merge, old);
2582 update = 0;
2583 } else {
2584 if (verify_uptodate(old, o)) {
2585 discard_cache_entry(merge);
2586 return -1;
2588 /* Migrate old flags over */
2589 update |= old->ce_flags & (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
2590 invalidate_ce_path(old, o);
2593 if (submodule_from_ce(ce) && file_exists(ce->name)) {
2594 int ret = check_submodule_move_head(ce, oid_to_hex(&old->oid),
2595 oid_to_hex(&ce->oid),
2597 if (ret)
2598 return ret;
2600 } else {
2602 * Previously unmerged entry left as an existence
2603 * marker by read_index_unmerged();
2605 if (verify_absent_if_directory(merge,
2606 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
2607 discard_cache_entry(merge);
2608 return -1;
2611 invalidate_ce_path(old, o);
2614 if (do_add_entry(o, merge, update, CE_STAGEMASK) < 0)
2615 return -1;
2616 return 1;
2619 static int merged_sparse_dir(const struct cache_entry * const *src, int n,
2620 struct unpack_trees_options *o)
2622 struct tree_desc t[MAX_UNPACK_TREES + 1];
2623 void * tree_bufs[MAX_UNPACK_TREES + 1];
2624 struct traverse_info info;
2625 int i, ret;
2628 * Create the tree traversal information for traversing into *only* the
2629 * sparse directory.
2631 setup_traverse_info(&info, src[0]->name);
2632 info.fn = unpack_sparse_callback;
2633 info.data = o;
2634 info.show_all_errors = o->internal.show_all_errors;
2635 info.pathspec = o->pathspec;
2637 /* Get the tree descriptors of the sparse directory in each of the merging trees */
2638 for (i = 0; i < n; i++)
2639 tree_bufs[i] = fill_tree_descriptor(o->src_index->repo, &t[i],
2640 src[i] && !is_null_oid(&src[i]->oid) ? &src[i]->oid : NULL);
2642 ret = traverse_trees(o->src_index, n, t, &info);
2644 for (i = 0; i < n; i++)
2645 free(tree_bufs[i]);
2647 return ret;
2650 static int deleted_entry(const struct cache_entry *ce,
2651 const struct cache_entry *old,
2652 struct unpack_trees_options *o)
2654 /* Did it exist in the index? */
2655 if (!old) {
2656 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2657 return -1;
2658 return 0;
2659 } else if (verify_absent_if_directory(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o)) {
2660 return -1;
2663 if (!(old->ce_flags & CE_CONFLICTED) && verify_uptodate(old, o))
2664 return -1;
2665 add_entry(o, ce, CE_REMOVE, 0);
2666 invalidate_ce_path(ce, o);
2667 return 1;
2670 static int keep_entry(const struct cache_entry *ce,
2671 struct unpack_trees_options *o)
2673 add_entry(o, ce, 0, 0);
2674 if (ce_stage(ce))
2675 invalidate_ce_path(ce, o);
2676 return 1;
2679 #if DBRT_DEBUG
2680 static void show_stage_entry(FILE *o,
2681 const char *label, const struct cache_entry *ce)
2683 if (!ce)
2684 fprintf(o, "%s (missing)\n", label);
2685 else
2686 fprintf(o, "%s%06o %s %d\t%s\n",
2687 label,
2688 ce->ce_mode,
2689 oid_to_hex(&ce->oid),
2690 ce_stage(ce),
2691 ce->name);
2693 #endif
2695 int threeway_merge(const struct cache_entry * const *stages,
2696 struct unpack_trees_options *o)
2698 const struct cache_entry *index;
2699 const struct cache_entry *head;
2700 const struct cache_entry *remote = stages[o->head_idx + 1];
2701 int count;
2702 int head_match = 0;
2703 int remote_match = 0;
2705 int df_conflict_head = 0;
2706 int df_conflict_remote = 0;
2708 int any_anc_missing = 0;
2709 int no_anc_exists = 1;
2710 int i;
2712 for (i = 1; i < o->head_idx; i++) {
2713 if (!stages[i] || stages[i] == o->df_conflict_entry)
2714 any_anc_missing = 1;
2715 else
2716 no_anc_exists = 0;
2719 index = stages[0];
2720 head = stages[o->head_idx];
2722 if (head == o->df_conflict_entry) {
2723 df_conflict_head = 1;
2724 head = NULL;
2727 if (remote == o->df_conflict_entry) {
2728 df_conflict_remote = 1;
2729 remote = NULL;
2733 * First, if there's a #16 situation, note that to prevent #13
2734 * and #14.
2736 if (!same(remote, head)) {
2737 for (i = 1; i < o->head_idx; i++) {
2738 if (same(stages[i], head)) {
2739 head_match = i;
2741 if (same(stages[i], remote)) {
2742 remote_match = i;
2748 * We start with cases where the index is allowed to match
2749 * something other than the head: #14(ALT) and #2ALT, where it
2750 * is permitted to match the result instead.
2752 /* #14, #14ALT, #2ALT */
2753 if (remote && !df_conflict_head && head_match && !remote_match) {
2754 if (index && !same(index, remote) && !same(index, head)) {
2755 if (S_ISSPARSEDIR(index->ce_mode))
2756 return merged_sparse_dir(stages, 4, o);
2757 else
2758 return reject_merge(index, o);
2760 return merged_entry(remote, index, o);
2763 * If we have an entry in the index cache, then we want to
2764 * make sure that it matches head.
2766 if (index && !same(index, head)) {
2767 if (S_ISSPARSEDIR(index->ce_mode))
2768 return merged_sparse_dir(stages, 4, o);
2769 else
2770 return reject_merge(index, o);
2773 if (head) {
2774 /* #5ALT, #15 */
2775 if (same(head, remote))
2776 return merged_entry(head, index, o);
2777 /* #13, #3ALT */
2778 if (!df_conflict_remote && remote_match && !head_match)
2779 return merged_entry(head, index, o);
2782 /* #1 */
2783 if (!head && !remote && any_anc_missing)
2784 return 0;
2787 * Under the "aggressive" rule, we resolve mostly trivial
2788 * cases that we historically had git-merge-one-file resolve.
2790 if (o->aggressive) {
2791 int head_deleted = !head;
2792 int remote_deleted = !remote;
2793 const struct cache_entry *ce = NULL;
2795 if (index)
2796 ce = index;
2797 else if (head)
2798 ce = head;
2799 else if (remote)
2800 ce = remote;
2801 else {
2802 for (i = 1; i < o->head_idx; i++) {
2803 if (stages[i] && stages[i] != o->df_conflict_entry) {
2804 ce = stages[i];
2805 break;
2811 * Deleted in both.
2812 * Deleted in one and unchanged in the other.
2814 if ((head_deleted && remote_deleted) ||
2815 (head_deleted && remote && remote_match) ||
2816 (remote_deleted && head && head_match)) {
2817 if (index)
2818 return deleted_entry(index, index, o);
2819 if (ce && !head_deleted) {
2820 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2821 return -1;
2823 return 0;
2826 * Added in both, identically.
2828 if (no_anc_exists && head && remote && same(head, remote))
2829 return merged_entry(head, index, o);
2833 /* Handle "no merge" cases (see t/t1000-read-tree-m-3way.sh) */
2834 if (index) {
2836 * If we've reached the "no merge" cases and we're merging
2837 * a sparse directory, we may have an "edit/edit" conflict that
2838 * can be resolved by individually merging directory contents.
2840 if (S_ISSPARSEDIR(index->ce_mode))
2841 return merged_sparse_dir(stages, 4, o);
2844 * If we're not merging a sparse directory, ensure the index is
2845 * up-to-date to avoid files getting overwritten with conflict
2846 * resolution files
2848 if (verify_uptodate(index, o))
2849 return -1;
2852 o->internal.nontrivial_merge = 1;
2854 /* #2, #3, #4, #6, #7, #9, #10, #11. */
2855 count = 0;
2856 if (!head_match || !remote_match) {
2857 for (i = 1; i < o->head_idx; i++) {
2858 if (stages[i] && stages[i] != o->df_conflict_entry) {
2859 keep_entry(stages[i], o);
2860 count++;
2861 break;
2865 #if DBRT_DEBUG
2866 else {
2867 fprintf(stderr, "read-tree: warning #16 detected\n");
2868 show_stage_entry(stderr, "head ", stages[head_match]);
2869 show_stage_entry(stderr, "remote ", stages[remote_match]);
2871 #endif
2872 if (head) { count += keep_entry(head, o); }
2873 if (remote) { count += keep_entry(remote, o); }
2874 return count;
2878 * Two-way merge.
2880 * The rule is to "carry forward" what is in the index without losing
2881 * information across a "fast-forward", favoring a successful merge
2882 * over a merge failure when it makes sense. For details of the
2883 * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
2886 int twoway_merge(const struct cache_entry * const *src,
2887 struct unpack_trees_options *o)
2889 const struct cache_entry *current = src[0];
2890 const struct cache_entry *oldtree = src[1];
2891 const struct cache_entry *newtree = src[2];
2893 if (o->internal.merge_size != 2)
2894 return error("Cannot do a twoway merge of %d trees",
2895 o->internal.merge_size);
2897 if (oldtree == o->df_conflict_entry)
2898 oldtree = NULL;
2899 if (newtree == o->df_conflict_entry)
2900 newtree = NULL;
2902 if (current) {
2903 if (current->ce_flags & CE_CONFLICTED) {
2904 if (same(oldtree, newtree) || o->reset) {
2905 if (!newtree)
2906 return deleted_entry(current, current, o);
2907 else
2908 return merged_entry(newtree, current, o);
2910 return reject_merge(current, o);
2911 } else if ((!oldtree && !newtree) || /* 4 and 5 */
2912 (!oldtree && newtree &&
2913 same(current, newtree)) || /* 6 and 7 */
2914 (oldtree && newtree &&
2915 same(oldtree, newtree)) || /* 14 and 15 */
2916 (oldtree && newtree &&
2917 !same(oldtree, newtree) && /* 18 and 19 */
2918 same(current, newtree))) {
2919 return keep_entry(current, o);
2920 } else if (oldtree && !newtree && same(current, oldtree)) {
2921 /* 10 or 11 */
2922 return deleted_entry(oldtree, current, o);
2923 } else if (oldtree && newtree &&
2924 same(current, oldtree) && !same(current, newtree)) {
2925 /* 20 or 21 */
2926 return merged_entry(newtree, current, o);
2927 } else if (current && !oldtree && newtree &&
2928 S_ISSPARSEDIR(current->ce_mode) != S_ISSPARSEDIR(newtree->ce_mode) &&
2929 ce_stage(current) == 0) {
2931 * This case is a directory/file conflict across the sparse-index
2932 * boundary. When we are changing from one path to another via
2933 * 'git checkout', then we want to replace one entry with another
2934 * via merged_entry(). If there are staged changes, then we should
2935 * reject the merge instead.
2937 return merged_entry(newtree, current, o);
2938 } else if (S_ISSPARSEDIR(current->ce_mode)) {
2940 * The sparse directories differ, but we don't know whether that's
2941 * because of two different files in the directory being modified
2942 * (can be trivially merged) or if there is a real file conflict.
2943 * Merge the sparse directory by OID to compare file-by-file.
2945 return merged_sparse_dir(src, 3, o);
2946 } else
2947 return reject_merge(current, o);
2949 else if (newtree) {
2950 if (oldtree && !o->initial_checkout) {
2952 * deletion of the path was staged;
2954 if (same(oldtree, newtree))
2955 return 1;
2956 return reject_merge(oldtree, o);
2958 return merged_entry(newtree, current, o);
2960 return deleted_entry(oldtree, current, o);
2964 * Bind merge.
2966 * Keep the index entries at stage0, collapse stage1 but make sure
2967 * stage0 does not have anything there.
2969 int bind_merge(const struct cache_entry * const *src,
2970 struct unpack_trees_options *o)
2972 const struct cache_entry *old = src[0];
2973 const struct cache_entry *a = src[1];
2975 if (o->internal.merge_size != 1)
2976 return error("Cannot do a bind merge of %d trees",
2977 o->internal.merge_size);
2978 if (a && old)
2979 return o->quiet ? -1 :
2980 error(ERRORMSG(o, ERROR_BIND_OVERLAP),
2981 super_prefixed(a->name, o->super_prefix),
2982 super_prefixed(old->name, o->super_prefix));
2983 if (!a)
2984 return keep_entry(old, o);
2985 else
2986 return merged_entry(a, NULL, o);
2990 * One-way merge.
2992 * The rule is:
2993 * - take the stat information from stage0, take the data from stage1
2995 int oneway_merge(const struct cache_entry * const *src,
2996 struct unpack_trees_options *o)
2998 const struct cache_entry *old = src[0];
2999 const struct cache_entry *a = src[1];
3001 if (o->internal.merge_size != 1)
3002 return error("Cannot do a oneway merge of %d trees",
3003 o->internal.merge_size);
3005 if (!a || a == o->df_conflict_entry)
3006 return deleted_entry(old, old, o);
3008 if (old && same(old, a)) {
3009 int update = 0;
3010 if (o->reset && o->update && !ce_uptodate(old) && !ce_skip_worktree(old) &&
3011 !(old->ce_flags & CE_FSMONITOR_VALID)) {
3012 struct stat st;
3013 if (lstat(old->name, &st) ||
3014 ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE))
3015 update |= CE_UPDATE;
3017 if (o->update && S_ISGITLINK(old->ce_mode) &&
3018 should_update_submodules() && !verify_uptodate(old, o))
3019 update |= CE_UPDATE;
3020 add_entry(o, old, update, CE_STAGEMASK);
3021 return 0;
3023 return merged_entry(a, old, o);
3027 * Merge worktree and untracked entries in a stash entry.
3029 * Ignore all index entries. Collapse remaining trees but make sure that they
3030 * don't have any conflicting files.
3032 int stash_worktree_untracked_merge(const struct cache_entry * const *src,
3033 struct unpack_trees_options *o)
3035 const struct cache_entry *worktree = src[1];
3036 const struct cache_entry *untracked = src[2];
3038 if (o->internal.merge_size != 2)
3039 BUG("invalid merge_size: %d", o->internal.merge_size);
3041 if (worktree && untracked)
3042 return error(_("worktree and untracked commit have duplicate entries: %s"),
3043 super_prefixed(worktree->name, o->super_prefix));
3045 return merged_entry(worktree ? worktree : untracked, NULL, o);