wrapper.h: move declarations for wrapper.c functions from cache.h
[git/debian.git] / unpack-trees.c
blob84e0d2e8afe51b0dddbee0971f439f79eee9fcbf
1 #include "cache.h"
2 #include "strvec.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "dir.h"
6 #include "gettext.h"
7 #include "hex.h"
8 #include "tree.h"
9 #include "tree-walk.h"
10 #include "cache-tree.h"
11 #include "unpack-trees.h"
12 #include "progress.h"
13 #include "refs.h"
14 #include "attr.h"
15 #include "split-index.h"
16 #include "sparse-index.h"
17 #include "submodule.h"
18 #include "submodule-config.h"
19 #include "fsmonitor.h"
20 #include "object-store.h"
21 #include "promisor-remote.h"
22 #include "entry.h"
23 #include "parallel-checkout.h"
26 * Error messages expected by scripts out of plumbing commands such as
27 * read-tree. Non-scripted Porcelain is not required to use these messages
28 * and in fact are encouraged to reword them to better suit their particular
29 * situation better. See how "git checkout" and "git merge" replaces
30 * them using setup_unpack_trees_porcelain(), for example.
32 static const char *unpack_plumbing_errors[NB_UNPACK_TREES_WARNING_TYPES] = {
33 /* ERROR_WOULD_OVERWRITE */
34 "Entry '%s' would be overwritten by merge. Cannot merge.",
36 /* ERROR_NOT_UPTODATE_FILE */
37 "Entry '%s' not uptodate. Cannot merge.",
39 /* ERROR_NOT_UPTODATE_DIR */
40 "Updating '%s' would lose untracked files in it",
42 /* ERROR_CWD_IN_THE_WAY */
43 "Refusing to remove '%s' since it is the current working directory.",
45 /* ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN */
46 "Untracked working tree file '%s' would be overwritten by merge.",
48 /* ERROR_WOULD_LOSE_UNTRACKED_REMOVED */
49 "Untracked working tree file '%s' would be removed by merge.",
51 /* ERROR_BIND_OVERLAP */
52 "Entry '%s' overlaps with '%s'. Cannot bind.",
54 /* ERROR_WOULD_LOSE_SUBMODULE */
55 "Submodule '%s' cannot checkout new HEAD.",
57 /* NB_UNPACK_TREES_ERROR_TYPES; just a meta value */
58 "",
60 /* WARNING_SPARSE_NOT_UPTODATE_FILE */
61 "Path '%s' not uptodate; will not remove from working tree.",
63 /* WARNING_SPARSE_UNMERGED_FILE */
64 "Path '%s' unmerged; will not remove from working tree.",
66 /* WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN */
67 "Path '%s' already present; will not overwrite with sparse update.",
70 #define ERRORMSG(o,type) \
71 ( ((o) && (o)->internal.msgs[(type)]) \
72 ? ((o)->internal.msgs[(type)]) \
73 : (unpack_plumbing_errors[(type)]) )
75 static const char *super_prefixed(const char *path, const char *super_prefix)
78 * It is necessary and sufficient to have two static buffers
79 * here, as the return value of this function is fed to
80 * error() using the unpack_*_errors[] templates we see above.
82 static struct strbuf buf[2] = {STRBUF_INIT, STRBUF_INIT};
83 static int super_prefix_len = -1;
84 static unsigned idx = ARRAY_SIZE(buf) - 1;
86 if (super_prefix_len < 0) {
87 if (!super_prefix) {
88 super_prefix_len = 0;
89 } else {
90 int i;
91 for (i = 0; i < ARRAY_SIZE(buf); i++)
92 strbuf_addstr(&buf[i], super_prefix);
93 super_prefix_len = buf[0].len;
97 if (!super_prefix_len)
98 return path;
100 if (++idx >= ARRAY_SIZE(buf))
101 idx = 0;
103 strbuf_setlen(&buf[idx], super_prefix_len);
104 strbuf_addstr(&buf[idx], path);
106 return buf[idx].buf;
109 void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,
110 const char *cmd)
112 int i;
113 const char **msgs = opts->internal.msgs;
114 const char *msg;
116 strvec_init(&opts->internal.msgs_to_free);
118 if (!strcmp(cmd, "checkout"))
119 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
120 ? _("Your local changes to the following files would be overwritten by checkout:\n%%s"
121 "Please commit your changes or stash them before you switch branches.")
122 : _("Your local changes to the following files would be overwritten by checkout:\n%%s");
123 else if (!strcmp(cmd, "merge"))
124 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
125 ? _("Your local changes to the following files would be overwritten by merge:\n%%s"
126 "Please commit your changes or stash them before you merge.")
127 : _("Your local changes to the following files would be overwritten by merge:\n%%s");
128 else
129 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
130 ? _("Your local changes to the following files would be overwritten by %s:\n%%s"
131 "Please commit your changes or stash them before you %s.")
132 : _("Your local changes to the following files would be overwritten by %s:\n%%s");
133 msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOT_UPTODATE_FILE] =
134 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
136 msgs[ERROR_NOT_UPTODATE_DIR] =
137 _("Updating the following directories would lose untracked files in them:\n%s");
139 msgs[ERROR_CWD_IN_THE_WAY] =
140 _("Refusing to remove the current working directory:\n%s");
142 if (!strcmp(cmd, "checkout"))
143 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
144 ? _("The following untracked working tree files would be removed by checkout:\n%%s"
145 "Please move or remove them before you switch branches.")
146 : _("The following untracked working tree files would be removed by checkout:\n%%s");
147 else if (!strcmp(cmd, "merge"))
148 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
149 ? _("The following untracked working tree files would be removed by merge:\n%%s"
150 "Please move or remove them before you merge.")
151 : _("The following untracked working tree files would be removed by merge:\n%%s");
152 else
153 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
154 ? _("The following untracked working tree files would be removed by %s:\n%%s"
155 "Please move or remove them before you %s.")
156 : _("The following untracked working tree files would be removed by %s:\n%%s");
157 msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED] =
158 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
160 if (!strcmp(cmd, "checkout"))
161 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
162 ? _("The following untracked working tree files would be overwritten by checkout:\n%%s"
163 "Please move or remove them before you switch branches.")
164 : _("The following untracked working tree files would be overwritten by checkout:\n%%s");
165 else if (!strcmp(cmd, "merge"))
166 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
167 ? _("The following untracked working tree files would be overwritten by merge:\n%%s"
168 "Please move or remove them before you merge.")
169 : _("The following untracked working tree files would be overwritten by merge:\n%%s");
170 else
171 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
172 ? _("The following untracked working tree files would be overwritten by %s:\n%%s"
173 "Please move or remove them before you %s.")
174 : _("The following untracked working tree files would be overwritten by %s:\n%%s");
175 msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN] =
176 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
179 * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
180 * cannot easily display it as a list.
182 msgs[ERROR_BIND_OVERLAP] = _("Entry '%s' overlaps with '%s'. Cannot bind.");
184 msgs[ERROR_WOULD_LOSE_SUBMODULE] =
185 _("Cannot update submodule:\n%s");
187 msgs[WARNING_SPARSE_NOT_UPTODATE_FILE] =
188 _("The following paths are not up to date and were left despite sparse patterns:\n%s");
189 msgs[WARNING_SPARSE_UNMERGED_FILE] =
190 _("The following paths are unmerged and were left despite sparse patterns:\n%s");
191 msgs[WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN] =
192 _("The following paths were already present and thus not updated despite sparse patterns:\n%s");
194 opts->internal.show_all_errors = 1;
195 /* rejected paths may not have a static buffer */
196 for (i = 0; i < ARRAY_SIZE(opts->internal.unpack_rejects); i++)
197 opts->internal.unpack_rejects[i].strdup_strings = 1;
200 void clear_unpack_trees_porcelain(struct unpack_trees_options *opts)
202 strvec_clear(&opts->internal.msgs_to_free);
203 memset(opts->internal.msgs, 0, sizeof(opts->internal.msgs));
206 static int do_add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
207 unsigned int set, unsigned int clear)
209 clear |= CE_HASHED;
211 if (set & CE_REMOVE)
212 set |= CE_WT_REMOVE;
214 ce->ce_flags = (ce->ce_flags & ~clear) | set;
215 return add_index_entry(&o->internal.result, ce,
216 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
219 static void add_entry(struct unpack_trees_options *o,
220 const struct cache_entry *ce,
221 unsigned int set, unsigned int clear)
223 do_add_entry(o, dup_cache_entry(ce, &o->internal.result), set, clear);
227 * add error messages on path <path>
228 * corresponding to the type <e> with the message <msg>
229 * indicating if it should be display in porcelain or not
231 static int add_rejected_path(struct unpack_trees_options *o,
232 enum unpack_trees_error_types e,
233 const char *path)
235 if (o->quiet)
236 return -1;
238 if (!o->internal.show_all_errors)
239 return error(ERRORMSG(o, e), super_prefixed(path,
240 o->super_prefix));
243 * Otherwise, insert in a list for future display by
244 * display_(error|warning)_msgs()
246 string_list_append(&o->internal.unpack_rejects[e], path);
247 return -1;
251 * display all the error messages stored in a nice way
253 static void display_error_msgs(struct unpack_trees_options *o)
255 int e;
256 unsigned error_displayed = 0;
257 for (e = 0; e < NB_UNPACK_TREES_ERROR_TYPES; e++) {
258 struct string_list *rejects = &o->internal.unpack_rejects[e];
260 if (rejects->nr > 0) {
261 int i;
262 struct strbuf path = STRBUF_INIT;
264 error_displayed = 1;
265 for (i = 0; i < rejects->nr; i++)
266 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
267 error(ERRORMSG(o, e), super_prefixed(path.buf,
268 o->super_prefix));
269 strbuf_release(&path);
271 string_list_clear(rejects, 0);
273 if (error_displayed)
274 fprintf(stderr, _("Aborting\n"));
278 * display all the warning messages stored in a nice way
280 static void display_warning_msgs(struct unpack_trees_options *o)
282 int e;
283 unsigned warning_displayed = 0;
284 for (e = NB_UNPACK_TREES_ERROR_TYPES + 1;
285 e < NB_UNPACK_TREES_WARNING_TYPES; e++) {
286 struct string_list *rejects = &o->internal.unpack_rejects[e];
288 if (rejects->nr > 0) {
289 int i;
290 struct strbuf path = STRBUF_INIT;
292 warning_displayed = 1;
293 for (i = 0; i < rejects->nr; i++)
294 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
295 warning(ERRORMSG(o, e), super_prefixed(path.buf,
296 o->super_prefix));
297 strbuf_release(&path);
299 string_list_clear(rejects, 0);
301 if (warning_displayed)
302 fprintf(stderr, _("After fixing the above paths, you may want to run `git sparse-checkout reapply`.\n"));
304 static int check_submodule_move_head(const struct cache_entry *ce,
305 const char *old_id,
306 const char *new_id,
307 struct unpack_trees_options *o)
309 unsigned flags = SUBMODULE_MOVE_HEAD_DRY_RUN;
310 const struct submodule *sub = submodule_from_ce(ce);
312 if (!sub)
313 return 0;
315 if (o->reset)
316 flags |= SUBMODULE_MOVE_HEAD_FORCE;
318 if (submodule_move_head(ce->name, o->super_prefix, old_id, new_id,
319 flags))
320 return add_rejected_path(o, ERROR_WOULD_LOSE_SUBMODULE, ce->name);
321 return 0;
325 * Perform the loading of the repository's gitmodules file. This function is
326 * used by 'check_update()' to perform loading of the gitmodules file in two
327 * different situations:
328 * (1) before removing entries from the working tree if the gitmodules file has
329 * been marked for removal. This situation is specified by 'state' == NULL.
330 * (2) before checking out entries to the working tree if the gitmodules file
331 * has been marked for update. This situation is specified by 'state' != NULL.
333 static void load_gitmodules_file(struct index_state *index,
334 struct checkout *state)
336 int pos = index_name_pos(index, GITMODULES_FILE, strlen(GITMODULES_FILE));
338 if (pos >= 0) {
339 struct cache_entry *ce = index->cache[pos];
340 if (!state && ce->ce_flags & CE_WT_REMOVE) {
341 repo_read_gitmodules(the_repository, 0);
342 } else if (state && (ce->ce_flags & CE_UPDATE)) {
343 submodule_free(the_repository);
344 checkout_entry(ce, state, NULL, NULL);
345 repo_read_gitmodules(the_repository, 0);
350 static struct progress *get_progress(struct unpack_trees_options *o,
351 struct index_state *index)
353 unsigned cnt = 0, total = 0;
355 if (!o->update || !o->verbose_update)
356 return NULL;
358 for (; cnt < index->cache_nr; cnt++) {
359 const struct cache_entry *ce = index->cache[cnt];
360 if (ce->ce_flags & (CE_UPDATE | CE_WT_REMOVE))
361 total++;
364 return start_delayed_progress(_("Updating files"), total);
367 static void setup_collided_checkout_detection(struct checkout *state,
368 struct index_state *index)
370 int i;
372 state->clone = 1;
373 for (i = 0; i < index->cache_nr; i++)
374 index->cache[i]->ce_flags &= ~CE_MATCHED;
377 static void report_collided_checkout(struct index_state *index)
379 struct string_list list = STRING_LIST_INIT_NODUP;
380 int i;
382 for (i = 0; i < index->cache_nr; i++) {
383 struct cache_entry *ce = index->cache[i];
385 if (!(ce->ce_flags & CE_MATCHED))
386 continue;
388 string_list_append(&list, ce->name);
389 ce->ce_flags &= ~CE_MATCHED;
392 list.cmp = fspathcmp;
393 string_list_sort(&list);
395 if (list.nr) {
396 warning(_("the following paths have collided (e.g. case-sensitive paths\n"
397 "on a case-insensitive filesystem) and only one from the same\n"
398 "colliding group is in the working tree:\n"));
400 for (i = 0; i < list.nr; i++)
401 fprintf(stderr, " '%s'\n", list.items[i].string);
404 string_list_clear(&list, 0);
407 static int must_checkout(const struct cache_entry *ce)
409 return ce->ce_flags & CE_UPDATE;
412 static int check_updates(struct unpack_trees_options *o,
413 struct index_state *index)
415 unsigned cnt = 0;
416 int errs = 0;
417 struct progress *progress;
418 struct checkout state = CHECKOUT_INIT;
419 int i, pc_workers, pc_threshold;
421 trace_performance_enter();
422 state.super_prefix = o->super_prefix;
423 state.force = 1;
424 state.quiet = 1;
425 state.refresh_cache = 1;
426 state.istate = index;
427 clone_checkout_metadata(&state.meta, &o->meta, NULL);
429 if (!o->update || o->dry_run) {
430 remove_marked_cache_entries(index, 0);
431 trace_performance_leave("check_updates");
432 return 0;
435 if (o->clone)
436 setup_collided_checkout_detection(&state, index);
438 progress = get_progress(o, index);
440 /* Start with clean cache to avoid using any possibly outdated info. */
441 invalidate_lstat_cache();
443 git_attr_set_direction(GIT_ATTR_CHECKOUT);
445 if (should_update_submodules())
446 load_gitmodules_file(index, NULL);
448 for (i = 0; i < index->cache_nr; i++) {
449 const struct cache_entry *ce = index->cache[i];
451 if (ce->ce_flags & CE_WT_REMOVE) {
452 display_progress(progress, ++cnt);
453 unlink_entry(ce, o->super_prefix);
457 remove_marked_cache_entries(index, 0);
458 remove_scheduled_dirs();
460 if (should_update_submodules())
461 load_gitmodules_file(index, &state);
463 if (has_promisor_remote())
465 * Prefetch the objects that are to be checked out in the loop
466 * below.
468 prefetch_cache_entries(index, must_checkout);
470 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
472 enable_delayed_checkout(&state);
473 if (pc_workers > 1)
474 init_parallel_checkout();
475 for (i = 0; i < index->cache_nr; i++) {
476 struct cache_entry *ce = index->cache[i];
478 if (must_checkout(ce)) {
479 size_t last_pc_queue_size = pc_queue_size();
481 if (ce->ce_flags & CE_WT_REMOVE)
482 BUG("both update and delete flags are set on %s",
483 ce->name);
484 ce->ce_flags &= ~CE_UPDATE;
485 errs |= checkout_entry(ce, &state, NULL, NULL);
487 if (last_pc_queue_size == pc_queue_size())
488 display_progress(progress, ++cnt);
491 if (pc_workers > 1)
492 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
493 progress, &cnt);
494 stop_progress(&progress);
495 errs |= finish_delayed_checkout(&state, o->verbose_update);
496 git_attr_set_direction(GIT_ATTR_CHECKIN);
498 if (o->clone)
499 report_collided_checkout(index);
501 trace_performance_leave("check_updates");
502 return errs != 0;
505 static int verify_uptodate_sparse(const struct cache_entry *ce,
506 struct unpack_trees_options *o);
507 static int verify_absent_sparse(const struct cache_entry *ce,
508 enum unpack_trees_error_types,
509 struct unpack_trees_options *o);
511 static int apply_sparse_checkout(struct index_state *istate,
512 struct cache_entry *ce,
513 struct unpack_trees_options *o)
515 int was_skip_worktree = ce_skip_worktree(ce);
517 if (ce->ce_flags & CE_NEW_SKIP_WORKTREE)
518 ce->ce_flags |= CE_SKIP_WORKTREE;
519 else
520 ce->ce_flags &= ~CE_SKIP_WORKTREE;
521 if (was_skip_worktree != ce_skip_worktree(ce)) {
522 ce->ce_flags |= CE_UPDATE_IN_BASE;
523 mark_fsmonitor_invalid(istate, ce);
524 istate->cache_changed |= CE_ENTRY_CHANGED;
528 * if (!was_skip_worktree && !ce_skip_worktree()) {
529 * This is perfectly normal. Move on;
534 * Merge strategies may set CE_UPDATE|CE_REMOVE outside checkout
535 * area as a result of ce_skip_worktree() shortcuts in
536 * verify_absent() and verify_uptodate().
537 * Make sure they don't modify worktree if they are already
538 * outside checkout area
540 if (was_skip_worktree && ce_skip_worktree(ce)) {
541 ce->ce_flags &= ~CE_UPDATE;
544 * By default, when CE_REMOVE is on, CE_WT_REMOVE is also
545 * on to get that file removed from both index and worktree.
546 * If that file is already outside worktree area, don't
547 * bother remove it.
549 if (ce->ce_flags & CE_REMOVE)
550 ce->ce_flags &= ~CE_WT_REMOVE;
553 if (!was_skip_worktree && ce_skip_worktree(ce)) {
555 * If CE_UPDATE is set, verify_uptodate() must be called already
556 * also stat info may have lost after merged_entry() so calling
557 * verify_uptodate() again may fail
559 if (!(ce->ce_flags & CE_UPDATE) &&
560 verify_uptodate_sparse(ce, o)) {
561 ce->ce_flags &= ~CE_SKIP_WORKTREE;
562 return -1;
564 ce->ce_flags |= CE_WT_REMOVE;
565 ce->ce_flags &= ~CE_UPDATE;
567 if (was_skip_worktree && !ce_skip_worktree(ce)) {
568 if (verify_absent_sparse(ce, WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN, o))
569 return -1;
570 ce->ce_flags |= CE_UPDATE;
572 return 0;
575 static int warn_conflicted_path(struct index_state *istate,
576 int i,
577 struct unpack_trees_options *o)
579 char *conflicting_path = istate->cache[i]->name;
580 int count = 0;
582 add_rejected_path(o, WARNING_SPARSE_UNMERGED_FILE, conflicting_path);
584 /* Find out how many higher stage entries are at same path */
585 while ((++count) + i < istate->cache_nr &&
586 !strcmp(conflicting_path, istate->cache[count + i]->name))
587 ; /* do nothing */
589 return count;
592 static inline int call_unpack_fn(const struct cache_entry * const *src,
593 struct unpack_trees_options *o)
595 int ret = o->fn(src, o);
596 if (ret > 0)
597 ret = 0;
598 return ret;
601 static void mark_ce_used(struct cache_entry *ce, struct unpack_trees_options *o)
603 ce->ce_flags |= CE_UNPACKED;
605 if (o->internal.cache_bottom < o->src_index->cache_nr &&
606 o->src_index->cache[o->internal.cache_bottom] == ce) {
607 int bottom = o->internal.cache_bottom;
609 while (bottom < o->src_index->cache_nr &&
610 o->src_index->cache[bottom]->ce_flags & CE_UNPACKED)
611 bottom++;
612 o->internal.cache_bottom = bottom;
616 static void mark_all_ce_unused(struct index_state *index)
618 int i;
619 for (i = 0; i < index->cache_nr; i++)
620 index->cache[i]->ce_flags &= ~(CE_UNPACKED | CE_ADDED | CE_NEW_SKIP_WORKTREE);
623 static int locate_in_src_index(const struct cache_entry *ce,
624 struct unpack_trees_options *o)
626 struct index_state *index = o->src_index;
627 int len = ce_namelen(ce);
628 int pos = index_name_pos(index, ce->name, len);
629 if (pos < 0)
630 pos = -1 - pos;
631 return pos;
635 * We call unpack_index_entry() with an unmerged cache entry
636 * only in diff-index, and it wants a single callback. Skip
637 * the other unmerged entry with the same name.
639 static void mark_ce_used_same_name(struct cache_entry *ce,
640 struct unpack_trees_options *o)
642 struct index_state *index = o->src_index;
643 int len = ce_namelen(ce);
644 int pos;
646 for (pos = locate_in_src_index(ce, o); pos < index->cache_nr; pos++) {
647 struct cache_entry *next = index->cache[pos];
648 if (len != ce_namelen(next) ||
649 memcmp(ce->name, next->name, len))
650 break;
651 mark_ce_used(next, o);
655 static struct cache_entry *next_cache_entry(struct unpack_trees_options *o)
657 const struct index_state *index = o->src_index;
658 int pos = o->internal.cache_bottom;
660 while (pos < index->cache_nr) {
661 struct cache_entry *ce = index->cache[pos];
662 if (!(ce->ce_flags & CE_UNPACKED))
663 return ce;
664 pos++;
666 return NULL;
669 static void add_same_unmerged(const struct cache_entry *ce,
670 struct unpack_trees_options *o)
672 struct index_state *index = o->src_index;
673 int len = ce_namelen(ce);
674 int pos = index_name_pos(index, ce->name, len);
676 if (0 <= pos)
677 die("programming error in a caller of mark_ce_used_same_name");
678 for (pos = -pos - 1; pos < index->cache_nr; pos++) {
679 struct cache_entry *next = index->cache[pos];
680 if (len != ce_namelen(next) ||
681 memcmp(ce->name, next->name, len))
682 break;
683 add_entry(o, next, 0, 0);
684 mark_ce_used(next, o);
688 static int unpack_index_entry(struct cache_entry *ce,
689 struct unpack_trees_options *o)
691 const struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
692 int ret;
694 src[0] = ce;
696 mark_ce_used(ce, o);
697 if (ce_stage(ce)) {
698 if (o->skip_unmerged) {
699 add_entry(o, ce, 0, 0);
700 return 0;
703 ret = call_unpack_fn(src, o);
704 if (ce_stage(ce))
705 mark_ce_used_same_name(ce, o);
706 return ret;
709 static int find_cache_pos(struct traverse_info *, const char *p, size_t len);
711 static void restore_cache_bottom(struct traverse_info *info, int bottom)
713 struct unpack_trees_options *o = info->data;
715 if (o->diff_index_cached)
716 return;
717 o->internal.cache_bottom = bottom;
720 static int switch_cache_bottom(struct traverse_info *info)
722 struct unpack_trees_options *o = info->data;
723 int ret, pos;
725 if (o->diff_index_cached)
726 return 0;
727 ret = o->internal.cache_bottom;
728 pos = find_cache_pos(info->prev, info->name, info->namelen);
730 if (pos < -1)
731 o->internal.cache_bottom = -2 - pos;
732 else if (pos < 0)
733 o->internal.cache_bottom = o->src_index->cache_nr;
734 return ret;
737 static inline int are_same_oid(struct name_entry *name_j, struct name_entry *name_k)
739 return !is_null_oid(&name_j->oid) && !is_null_oid(&name_k->oid) && oideq(&name_j->oid, &name_k->oid);
742 static int all_trees_same_as_cache_tree(int n, unsigned long dirmask,
743 struct name_entry *names,
744 struct traverse_info *info)
746 struct unpack_trees_options *o = info->data;
747 int i;
749 if (!o->merge || dirmask != ((1 << n) - 1))
750 return 0;
752 for (i = 1; i < n; i++)
753 if (!are_same_oid(names, names + i))
754 return 0;
756 return cache_tree_matches_traversal(o->src_index->cache_tree, names, info);
759 static int index_pos_by_traverse_info(struct name_entry *names,
760 struct traverse_info *info)
762 struct unpack_trees_options *o = info->data;
763 struct strbuf name = STRBUF_INIT;
764 int pos;
766 strbuf_make_traverse_path(&name, info, names->path, names->pathlen);
767 strbuf_addch(&name, '/');
768 pos = index_name_pos(o->src_index, name.buf, name.len);
769 if (pos >= 0) {
770 if (!o->src_index->sparse_index ||
771 !(o->src_index->cache[pos]->ce_flags & CE_SKIP_WORKTREE))
772 BUG("This is a directory and should not exist in index");
773 } else {
774 pos = -pos - 1;
776 if (pos >= o->src_index->cache_nr ||
777 !starts_with(o->src_index->cache[pos]->name, name.buf) ||
778 (pos > 0 && starts_with(o->src_index->cache[pos-1]->name, name.buf)))
779 BUG("pos %d doesn't point to the first entry of %s in index",
780 pos, name.buf);
781 strbuf_release(&name);
782 return pos;
786 * Fast path if we detect that all trees are the same as cache-tree at this
787 * path. We'll walk these trees in an iterative loop using cache-tree/index
788 * instead of ODB since we already know what these trees contain.
790 static int traverse_by_cache_tree(int pos, int nr_entries, int nr_names,
791 struct traverse_info *info)
793 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
794 struct unpack_trees_options *o = info->data;
795 struct cache_entry *tree_ce = NULL;
796 int ce_len = 0;
797 int i, d;
799 if (!o->merge)
800 BUG("We need cache-tree to do this optimization");
803 * Do what unpack_callback() and unpack_single_entry() normally
804 * do. But we walk all paths in an iterative loop instead.
806 * D/F conflicts and higher stage entries are not a concern
807 * because cache-tree would be invalidated and we would never
808 * get here in the first place.
810 for (i = 0; i < nr_entries; i++) {
811 int new_ce_len, len, rc;
813 src[0] = o->src_index->cache[pos + i];
815 len = ce_namelen(src[0]);
816 new_ce_len = cache_entry_size(len);
818 if (new_ce_len > ce_len) {
819 new_ce_len <<= 1;
820 tree_ce = xrealloc(tree_ce, new_ce_len);
821 memset(tree_ce, 0, new_ce_len);
822 ce_len = new_ce_len;
824 tree_ce->ce_flags = create_ce_flags(0);
826 for (d = 1; d <= nr_names; d++)
827 src[d] = tree_ce;
830 tree_ce->ce_mode = src[0]->ce_mode;
831 tree_ce->ce_namelen = len;
832 oidcpy(&tree_ce->oid, &src[0]->oid);
833 memcpy(tree_ce->name, src[0]->name, len + 1);
835 rc = call_unpack_fn((const struct cache_entry * const *)src, o);
836 if (rc < 0) {
837 free(tree_ce);
838 return rc;
841 mark_ce_used(src[0], o);
843 free(tree_ce);
844 if (o->internal.debug_unpack)
845 printf("Unpacked %d entries from %s to %s using cache-tree\n",
846 nr_entries,
847 o->src_index->cache[pos]->name,
848 o->src_index->cache[pos + nr_entries - 1]->name);
849 return 0;
852 static int traverse_trees_recursive(int n, unsigned long dirmask,
853 unsigned long df_conflicts,
854 struct name_entry *names,
855 struct traverse_info *info)
857 struct unpack_trees_options *o = info->data;
858 int i, ret, bottom;
859 int nr_buf = 0;
860 struct tree_desc t[MAX_UNPACK_TREES];
861 void *buf[MAX_UNPACK_TREES];
862 struct traverse_info newinfo;
863 struct name_entry *p;
864 int nr_entries;
866 nr_entries = all_trees_same_as_cache_tree(n, dirmask, names, info);
867 if (nr_entries > 0) {
868 int pos = index_pos_by_traverse_info(names, info);
870 if (!o->merge || df_conflicts)
871 BUG("Wrong condition to get here buddy");
874 * All entries up to 'pos' must have been processed
875 * (i.e. marked CE_UNPACKED) at this point. But to be safe,
876 * save and restore cache_bottom anyway to not miss
877 * unprocessed entries before 'pos'.
879 bottom = o->internal.cache_bottom;
880 ret = traverse_by_cache_tree(pos, nr_entries, n, info);
881 o->internal.cache_bottom = bottom;
882 return ret;
885 p = names;
886 while (!p->mode)
887 p++;
889 newinfo = *info;
890 newinfo.prev = info;
891 newinfo.pathspec = info->pathspec;
892 newinfo.name = p->path;
893 newinfo.namelen = p->pathlen;
894 newinfo.mode = p->mode;
895 newinfo.pathlen = st_add3(newinfo.pathlen, tree_entry_len(p), 1);
896 newinfo.df_conflicts |= df_conflicts;
899 * Fetch the tree from the ODB for each peer directory in the
900 * n commits.
902 * For 2- and 3-way traversals, we try to avoid hitting the
903 * ODB twice for the same OID. This should yield a nice speed
904 * up in checkouts and merges when the commits are similar.
906 * We don't bother doing the full O(n^2) search for larger n,
907 * because wider traversals don't happen that often and we
908 * avoid the search setup.
910 * When 2 peer OIDs are the same, we just copy the tree
911 * descriptor data. This implicitly borrows the buffer
912 * data from the earlier cell.
914 for (i = 0; i < n; i++, dirmask >>= 1) {
915 if (i > 0 && are_same_oid(&names[i], &names[i - 1]))
916 t[i] = t[i - 1];
917 else if (i > 1 && are_same_oid(&names[i], &names[i - 2]))
918 t[i] = t[i - 2];
919 else {
920 const struct object_id *oid = NULL;
921 if (dirmask & 1)
922 oid = &names[i].oid;
923 buf[nr_buf++] = fill_tree_descriptor(the_repository, t + i, oid);
927 bottom = switch_cache_bottom(&newinfo);
928 ret = traverse_trees(o->src_index, n, t, &newinfo);
929 restore_cache_bottom(&newinfo, bottom);
931 for (i = 0; i < nr_buf; i++)
932 free(buf[i]);
934 return ret;
938 * Compare the traverse-path to the cache entry without actually
939 * having to generate the textual representation of the traverse
940 * path.
942 * NOTE! This *only* compares up to the size of the traverse path
943 * itself - the caller needs to do the final check for the cache
944 * entry having more data at the end!
946 static int do_compare_entry_piecewise(const struct cache_entry *ce,
947 const struct traverse_info *info,
948 const char *name, size_t namelen,
949 unsigned mode)
951 int pathlen, ce_len;
952 const char *ce_name;
954 if (info->prev) {
955 int cmp = do_compare_entry_piecewise(ce, info->prev,
956 info->name, info->namelen,
957 info->mode);
958 if (cmp)
959 return cmp;
961 pathlen = info->pathlen;
962 ce_len = ce_namelen(ce);
964 /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
965 if (ce_len < pathlen)
966 return -1;
968 ce_len -= pathlen;
969 ce_name = ce->name + pathlen;
971 return df_name_compare(ce_name, ce_len, S_IFREG, name, namelen, mode);
974 static int do_compare_entry(const struct cache_entry *ce,
975 const struct traverse_info *info,
976 const char *name, size_t namelen,
977 unsigned mode)
979 int pathlen, ce_len;
980 const char *ce_name;
981 int cmp;
982 unsigned ce_mode;
985 * If we have not precomputed the traverse path, it is quicker
986 * to avoid doing so. But if we have precomputed it,
987 * it is quicker to use the precomputed version.
989 if (!info->traverse_path)
990 return do_compare_entry_piecewise(ce, info, name, namelen, mode);
992 cmp = strncmp(ce->name, info->traverse_path, info->pathlen);
993 if (cmp)
994 return cmp;
996 pathlen = info->pathlen;
997 ce_len = ce_namelen(ce);
999 if (ce_len < pathlen)
1000 return -1;
1002 ce_len -= pathlen;
1003 ce_name = ce->name + pathlen;
1005 ce_mode = S_ISSPARSEDIR(ce->ce_mode) ? S_IFDIR : S_IFREG;
1006 return df_name_compare(ce_name, ce_len, ce_mode, name, namelen, mode);
1009 static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
1011 int cmp = do_compare_entry(ce, info, n->path, n->pathlen, n->mode);
1012 if (cmp)
1013 return cmp;
1016 * At this point, we know that we have a prefix match. If ce
1017 * is a sparse directory, then allow an exact match. This only
1018 * works when the input name is a directory, since ce->name
1019 * ends in a directory separator.
1021 if (S_ISSPARSEDIR(ce->ce_mode) &&
1022 ce->ce_namelen == traverse_path_len(info, tree_entry_len(n)) + 1)
1023 return 0;
1026 * Even if the beginning compared identically, the ce should
1027 * compare as bigger than a directory leading up to it!
1029 return ce_namelen(ce) > traverse_path_len(info, tree_entry_len(n));
1032 static int ce_in_traverse_path(const struct cache_entry *ce,
1033 const struct traverse_info *info)
1035 if (!info->prev)
1036 return 1;
1037 if (do_compare_entry(ce, info->prev,
1038 info->name, info->namelen, info->mode))
1039 return 0;
1041 * If ce (blob) is the same name as the path (which is a tree
1042 * we will be descending into), it won't be inside it.
1044 return (info->pathlen < ce_namelen(ce));
1047 static struct cache_entry *create_ce_entry(const struct traverse_info *info,
1048 const struct name_entry *n,
1049 int stage,
1050 struct index_state *istate,
1051 int is_transient,
1052 int is_sparse_directory)
1054 size_t len = traverse_path_len(info, tree_entry_len(n));
1055 size_t alloc_len = is_sparse_directory ? len + 1 : len;
1056 struct cache_entry *ce =
1057 is_transient ?
1058 make_empty_transient_cache_entry(alloc_len, NULL) :
1059 make_empty_cache_entry(istate, alloc_len);
1061 ce->ce_mode = create_ce_mode(n->mode);
1062 ce->ce_flags = create_ce_flags(stage);
1063 ce->ce_namelen = len;
1064 oidcpy(&ce->oid, &n->oid);
1065 /* len+1 because the cache_entry allocates space for NUL */
1066 make_traverse_path(ce->name, len + 1, info, n->path, n->pathlen);
1068 if (is_sparse_directory) {
1069 ce->name[len] = '/';
1070 ce->name[len + 1] = '\0';
1071 ce->ce_namelen++;
1072 ce->ce_flags |= CE_SKIP_WORKTREE;
1075 return ce;
1079 * Determine whether the path specified by 'p' should be unpacked as a new
1080 * sparse directory in a sparse index. A new sparse directory 'A/':
1081 * - must be outside the sparse cone.
1082 * - must not already be in the index (i.e., no index entry with name 'A/'
1083 * exists).
1084 * - must not have any child entries in the index (i.e., no index entry
1085 * 'A/<something>' exists).
1086 * If 'p' meets the above requirements, return 1; otherwise, return 0.
1088 static int entry_is_new_sparse_dir(const struct traverse_info *info,
1089 const struct name_entry *p)
1091 int res, pos;
1092 struct strbuf dirpath = STRBUF_INIT;
1093 struct unpack_trees_options *o = info->data;
1095 if (!S_ISDIR(p->mode))
1096 return 0;
1099 * If the path is inside the sparse cone, it can't be a sparse directory.
1101 strbuf_add(&dirpath, info->traverse_path, info->pathlen);
1102 strbuf_add(&dirpath, p->path, p->pathlen);
1103 strbuf_addch(&dirpath, '/');
1104 if (path_in_cone_mode_sparse_checkout(dirpath.buf, o->src_index)) {
1105 res = 0;
1106 goto cleanup;
1109 pos = index_name_pos_sparse(o->src_index, dirpath.buf, dirpath.len);
1110 if (pos >= 0) {
1111 /* Path is already in the index, not a new sparse dir */
1112 res = 0;
1113 goto cleanup;
1116 /* Where would this sparse dir be inserted into the index? */
1117 pos = -pos - 1;
1118 if (pos >= o->src_index->cache_nr) {
1120 * Sparse dir would be inserted at the end of the index, so we
1121 * know it has no child entries.
1123 res = 1;
1124 goto cleanup;
1128 * If the dir has child entries in the index, the first would be at the
1129 * position the sparse directory would be inserted. If the entry at this
1130 * position is inside the dir, not a new sparse dir.
1132 res = strncmp(o->src_index->cache[pos]->name, dirpath.buf, dirpath.len);
1134 cleanup:
1135 strbuf_release(&dirpath);
1136 return res;
1140 * Note that traverse_by_cache_tree() duplicates some logic in this function
1141 * without actually calling it. If you change the logic here you may need to
1142 * check and change there as well.
1144 static int unpack_single_entry(int n, unsigned long mask,
1145 unsigned long dirmask,
1146 struct cache_entry **src,
1147 const struct name_entry *names,
1148 const struct traverse_info *info,
1149 int *is_new_sparse_dir)
1151 int i;
1152 struct unpack_trees_options *o = info->data;
1153 unsigned long conflicts = info->df_conflicts | dirmask;
1154 const struct name_entry *p = names;
1156 *is_new_sparse_dir = 0;
1157 if (mask == dirmask && !src[0]) {
1159 * If we're not in a sparse index, we can't unpack a directory
1160 * without recursing into it, so we return.
1162 if (!o->src_index->sparse_index)
1163 return 0;
1165 /* Find first entry with a real name (we could use "mask" too) */
1166 while (!p->mode)
1167 p++;
1170 * If the directory is completely missing from the index but
1171 * would otherwise be a sparse directory, we should unpack it.
1172 * If not, we'll return and continue recursively traversing the
1173 * tree.
1175 *is_new_sparse_dir = entry_is_new_sparse_dir(info, p);
1176 if (!*is_new_sparse_dir)
1177 return 0;
1181 * When we are unpacking a sparse directory, then this isn't necessarily
1182 * a directory-file conflict.
1184 if (mask == dirmask &&
1185 (*is_new_sparse_dir || (src[0] && S_ISSPARSEDIR(src[0]->ce_mode))))
1186 conflicts = 0;
1189 * Ok, we've filled in up to any potential index entry in src[0],
1190 * now do the rest.
1192 for (i = 0; i < n; i++) {
1193 int stage;
1194 unsigned int bit = 1ul << i;
1195 if (conflicts & bit) {
1196 src[i + o->merge] = o->df_conflict_entry;
1197 continue;
1199 if (!(mask & bit))
1200 continue;
1201 if (!o->merge)
1202 stage = 0;
1203 else if (i + 1 < o->head_idx)
1204 stage = 1;
1205 else if (i + 1 > o->head_idx)
1206 stage = 3;
1207 else
1208 stage = 2;
1211 * If the merge bit is set, then the cache entries are
1212 * discarded in the following block. In this case,
1213 * construct "transient" cache_entries, as they are
1214 * not stored in the index. otherwise construct the
1215 * cache entry from the index aware logic.
1217 src[i + o->merge] = create_ce_entry(info, names + i, stage,
1218 &o->internal.result,
1219 o->merge, bit & dirmask);
1222 if (o->merge) {
1223 int rc = call_unpack_fn((const struct cache_entry * const *)src,
1225 for (i = 0; i < n; i++) {
1226 struct cache_entry *ce = src[i + o->merge];
1227 if (ce != o->df_conflict_entry)
1228 discard_cache_entry(ce);
1230 return rc;
1233 for (i = 0; i < n; i++)
1234 if (src[i] && src[i] != o->df_conflict_entry)
1235 if (do_add_entry(o, src[i], 0, 0))
1236 return -1;
1238 return 0;
1241 static int unpack_failed(struct unpack_trees_options *o, const char *message)
1243 discard_index(&o->internal.result);
1244 if (!o->quiet && !o->exiting_early) {
1245 if (message)
1246 return error("%s", message);
1247 return -1;
1249 return -1;
1253 * The tree traversal is looking at name p. If we have a matching entry,
1254 * return it. If name p is a directory in the index, do not return
1255 * anything, as we will want to match it when the traversal descends into
1256 * the directory.
1258 static int find_cache_pos(struct traverse_info *info,
1259 const char *p, size_t p_len)
1261 int pos;
1262 struct unpack_trees_options *o = info->data;
1263 struct index_state *index = o->src_index;
1264 int pfxlen = info->pathlen;
1266 for (pos = o->internal.cache_bottom; pos < index->cache_nr; pos++) {
1267 const struct cache_entry *ce = index->cache[pos];
1268 const char *ce_name, *ce_slash;
1269 int cmp, ce_len;
1271 if (ce->ce_flags & CE_UNPACKED) {
1273 * cache_bottom entry is already unpacked, so
1274 * we can never match it; don't check it
1275 * again.
1277 if (pos == o->internal.cache_bottom)
1278 ++o->internal.cache_bottom;
1279 continue;
1281 if (!ce_in_traverse_path(ce, info)) {
1283 * Check if we can skip future cache checks
1284 * (because we're already past all possible
1285 * entries in the traverse path).
1287 if (info->traverse_path) {
1288 if (strncmp(ce->name, info->traverse_path,
1289 info->pathlen) > 0)
1290 break;
1292 continue;
1294 ce_name = ce->name + pfxlen;
1295 ce_slash = strchr(ce_name, '/');
1296 if (ce_slash)
1297 ce_len = ce_slash - ce_name;
1298 else
1299 ce_len = ce_namelen(ce) - pfxlen;
1300 cmp = name_compare(p, p_len, ce_name, ce_len);
1302 * Exact match; if we have a directory we need to
1303 * delay returning it.
1305 if (!cmp)
1306 return ce_slash ? -2 - pos : pos;
1307 if (0 < cmp)
1308 continue; /* keep looking */
1310 * ce_name sorts after p->path; could it be that we
1311 * have files under p->path directory in the index?
1312 * E.g. ce_name == "t-i", and p->path == "t"; we may
1313 * have "t/a" in the index.
1315 if (p_len < ce_len && !memcmp(ce_name, p, p_len) &&
1316 ce_name[p_len] < '/')
1317 continue; /* keep looking */
1318 break;
1320 return -1;
1324 * Given a sparse directory entry 'ce', compare ce->name to
1325 * info->traverse_path + p->path + '/' if info->traverse_path
1326 * is non-empty.
1328 * Compare ce->name to p->path + '/' otherwise. Note that
1329 * ce->name must end in a trailing '/' because it is a sparse
1330 * directory entry.
1332 static int sparse_dir_matches_path(const struct cache_entry *ce,
1333 struct traverse_info *info,
1334 const struct name_entry *p)
1336 assert(S_ISSPARSEDIR(ce->ce_mode));
1337 assert(ce->name[ce->ce_namelen - 1] == '/');
1339 if (info->pathlen)
1340 return ce->ce_namelen == info->pathlen + p->pathlen + 1 &&
1341 ce->name[info->pathlen - 1] == '/' &&
1342 !strncmp(ce->name, info->traverse_path, info->pathlen) &&
1343 !strncmp(ce->name + info->pathlen, p->path, p->pathlen);
1344 return ce->ce_namelen == p->pathlen + 1 &&
1345 !strncmp(ce->name, p->path, p->pathlen);
1348 static struct cache_entry *find_cache_entry(struct traverse_info *info,
1349 const struct name_entry *p)
1351 const char *path;
1352 int pos = find_cache_pos(info, p->path, p->pathlen);
1353 struct unpack_trees_options *o = info->data;
1355 if (0 <= pos)
1356 return o->src_index->cache[pos];
1359 * Check for a sparse-directory entry named "path/".
1360 * Due to the input p->path not having a trailing
1361 * slash, the negative 'pos' value overshoots the
1362 * expected position, hence "-2" instead of "-1".
1364 pos = -pos - 2;
1366 if (pos < 0 || pos >= o->src_index->cache_nr)
1367 return NULL;
1370 * Due to lexicographic sorting and sparse directory
1371 * entries ending with a trailing slash, our path as a
1372 * sparse directory (e.g "subdir/") and our path as a
1373 * file (e.g. "subdir") might be separated by other
1374 * paths (e.g. "subdir-").
1376 while (pos >= 0) {
1377 struct cache_entry *ce = o->src_index->cache[pos];
1379 if (!skip_prefix(ce->name, info->traverse_path, &path) ||
1380 strncmp(path, p->path, p->pathlen) ||
1381 path[p->pathlen] != '/')
1382 return NULL;
1384 if (S_ISSPARSEDIR(ce->ce_mode) &&
1385 sparse_dir_matches_path(ce, info, p))
1386 return ce;
1388 pos--;
1391 return NULL;
1394 static void debug_path(struct traverse_info *info)
1396 if (info->prev) {
1397 debug_path(info->prev);
1398 if (*info->prev->name)
1399 putchar('/');
1401 printf("%s", info->name);
1404 static void debug_name_entry(int i, struct name_entry *n)
1406 printf("ent#%d %06o %s\n", i,
1407 n->path ? n->mode : 0,
1408 n->path ? n->path : "(missing)");
1411 static void debug_unpack_callback(int n,
1412 unsigned long mask,
1413 unsigned long dirmask,
1414 struct name_entry *names,
1415 struct traverse_info *info)
1417 int i;
1418 printf("* unpack mask %lu, dirmask %lu, cnt %d ",
1419 mask, dirmask, n);
1420 debug_path(info);
1421 putchar('\n');
1422 for (i = 0; i < n; i++)
1423 debug_name_entry(i, names + i);
1427 * Returns true if and only if the given cache_entry is a
1428 * sparse-directory entry that matches the given name_entry
1429 * from the tree walk at the given traverse_info.
1431 static int is_sparse_directory_entry(struct cache_entry *ce,
1432 const struct name_entry *name,
1433 struct traverse_info *info)
1435 if (!ce || !name || !S_ISSPARSEDIR(ce->ce_mode))
1436 return 0;
1438 return sparse_dir_matches_path(ce, info, name);
1441 static int unpack_sparse_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1443 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1444 struct unpack_trees_options *o = info->data;
1445 int ret, is_new_sparse_dir;
1447 assert(o->merge);
1450 * Unlike in 'unpack_callback', where src[0] is derived from the index when
1451 * merging, src[0] is a transient cache entry derived from the first tree
1452 * provided. Create the temporary entry as if it came from a non-sparse index.
1454 if (!is_null_oid(&names[0].oid)) {
1455 src[0] = create_ce_entry(info, &names[0], 0,
1456 &o->internal.result, 1,
1457 dirmask & (1ul << 0));
1458 src[0]->ce_flags |= (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1462 * 'unpack_single_entry' assumes that src[0] is derived directly from
1463 * the index, rather than from an entry in 'names'. This is *not* true when
1464 * merging a sparse directory, in which case names[0] is the "index" source
1465 * entry. To match the expectations of 'unpack_single_entry', shift past the
1466 * "index" tree (i.e., names[0]) and adjust 'names', 'n', 'mask', and
1467 * 'dirmask' accordingly.
1469 ret = unpack_single_entry(n - 1, mask >> 1, dirmask >> 1, src, names + 1, info, &is_new_sparse_dir);
1471 if (src[0])
1472 discard_cache_entry(src[0]);
1474 return ret >= 0 ? mask : -1;
1478 * Note that traverse_by_cache_tree() duplicates some logic in this function
1479 * without actually calling it. If you change the logic here you may need to
1480 * check and change there as well.
1482 static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1484 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1485 struct unpack_trees_options *o = info->data;
1486 const struct name_entry *p = names;
1487 int is_new_sparse_dir;
1489 /* Find first entry with a real name (we could use "mask" too) */
1490 while (!p->mode)
1491 p++;
1493 if (o->internal.debug_unpack)
1494 debug_unpack_callback(n, mask, dirmask, names, info);
1496 /* Are we supposed to look at the index too? */
1497 if (o->merge) {
1498 while (1) {
1499 int cmp;
1500 struct cache_entry *ce;
1502 if (o->diff_index_cached)
1503 ce = next_cache_entry(o);
1504 else
1505 ce = find_cache_entry(info, p);
1507 if (!ce)
1508 break;
1509 cmp = compare_entry(ce, info, p);
1510 if (cmp < 0) {
1511 if (unpack_index_entry(ce, o) < 0)
1512 return unpack_failed(o, NULL);
1513 continue;
1515 if (!cmp) {
1516 if (ce_stage(ce)) {
1518 * If we skip unmerged index
1519 * entries, we'll skip this
1520 * entry *and* the tree
1521 * entries associated with it!
1523 if (o->skip_unmerged) {
1524 add_same_unmerged(ce, o);
1525 return mask;
1528 src[0] = ce;
1530 break;
1534 if (unpack_single_entry(n, mask, dirmask, src, names, info, &is_new_sparse_dir))
1535 return -1;
1537 if (o->merge && src[0]) {
1538 if (ce_stage(src[0]))
1539 mark_ce_used_same_name(src[0], o);
1540 else
1541 mark_ce_used(src[0], o);
1544 /* Now handle any directories.. */
1545 if (dirmask) {
1546 /* special case: "diff-index --cached" looking at a tree */
1547 if (o->diff_index_cached &&
1548 n == 1 && dirmask == 1 && S_ISDIR(names->mode)) {
1549 int matches;
1550 matches = cache_tree_matches_traversal(o->src_index->cache_tree,
1551 names, info);
1553 * Everything under the name matches; skip the
1554 * entire hierarchy. diff_index_cached codepath
1555 * special cases D/F conflicts in such a way that
1556 * it does not do any look-ahead, so this is safe.
1558 if (matches) {
1560 * Only increment the cache_bottom if the
1561 * directory isn't a sparse directory index
1562 * entry (if it is, it was already incremented)
1563 * in 'mark_ce_used()'
1565 if (!src[0] || !S_ISSPARSEDIR(src[0]->ce_mode))
1566 o->internal.cache_bottom += matches;
1567 return mask;
1571 if (!is_sparse_directory_entry(src[0], p, info) &&
1572 !is_new_sparse_dir &&
1573 traverse_trees_recursive(n, dirmask, mask & ~dirmask,
1574 names, info) < 0) {
1575 return -1;
1578 return mask;
1581 return mask;
1584 static int clear_ce_flags_1(struct index_state *istate,
1585 struct cache_entry **cache, int nr,
1586 struct strbuf *prefix,
1587 int select_mask, int clear_mask,
1588 struct pattern_list *pl,
1589 enum pattern_match_result default_match,
1590 int progress_nr);
1592 /* Whole directory matching */
1593 static int clear_ce_flags_dir(struct index_state *istate,
1594 struct cache_entry **cache, int nr,
1595 struct strbuf *prefix,
1596 char *basename,
1597 int select_mask, int clear_mask,
1598 struct pattern_list *pl,
1599 enum pattern_match_result default_match,
1600 int progress_nr)
1602 struct cache_entry **cache_end;
1603 int dtype = DT_DIR;
1604 int rc;
1605 enum pattern_match_result ret, orig_ret;
1606 orig_ret = path_matches_pattern_list(prefix->buf, prefix->len,
1607 basename, &dtype, pl, istate);
1609 strbuf_addch(prefix, '/');
1611 /* If undecided, use matching result of parent dir in defval */
1612 if (orig_ret == UNDECIDED)
1613 ret = default_match;
1614 else
1615 ret = orig_ret;
1617 for (cache_end = cache; cache_end != cache + nr; cache_end++) {
1618 struct cache_entry *ce = *cache_end;
1619 if (strncmp(ce->name, prefix->buf, prefix->len))
1620 break;
1623 if (pl->use_cone_patterns && orig_ret == MATCHED_RECURSIVE) {
1624 struct cache_entry **ce = cache;
1625 rc = cache_end - cache;
1627 while (ce < cache_end) {
1628 (*ce)->ce_flags &= ~clear_mask;
1629 ce++;
1631 } else if (pl->use_cone_patterns && orig_ret == NOT_MATCHED) {
1632 rc = cache_end - cache;
1633 } else {
1634 rc = clear_ce_flags_1(istate, cache, cache_end - cache,
1635 prefix,
1636 select_mask, clear_mask,
1637 pl, ret,
1638 progress_nr);
1641 strbuf_setlen(prefix, prefix->len - 1);
1642 return rc;
1646 * Traverse the index, find every entry that matches according to
1647 * o->pl. Do "ce_flags &= ~clear_mask" on those entries. Return the
1648 * number of traversed entries.
1650 * If select_mask is non-zero, only entries whose ce_flags has on of
1651 * those bits enabled are traversed.
1653 * cache : pointer to an index entry
1654 * prefix_len : an offset to its path
1656 * The current path ("prefix") including the trailing '/' is
1657 * cache[0]->name[0..(prefix_len-1)]
1658 * Top level path has prefix_len zero.
1660 static int clear_ce_flags_1(struct index_state *istate,
1661 struct cache_entry **cache, int nr,
1662 struct strbuf *prefix,
1663 int select_mask, int clear_mask,
1664 struct pattern_list *pl,
1665 enum pattern_match_result default_match,
1666 int progress_nr)
1668 struct cache_entry **cache_end = nr ? cache + nr : cache;
1671 * Process all entries that have the given prefix and meet
1672 * select_mask condition
1674 while(cache != cache_end) {
1675 struct cache_entry *ce = *cache;
1676 const char *name, *slash;
1677 int len, dtype;
1678 enum pattern_match_result ret;
1680 display_progress(istate->progress, progress_nr);
1682 if (select_mask && !(ce->ce_flags & select_mask)) {
1683 cache++;
1684 progress_nr++;
1685 continue;
1688 if (prefix->len && strncmp(ce->name, prefix->buf, prefix->len))
1689 break;
1691 name = ce->name + prefix->len;
1692 slash = strchr(name, '/');
1694 /* If it's a directory, try whole directory match first */
1695 if (slash) {
1696 int processed;
1698 len = slash - name;
1699 strbuf_add(prefix, name, len);
1701 processed = clear_ce_flags_dir(istate, cache, cache_end - cache,
1702 prefix,
1703 prefix->buf + prefix->len - len,
1704 select_mask, clear_mask,
1705 pl, default_match,
1706 progress_nr);
1708 /* clear_c_f_dir eats a whole dir already? */
1709 if (processed) {
1710 cache += processed;
1711 progress_nr += processed;
1712 strbuf_setlen(prefix, prefix->len - len);
1713 continue;
1716 strbuf_addch(prefix, '/');
1717 processed = clear_ce_flags_1(istate, cache, cache_end - cache,
1718 prefix,
1719 select_mask, clear_mask, pl,
1720 default_match, progress_nr);
1722 cache += processed;
1723 progress_nr += processed;
1725 strbuf_setlen(prefix, prefix->len - len - 1);
1726 continue;
1729 /* Non-directory */
1730 dtype = ce_to_dtype(ce);
1731 ret = path_matches_pattern_list(ce->name,
1732 ce_namelen(ce),
1733 name, &dtype, pl, istate);
1734 if (ret == UNDECIDED)
1735 ret = default_match;
1736 if (ret == MATCHED || ret == MATCHED_RECURSIVE)
1737 ce->ce_flags &= ~clear_mask;
1738 cache++;
1739 progress_nr++;
1742 display_progress(istate->progress, progress_nr);
1743 return nr - (cache_end - cache);
1746 static int clear_ce_flags(struct index_state *istate,
1747 int select_mask, int clear_mask,
1748 struct pattern_list *pl,
1749 int show_progress)
1751 static struct strbuf prefix = STRBUF_INIT;
1752 char label[100];
1753 int rval;
1755 strbuf_reset(&prefix);
1756 if (show_progress)
1757 istate->progress = start_delayed_progress(
1758 _("Updating index flags"),
1759 istate->cache_nr);
1761 xsnprintf(label, sizeof(label), "clear_ce_flags(0x%08lx,0x%08lx)",
1762 (unsigned long)select_mask, (unsigned long)clear_mask);
1763 trace2_region_enter("unpack_trees", label, the_repository);
1764 rval = clear_ce_flags_1(istate,
1765 istate->cache,
1766 istate->cache_nr,
1767 &prefix,
1768 select_mask, clear_mask,
1769 pl, 0, 0);
1770 trace2_region_leave("unpack_trees", label, the_repository);
1772 stop_progress(&istate->progress);
1773 return rval;
1777 * Set/Clear CE_NEW_SKIP_WORKTREE according to $GIT_DIR/info/sparse-checkout
1779 static void mark_new_skip_worktree(struct pattern_list *pl,
1780 struct index_state *istate,
1781 int select_flag, int skip_wt_flag,
1782 int show_progress)
1784 int i;
1787 * 1. Pretend the narrowest worktree: only unmerged entries
1788 * are checked out
1790 for (i = 0; i < istate->cache_nr; i++) {
1791 struct cache_entry *ce = istate->cache[i];
1793 if (select_flag && !(ce->ce_flags & select_flag))
1794 continue;
1796 if (!ce_stage(ce) && !(ce->ce_flags & CE_CONFLICTED))
1797 ce->ce_flags |= skip_wt_flag;
1798 else
1799 ce->ce_flags &= ~skip_wt_flag;
1803 * 2. Widen worktree according to sparse-checkout file.
1804 * Matched entries will have skip_wt_flag cleared (i.e. "in")
1806 clear_ce_flags(istate, select_flag, skip_wt_flag, pl, show_progress);
1809 static void populate_from_existing_patterns(struct unpack_trees_options *o,
1810 struct pattern_list *pl)
1812 if (get_sparse_checkout_patterns(pl) < 0)
1813 o->skip_sparse_checkout = 1;
1814 else
1815 o->internal.pl = pl;
1818 static void update_sparsity_for_prefix(const char *prefix,
1819 struct index_state *istate)
1821 int prefix_len = strlen(prefix);
1822 struct strbuf ce_prefix = STRBUF_INIT;
1824 if (!istate->sparse_index)
1825 return;
1827 while (prefix_len > 0 && prefix[prefix_len - 1] == '/')
1828 prefix_len--;
1830 if (prefix_len <= 0)
1831 BUG("Invalid prefix passed to update_sparsity_for_prefix");
1833 strbuf_grow(&ce_prefix, prefix_len + 1);
1834 strbuf_add(&ce_prefix, prefix, prefix_len);
1835 strbuf_addch(&ce_prefix, '/');
1838 * If the prefix points to a sparse directory or a path inside a sparse
1839 * directory, the index should be expanded. This is accomplished in one
1840 * of two ways:
1841 * - if the prefix is inside a sparse directory, it will be expanded by
1842 * the 'ensure_full_index(...)' call in 'index_name_pos(...)'.
1843 * - if the prefix matches an existing sparse directory entry,
1844 * 'index_name_pos(...)' will return its index position, triggering
1845 * the 'ensure_full_index(...)' below.
1847 if (!path_in_cone_mode_sparse_checkout(ce_prefix.buf, istate) &&
1848 index_name_pos(istate, ce_prefix.buf, ce_prefix.len) >= 0)
1849 ensure_full_index(istate);
1851 strbuf_release(&ce_prefix);
1854 static int verify_absent(const struct cache_entry *,
1855 enum unpack_trees_error_types,
1856 struct unpack_trees_options *);
1858 * N-way merge "len" trees. Returns 0 on success, -1 on failure to manipulate the
1859 * resulting index, -2 on failure to reflect the changes to the work tree.
1861 * CE_ADDED, CE_UNPACKED and CE_NEW_SKIP_WORKTREE are used internally
1863 int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
1865 struct repository *repo = the_repository;
1866 int i, ret;
1867 static struct cache_entry *dfc;
1868 struct pattern_list pl;
1869 int free_pattern_list = 0;
1870 struct dir_struct dir = DIR_INIT;
1872 if (o->reset == UNPACK_RESET_INVALID)
1873 BUG("o->reset had a value of 1; should be UNPACK_TREES_*_UNTRACKED");
1875 if (len > MAX_UNPACK_TREES)
1876 die("unpack_trees takes at most %d trees", MAX_UNPACK_TREES);
1877 if (o->internal.dir)
1878 BUG("o->internal.dir is for internal use only");
1879 if (o->internal.pl)
1880 BUG("o->internal.pl is for internal use only");
1881 if (o->df_conflict_entry)
1882 BUG("o->df_conflict_entry is an output only field");
1884 trace_performance_enter();
1885 trace2_region_enter("unpack_trees", "unpack_trees", the_repository);
1887 prepare_repo_settings(repo);
1888 if (repo->settings.command_requires_full_index) {
1889 ensure_full_index(o->src_index);
1890 if (o->dst_index)
1891 ensure_full_index(o->dst_index);
1894 if (o->reset == UNPACK_RESET_OVERWRITE_UNTRACKED &&
1895 o->preserve_ignored)
1896 BUG("UNPACK_RESET_OVERWRITE_UNTRACKED incompatible with preserved ignored files");
1898 if (!o->preserve_ignored) {
1899 o->internal.dir = &dir;
1900 o->internal.dir->flags |= DIR_SHOW_IGNORED;
1901 setup_standard_excludes(o->internal.dir);
1904 if (o->prefix)
1905 update_sparsity_for_prefix(o->prefix, o->src_index);
1907 if (!core_apply_sparse_checkout || !o->update)
1908 o->skip_sparse_checkout = 1;
1909 if (!o->skip_sparse_checkout) {
1910 memset(&pl, 0, sizeof(pl));
1911 free_pattern_list = 1;
1912 populate_from_existing_patterns(o, &pl);
1915 index_state_init(&o->internal.result, o->src_index->repo);
1916 o->internal.result.initialized = 1;
1917 o->internal.result.timestamp.sec = o->src_index->timestamp.sec;
1918 o->internal.result.timestamp.nsec = o->src_index->timestamp.nsec;
1919 o->internal.result.version = o->src_index->version;
1920 if (!o->src_index->split_index) {
1921 o->internal.result.split_index = NULL;
1922 } else if (o->src_index == o->dst_index) {
1924 * o->dst_index (and thus o->src_index) will be discarded
1925 * and overwritten with o->internal.result at the end of
1926 * this function, so just use src_index's split_index to
1927 * avoid having to create a new one.
1929 o->internal.result.split_index = o->src_index->split_index;
1930 o->internal.result.split_index->refcount++;
1931 } else {
1932 o->internal.result.split_index =
1933 init_split_index(&o->internal.result);
1935 oidcpy(&o->internal.result.oid, &o->src_index->oid);
1936 o->internal.merge_size = len;
1937 mark_all_ce_unused(o->src_index);
1939 o->internal.result.fsmonitor_last_update =
1940 xstrdup_or_null(o->src_index->fsmonitor_last_update);
1941 o->internal.result.fsmonitor_has_run_once = o->src_index->fsmonitor_has_run_once;
1943 if (!o->src_index->initialized &&
1944 !repo->settings.command_requires_full_index &&
1945 is_sparse_index_allowed(&o->internal.result, 0))
1946 o->internal.result.sparse_index = 1;
1949 * Sparse checkout loop #1: set NEW_SKIP_WORKTREE on existing entries
1951 if (!o->skip_sparse_checkout)
1952 mark_new_skip_worktree(o->internal.pl, o->src_index, 0,
1953 CE_NEW_SKIP_WORKTREE, o->verbose_update);
1955 if (!dfc)
1956 dfc = xcalloc(1, cache_entry_size(0));
1957 o->df_conflict_entry = dfc;
1959 if (len) {
1960 const char *prefix = o->prefix ? o->prefix : "";
1961 struct traverse_info info;
1963 setup_traverse_info(&info, prefix);
1964 info.fn = unpack_callback;
1965 info.data = o;
1966 info.show_all_errors = o->internal.show_all_errors;
1967 info.pathspec = o->pathspec;
1969 if (o->prefix) {
1971 * Unpack existing index entries that sort before the
1972 * prefix the tree is spliced into. Note that o->merge
1973 * is always true in this case.
1975 while (1) {
1976 struct cache_entry *ce = next_cache_entry(o);
1977 if (!ce)
1978 break;
1979 if (ce_in_traverse_path(ce, &info))
1980 break;
1981 if (unpack_index_entry(ce, o) < 0)
1982 goto return_failed;
1986 trace_performance_enter();
1987 trace2_region_enter("unpack_trees", "traverse_trees", the_repository);
1988 ret = traverse_trees(o->src_index, len, t, &info);
1989 trace2_region_leave("unpack_trees", "traverse_trees", the_repository);
1990 trace_performance_leave("traverse_trees");
1991 if (ret < 0)
1992 goto return_failed;
1995 /* Any left-over entries in the index? */
1996 if (o->merge) {
1997 while (1) {
1998 struct cache_entry *ce = next_cache_entry(o);
1999 if (!ce)
2000 break;
2001 if (unpack_index_entry(ce, o) < 0)
2002 goto return_failed;
2005 mark_all_ce_unused(o->src_index);
2007 if (o->trivial_merges_only && o->internal.nontrivial_merge) {
2008 ret = unpack_failed(o, "Merge requires file-level merging");
2009 goto done;
2012 if (!o->skip_sparse_checkout) {
2014 * Sparse checkout loop #2: set NEW_SKIP_WORKTREE on entries not in loop #1
2015 * If they will have NEW_SKIP_WORKTREE, also set CE_SKIP_WORKTREE
2016 * so apply_sparse_checkout() won't attempt to remove it from worktree
2018 mark_new_skip_worktree(o->internal.pl, &o->internal.result,
2019 CE_ADDED, CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE,
2020 o->verbose_update);
2022 ret = 0;
2023 for (i = 0; i < o->internal.result.cache_nr; i++) {
2024 struct cache_entry *ce = o->internal.result.cache[i];
2027 * Entries marked with CE_ADDED in merged_entry() do not have
2028 * verify_absent() check (the check is effectively disabled
2029 * because CE_NEW_SKIP_WORKTREE is set unconditionally).
2031 * Do the real check now because we have had
2032 * correct CE_NEW_SKIP_WORKTREE
2034 if (ce->ce_flags & CE_ADDED &&
2035 verify_absent(ce, WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN, o))
2036 ret = 1;
2038 if (apply_sparse_checkout(&o->internal.result, ce, o))
2039 ret = 1;
2041 if (ret == 1) {
2043 * Inability to sparsify or de-sparsify individual
2044 * paths is not an error, but just a warning.
2046 if (o->internal.show_all_errors)
2047 display_warning_msgs(o);
2048 ret = 0;
2052 ret = check_updates(o, &o->internal.result) ? (-2) : 0;
2053 if (o->dst_index) {
2054 move_index_extensions(&o->internal.result, o->src_index);
2055 if (!ret) {
2056 if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0))
2057 cache_tree_verify(the_repository,
2058 &o->internal.result);
2059 if (!o->skip_cache_tree_update &&
2060 !cache_tree_fully_valid(o->internal.result.cache_tree))
2061 cache_tree_update(&o->internal.result,
2062 WRITE_TREE_SILENT |
2063 WRITE_TREE_REPAIR);
2066 o->internal.result.updated_workdir = 1;
2067 discard_index(o->dst_index);
2068 *o->dst_index = o->internal.result;
2069 } else {
2070 discard_index(&o->internal.result);
2072 o->src_index = NULL;
2074 done:
2075 if (free_pattern_list)
2076 clear_pattern_list(&pl);
2077 if (o->internal.dir) {
2078 dir_clear(o->internal.dir);
2079 o->internal.dir = NULL;
2081 trace2_region_leave("unpack_trees", "unpack_trees", the_repository);
2082 trace_performance_leave("unpack_trees");
2083 return ret;
2085 return_failed:
2086 if (o->internal.show_all_errors)
2087 display_error_msgs(o);
2088 mark_all_ce_unused(o->src_index);
2089 ret = unpack_failed(o, NULL);
2090 if (o->exiting_early)
2091 ret = 0;
2092 goto done;
2096 * Update SKIP_WORKTREE bits according to sparsity patterns, and update
2097 * working directory to match.
2099 * CE_NEW_SKIP_WORKTREE is used internally.
2101 enum update_sparsity_result update_sparsity(struct unpack_trees_options *o,
2102 struct pattern_list *pl)
2104 enum update_sparsity_result ret = UPDATE_SPARSITY_SUCCESS;
2105 int i;
2106 unsigned old_show_all_errors;
2107 int free_pattern_list = 0;
2109 old_show_all_errors = o->internal.show_all_errors;
2110 o->internal.show_all_errors = 1;
2111 index_state_init(&o->internal.result, o->src_index->repo);
2113 /* Sanity checks */
2114 if (!o->update || o->index_only || o->skip_sparse_checkout)
2115 BUG("update_sparsity() is for reflecting sparsity patterns in working directory");
2116 if (o->src_index != o->dst_index || o->fn)
2117 BUG("update_sparsity() called wrong");
2119 trace_performance_enter();
2121 /* If we weren't given patterns, use the recorded ones */
2122 if (!pl) {
2123 free_pattern_list = 1;
2124 pl = xcalloc(1, sizeof(*pl));
2125 populate_from_existing_patterns(o, pl);
2127 o->internal.pl = pl;
2129 /* Expand sparse directories as needed */
2130 expand_index(o->src_index, o->internal.pl);
2132 /* Set NEW_SKIP_WORKTREE on existing entries. */
2133 mark_all_ce_unused(o->src_index);
2134 mark_new_skip_worktree(o->internal.pl, o->src_index, 0,
2135 CE_NEW_SKIP_WORKTREE, o->verbose_update);
2137 /* Then loop over entries and update/remove as needed */
2138 ret = UPDATE_SPARSITY_SUCCESS;
2139 for (i = 0; i < o->src_index->cache_nr; i++) {
2140 struct cache_entry *ce = o->src_index->cache[i];
2143 if (ce_stage(ce)) {
2144 /* -1 because for loop will increment by 1 */
2145 i += warn_conflicted_path(o->src_index, i, o) - 1;
2146 ret = UPDATE_SPARSITY_WARNINGS;
2147 continue;
2150 if (apply_sparse_checkout(o->src_index, ce, o))
2151 ret = UPDATE_SPARSITY_WARNINGS;
2154 if (check_updates(o, o->src_index))
2155 ret = UPDATE_SPARSITY_WORKTREE_UPDATE_FAILURES;
2157 display_warning_msgs(o);
2158 o->internal.show_all_errors = old_show_all_errors;
2159 if (free_pattern_list) {
2160 clear_pattern_list(pl);
2161 free(pl);
2162 o->internal.pl = NULL;
2164 trace_performance_leave("update_sparsity");
2165 return ret;
2168 /* Here come the merge functions */
2170 static int reject_merge(const struct cache_entry *ce,
2171 struct unpack_trees_options *o)
2173 return add_rejected_path(o, ERROR_WOULD_OVERWRITE, ce->name);
2176 static int same(const struct cache_entry *a, const struct cache_entry *b)
2178 if (!!a != !!b)
2179 return 0;
2180 if (!a && !b)
2181 return 1;
2182 if ((a->ce_flags | b->ce_flags) & CE_CONFLICTED)
2183 return 0;
2184 return a->ce_mode == b->ce_mode &&
2185 oideq(&a->oid, &b->oid);
2190 * When a CE gets turned into an unmerged entry, we
2191 * want it to be up-to-date
2193 static int verify_uptodate_1(const struct cache_entry *ce,
2194 struct unpack_trees_options *o,
2195 enum unpack_trees_error_types error_type)
2197 struct stat st;
2199 if (o->index_only)
2200 return 0;
2203 * CE_VALID and CE_SKIP_WORKTREE cheat, we better check again
2204 * if this entry is truly up-to-date because this file may be
2205 * overwritten.
2207 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2208 ; /* keep checking */
2209 else if (o->reset || ce_uptodate(ce))
2210 return 0;
2212 if (!lstat(ce->name, &st)) {
2213 int flags = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE;
2214 unsigned changed = ie_match_stat(o->src_index, ce, &st, flags);
2216 if (submodule_from_ce(ce)) {
2217 int r = check_submodule_move_head(ce,
2218 "HEAD", oid_to_hex(&ce->oid), o);
2219 if (r)
2220 return add_rejected_path(o, error_type, ce->name);
2221 return 0;
2224 if (!changed)
2225 return 0;
2227 * Historic default policy was to allow submodule to be out
2228 * of sync wrt the superproject index. If the submodule was
2229 * not considered interesting above, we don't care here.
2231 if (S_ISGITLINK(ce->ce_mode))
2232 return 0;
2234 errno = 0;
2236 if (errno == ENOENT)
2237 return 0;
2238 return add_rejected_path(o, error_type, ce->name);
2241 int verify_uptodate(const struct cache_entry *ce,
2242 struct unpack_trees_options *o)
2244 if (!o->skip_sparse_checkout &&
2245 (ce->ce_flags & CE_SKIP_WORKTREE) &&
2246 (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2247 return 0;
2248 return verify_uptodate_1(ce, o, ERROR_NOT_UPTODATE_FILE);
2251 static int verify_uptodate_sparse(const struct cache_entry *ce,
2252 struct unpack_trees_options *o)
2254 return verify_uptodate_1(ce, o, WARNING_SPARSE_NOT_UPTODATE_FILE);
2258 * TODO: We should actually invalidate o->internal.result, not src_index [1].
2259 * But since cache tree and untracked cache both are not copied to
2260 * o->internal.result until unpacking is complete, we invalidate them on
2261 * src_index instead with the assumption that they will be copied to
2262 * dst_index at the end.
2264 * [1] src_index->cache_tree is also used in unpack_callback() so if
2265 * we invalidate o->internal.result, we need to update it to use
2266 * o->internal.result.cache_tree as well.
2268 static void invalidate_ce_path(const struct cache_entry *ce,
2269 struct unpack_trees_options *o)
2271 if (!ce)
2272 return;
2273 cache_tree_invalidate_path(o->src_index, ce->name);
2274 untracked_cache_invalidate_path(o->src_index, ce->name, 1);
2278 * Check that checking out ce->sha1 in subdir ce->name is not
2279 * going to overwrite any working files.
2281 static int verify_clean_submodule(const char *old_sha1,
2282 const struct cache_entry *ce,
2283 struct unpack_trees_options *o)
2285 if (!submodule_from_ce(ce))
2286 return 0;
2288 return check_submodule_move_head(ce, old_sha1,
2289 oid_to_hex(&ce->oid), o);
2292 static int verify_clean_subdirectory(const struct cache_entry *ce,
2293 struct unpack_trees_options *o)
2296 * we are about to extract "ce->name"; we would not want to lose
2297 * anything in the existing directory there.
2299 int namelen;
2300 int i;
2301 struct dir_struct d;
2302 char *pathbuf;
2303 int cnt = 0;
2305 if (S_ISGITLINK(ce->ce_mode)) {
2306 struct object_id oid;
2307 int sub_head = resolve_gitlink_ref(ce->name, "HEAD", &oid);
2309 * If we are not going to update the submodule, then
2310 * we don't care.
2312 if (!sub_head && oideq(&oid, &ce->oid))
2313 return 0;
2314 return verify_clean_submodule(sub_head ? NULL : oid_to_hex(&oid),
2315 ce, o);
2319 * First let's make sure we do not have a local modification
2320 * in that directory.
2322 namelen = ce_namelen(ce);
2323 for (i = locate_in_src_index(ce, o);
2324 i < o->src_index->cache_nr;
2325 i++) {
2326 struct cache_entry *ce2 = o->src_index->cache[i];
2327 int len = ce_namelen(ce2);
2328 if (len < namelen ||
2329 strncmp(ce->name, ce2->name, namelen) ||
2330 ce2->name[namelen] != '/')
2331 break;
2333 * ce2->name is an entry in the subdirectory to be
2334 * removed.
2336 if (!ce_stage(ce2)) {
2337 if (verify_uptodate(ce2, o))
2338 return -1;
2339 add_entry(o, ce2, CE_REMOVE, 0);
2340 invalidate_ce_path(ce, o);
2341 mark_ce_used(ce2, o);
2343 cnt++;
2346 /* Do not lose a locally present file that is not ignored. */
2347 pathbuf = xstrfmt("%.*s/", namelen, ce->name);
2349 memset(&d, 0, sizeof(d));
2350 if (o->internal.dir)
2351 setup_standard_excludes(&d);
2352 i = read_directory(&d, o->src_index, pathbuf, namelen+1, NULL);
2353 dir_clear(&d);
2354 free(pathbuf);
2355 if (i)
2356 return add_rejected_path(o, ERROR_NOT_UPTODATE_DIR, ce->name);
2358 /* Do not lose startup_info->original_cwd */
2359 if (startup_info->original_cwd &&
2360 !strcmp(startup_info->original_cwd, ce->name))
2361 return add_rejected_path(o, ERROR_CWD_IN_THE_WAY, ce->name);
2363 return cnt;
2367 * This gets called when there was no index entry for the tree entry 'dst',
2368 * but we found a file in the working tree that 'lstat()' said was fine,
2369 * and we're on a case-insensitive filesystem.
2371 * See if we can find a case-insensitive match in the index that also
2372 * matches the stat information, and assume it's that other file!
2374 static int icase_exists(struct unpack_trees_options *o, const char *name, int len, struct stat *st)
2376 const struct cache_entry *src;
2378 src = index_file_exists(o->src_index, name, len, 1);
2379 return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
2382 enum absent_checking_type {
2383 COMPLETELY_ABSENT,
2384 ABSENT_ANY_DIRECTORY
2387 static int check_ok_to_remove(const char *name, int len, int dtype,
2388 const struct cache_entry *ce, struct stat *st,
2389 enum unpack_trees_error_types error_type,
2390 enum absent_checking_type absent_type,
2391 struct unpack_trees_options *o)
2393 const struct cache_entry *result;
2396 * It may be that the 'lstat()' succeeded even though
2397 * target 'ce' was absent, because there is an old
2398 * entry that is different only in case..
2400 * Ignore that lstat() if it matches.
2402 if (ignore_case && icase_exists(o, name, len, st))
2403 return 0;
2405 if (o->internal.dir &&
2406 is_excluded(o->internal.dir, o->src_index, name, &dtype))
2408 * ce->name is explicitly excluded, so it is Ok to
2409 * overwrite it.
2411 return 0;
2412 if (S_ISDIR(st->st_mode)) {
2414 * We are checking out path "foo" and
2415 * found "foo/." in the working tree.
2416 * This is tricky -- if we have modified
2417 * files that are in "foo/" we would lose
2418 * them.
2420 if (verify_clean_subdirectory(ce, o) < 0)
2421 return -1;
2422 return 0;
2425 /* If we only care about directories, then we can remove */
2426 if (absent_type == ABSENT_ANY_DIRECTORY)
2427 return 0;
2430 * The previous round may already have decided to
2431 * delete this path, which is in a subdirectory that
2432 * is being replaced with a blob.
2434 result = index_file_exists(&o->internal.result, name, len, 0);
2435 if (result) {
2436 if (result->ce_flags & CE_REMOVE)
2437 return 0;
2440 return add_rejected_path(o, error_type, name);
2444 * We do not want to remove or overwrite a working tree file that
2445 * is not tracked, unless it is ignored.
2447 static int verify_absent_1(const struct cache_entry *ce,
2448 enum unpack_trees_error_types error_type,
2449 enum absent_checking_type absent_type,
2450 struct unpack_trees_options *o)
2452 int len;
2453 struct stat st;
2455 if (o->index_only || !o->update)
2456 return 0;
2458 if (o->reset == UNPACK_RESET_OVERWRITE_UNTRACKED) {
2459 /* Avoid nuking startup_info->original_cwd... */
2460 if (startup_info->original_cwd &&
2461 !strcmp(startup_info->original_cwd, ce->name))
2462 return add_rejected_path(o, ERROR_CWD_IN_THE_WAY,
2463 ce->name);
2464 /* ...but nuke anything else. */
2465 return 0;
2468 len = check_leading_path(ce->name, ce_namelen(ce), 0);
2469 if (!len)
2470 return 0;
2471 else if (len > 0) {
2472 char *path;
2473 int ret;
2475 path = xmemdupz(ce->name, len);
2476 if (lstat(path, &st))
2477 ret = error_errno("cannot stat '%s'", path);
2478 else {
2479 if (submodule_from_ce(ce))
2480 ret = check_submodule_move_head(ce,
2481 oid_to_hex(&ce->oid),
2482 NULL, o);
2483 else
2484 ret = check_ok_to_remove(path, len, DT_UNKNOWN, NULL,
2485 &st, error_type,
2486 absent_type, o);
2488 free(path);
2489 return ret;
2490 } else if (lstat(ce->name, &st)) {
2491 if (errno != ENOENT)
2492 return error_errno("cannot stat '%s'", ce->name);
2493 return 0;
2494 } else {
2495 if (submodule_from_ce(ce))
2496 return check_submodule_move_head(ce, oid_to_hex(&ce->oid),
2497 NULL, o);
2499 return check_ok_to_remove(ce->name, ce_namelen(ce),
2500 ce_to_dtype(ce), ce, &st,
2501 error_type, absent_type, o);
2505 static int verify_absent(const struct cache_entry *ce,
2506 enum unpack_trees_error_types error_type,
2507 struct unpack_trees_options *o)
2509 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2510 return 0;
2511 return verify_absent_1(ce, error_type, COMPLETELY_ABSENT, o);
2514 static int verify_absent_if_directory(const struct cache_entry *ce,
2515 enum unpack_trees_error_types error_type,
2516 struct unpack_trees_options *o)
2518 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2519 return 0;
2520 return verify_absent_1(ce, error_type, ABSENT_ANY_DIRECTORY, o);
2523 static int verify_absent_sparse(const struct cache_entry *ce,
2524 enum unpack_trees_error_types error_type,
2525 struct unpack_trees_options *o)
2527 return verify_absent_1(ce, error_type, COMPLETELY_ABSENT, o);
2530 static int merged_entry(const struct cache_entry *ce,
2531 const struct cache_entry *old,
2532 struct unpack_trees_options *o)
2534 int update = CE_UPDATE;
2535 struct cache_entry *merge = dup_cache_entry(ce, &o->internal.result);
2537 if (!old) {
2539 * New index entries. In sparse checkout, the following
2540 * verify_absent() will be delayed until after
2541 * traverse_trees() finishes in unpack_trees(), then:
2543 * - CE_NEW_SKIP_WORKTREE will be computed correctly
2544 * - verify_absent() be called again, this time with
2545 * correct CE_NEW_SKIP_WORKTREE
2547 * verify_absent() call here does nothing in sparse
2548 * checkout (i.e. o->skip_sparse_checkout == 0)
2550 update |= CE_ADDED;
2551 merge->ce_flags |= CE_NEW_SKIP_WORKTREE;
2553 if (verify_absent(merge,
2554 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
2555 discard_cache_entry(merge);
2556 return -1;
2558 invalidate_ce_path(merge, o);
2560 if (submodule_from_ce(ce) && file_exists(ce->name)) {
2561 int ret = check_submodule_move_head(ce, NULL,
2562 oid_to_hex(&ce->oid),
2564 if (ret)
2565 return ret;
2568 } else if (!(old->ce_flags & CE_CONFLICTED)) {
2570 * See if we can re-use the old CE directly?
2571 * That way we get the uptodate stat info.
2573 * This also removes the UPDATE flag on a match; otherwise
2574 * we will end up overwriting local changes in the work tree.
2576 if (same(old, merge)) {
2577 copy_cache_entry(merge, old);
2578 update = 0;
2579 } else {
2580 if (verify_uptodate(old, o)) {
2581 discard_cache_entry(merge);
2582 return -1;
2584 /* Migrate old flags over */
2585 update |= old->ce_flags & (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
2586 invalidate_ce_path(old, o);
2589 if (submodule_from_ce(ce) && file_exists(ce->name)) {
2590 int ret = check_submodule_move_head(ce, oid_to_hex(&old->oid),
2591 oid_to_hex(&ce->oid),
2593 if (ret)
2594 return ret;
2596 } else {
2598 * Previously unmerged entry left as an existence
2599 * marker by read_index_unmerged();
2601 if (verify_absent_if_directory(merge,
2602 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
2603 discard_cache_entry(merge);
2604 return -1;
2607 invalidate_ce_path(old, o);
2610 if (do_add_entry(o, merge, update, CE_STAGEMASK) < 0)
2611 return -1;
2612 return 1;
2615 static int merged_sparse_dir(const struct cache_entry * const *src, int n,
2616 struct unpack_trees_options *o)
2618 struct tree_desc t[MAX_UNPACK_TREES + 1];
2619 void * tree_bufs[MAX_UNPACK_TREES + 1];
2620 struct traverse_info info;
2621 int i, ret;
2624 * Create the tree traversal information for traversing into *only* the
2625 * sparse directory.
2627 setup_traverse_info(&info, src[0]->name);
2628 info.fn = unpack_sparse_callback;
2629 info.data = o;
2630 info.show_all_errors = o->internal.show_all_errors;
2631 info.pathspec = o->pathspec;
2633 /* Get the tree descriptors of the sparse directory in each of the merging trees */
2634 for (i = 0; i < n; i++)
2635 tree_bufs[i] = fill_tree_descriptor(o->src_index->repo, &t[i],
2636 src[i] && !is_null_oid(&src[i]->oid) ? &src[i]->oid : NULL);
2638 ret = traverse_trees(o->src_index, n, t, &info);
2640 for (i = 0; i < n; i++)
2641 free(tree_bufs[i]);
2643 return ret;
2646 static int deleted_entry(const struct cache_entry *ce,
2647 const struct cache_entry *old,
2648 struct unpack_trees_options *o)
2650 /* Did it exist in the index? */
2651 if (!old) {
2652 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2653 return -1;
2654 return 0;
2655 } else if (verify_absent_if_directory(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o)) {
2656 return -1;
2659 if (!(old->ce_flags & CE_CONFLICTED) && verify_uptodate(old, o))
2660 return -1;
2661 add_entry(o, ce, CE_REMOVE, 0);
2662 invalidate_ce_path(ce, o);
2663 return 1;
2666 static int keep_entry(const struct cache_entry *ce,
2667 struct unpack_trees_options *o)
2669 add_entry(o, ce, 0, 0);
2670 if (ce_stage(ce))
2671 invalidate_ce_path(ce, o);
2672 return 1;
2675 #if DBRT_DEBUG
2676 static void show_stage_entry(FILE *o,
2677 const char *label, const struct cache_entry *ce)
2679 if (!ce)
2680 fprintf(o, "%s (missing)\n", label);
2681 else
2682 fprintf(o, "%s%06o %s %d\t%s\n",
2683 label,
2684 ce->ce_mode,
2685 oid_to_hex(&ce->oid),
2686 ce_stage(ce),
2687 ce->name);
2689 #endif
2691 int threeway_merge(const struct cache_entry * const *stages,
2692 struct unpack_trees_options *o)
2694 const struct cache_entry *index;
2695 const struct cache_entry *head;
2696 const struct cache_entry *remote = stages[o->head_idx + 1];
2697 int count;
2698 int head_match = 0;
2699 int remote_match = 0;
2701 int df_conflict_head = 0;
2702 int df_conflict_remote = 0;
2704 int any_anc_missing = 0;
2705 int no_anc_exists = 1;
2706 int i;
2708 for (i = 1; i < o->head_idx; i++) {
2709 if (!stages[i] || stages[i] == o->df_conflict_entry)
2710 any_anc_missing = 1;
2711 else
2712 no_anc_exists = 0;
2715 index = stages[0];
2716 head = stages[o->head_idx];
2718 if (head == o->df_conflict_entry) {
2719 df_conflict_head = 1;
2720 head = NULL;
2723 if (remote == o->df_conflict_entry) {
2724 df_conflict_remote = 1;
2725 remote = NULL;
2729 * First, if there's a #16 situation, note that to prevent #13
2730 * and #14.
2732 if (!same(remote, head)) {
2733 for (i = 1; i < o->head_idx; i++) {
2734 if (same(stages[i], head)) {
2735 head_match = i;
2737 if (same(stages[i], remote)) {
2738 remote_match = i;
2744 * We start with cases where the index is allowed to match
2745 * something other than the head: #14(ALT) and #2ALT, where it
2746 * is permitted to match the result instead.
2748 /* #14, #14ALT, #2ALT */
2749 if (remote && !df_conflict_head && head_match && !remote_match) {
2750 if (index && !same(index, remote) && !same(index, head)) {
2751 if (S_ISSPARSEDIR(index->ce_mode))
2752 return merged_sparse_dir(stages, 4, o);
2753 else
2754 return reject_merge(index, o);
2756 return merged_entry(remote, index, o);
2759 * If we have an entry in the index cache, then we want to
2760 * make sure that it matches head.
2762 if (index && !same(index, head)) {
2763 if (S_ISSPARSEDIR(index->ce_mode))
2764 return merged_sparse_dir(stages, 4, o);
2765 else
2766 return reject_merge(index, o);
2769 if (head) {
2770 /* #5ALT, #15 */
2771 if (same(head, remote))
2772 return merged_entry(head, index, o);
2773 /* #13, #3ALT */
2774 if (!df_conflict_remote && remote_match && !head_match)
2775 return merged_entry(head, index, o);
2778 /* #1 */
2779 if (!head && !remote && any_anc_missing)
2780 return 0;
2783 * Under the "aggressive" rule, we resolve mostly trivial
2784 * cases that we historically had git-merge-one-file resolve.
2786 if (o->aggressive) {
2787 int head_deleted = !head;
2788 int remote_deleted = !remote;
2789 const struct cache_entry *ce = NULL;
2791 if (index)
2792 ce = index;
2793 else if (head)
2794 ce = head;
2795 else if (remote)
2796 ce = remote;
2797 else {
2798 for (i = 1; i < o->head_idx; i++) {
2799 if (stages[i] && stages[i] != o->df_conflict_entry) {
2800 ce = stages[i];
2801 break;
2807 * Deleted in both.
2808 * Deleted in one and unchanged in the other.
2810 if ((head_deleted && remote_deleted) ||
2811 (head_deleted && remote && remote_match) ||
2812 (remote_deleted && head && head_match)) {
2813 if (index)
2814 return deleted_entry(index, index, o);
2815 if (ce && !head_deleted) {
2816 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2817 return -1;
2819 return 0;
2822 * Added in both, identically.
2824 if (no_anc_exists && head && remote && same(head, remote))
2825 return merged_entry(head, index, o);
2829 /* Handle "no merge" cases (see t/t1000-read-tree-m-3way.sh) */
2830 if (index) {
2832 * If we've reached the "no merge" cases and we're merging
2833 * a sparse directory, we may have an "edit/edit" conflict that
2834 * can be resolved by individually merging directory contents.
2836 if (S_ISSPARSEDIR(index->ce_mode))
2837 return merged_sparse_dir(stages, 4, o);
2840 * If we're not merging a sparse directory, ensure the index is
2841 * up-to-date to avoid files getting overwritten with conflict
2842 * resolution files
2844 if (verify_uptodate(index, o))
2845 return -1;
2848 o->internal.nontrivial_merge = 1;
2850 /* #2, #3, #4, #6, #7, #9, #10, #11. */
2851 count = 0;
2852 if (!head_match || !remote_match) {
2853 for (i = 1; i < o->head_idx; i++) {
2854 if (stages[i] && stages[i] != o->df_conflict_entry) {
2855 keep_entry(stages[i], o);
2856 count++;
2857 break;
2861 #if DBRT_DEBUG
2862 else {
2863 fprintf(stderr, "read-tree: warning #16 detected\n");
2864 show_stage_entry(stderr, "head ", stages[head_match]);
2865 show_stage_entry(stderr, "remote ", stages[remote_match]);
2867 #endif
2868 if (head) { count += keep_entry(head, o); }
2869 if (remote) { count += keep_entry(remote, o); }
2870 return count;
2874 * Two-way merge.
2876 * The rule is to "carry forward" what is in the index without losing
2877 * information across a "fast-forward", favoring a successful merge
2878 * over a merge failure when it makes sense. For details of the
2879 * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
2882 int twoway_merge(const struct cache_entry * const *src,
2883 struct unpack_trees_options *o)
2885 const struct cache_entry *current = src[0];
2886 const struct cache_entry *oldtree = src[1];
2887 const struct cache_entry *newtree = src[2];
2889 if (o->internal.merge_size != 2)
2890 return error("Cannot do a twoway merge of %d trees",
2891 o->internal.merge_size);
2893 if (oldtree == o->df_conflict_entry)
2894 oldtree = NULL;
2895 if (newtree == o->df_conflict_entry)
2896 newtree = NULL;
2898 if (current) {
2899 if (current->ce_flags & CE_CONFLICTED) {
2900 if (same(oldtree, newtree) || o->reset) {
2901 if (!newtree)
2902 return deleted_entry(current, current, o);
2903 else
2904 return merged_entry(newtree, current, o);
2906 return reject_merge(current, o);
2907 } else if ((!oldtree && !newtree) || /* 4 and 5 */
2908 (!oldtree && newtree &&
2909 same(current, newtree)) || /* 6 and 7 */
2910 (oldtree && newtree &&
2911 same(oldtree, newtree)) || /* 14 and 15 */
2912 (oldtree && newtree &&
2913 !same(oldtree, newtree) && /* 18 and 19 */
2914 same(current, newtree))) {
2915 return keep_entry(current, o);
2916 } else if (oldtree && !newtree && same(current, oldtree)) {
2917 /* 10 or 11 */
2918 return deleted_entry(oldtree, current, o);
2919 } else if (oldtree && newtree &&
2920 same(current, oldtree) && !same(current, newtree)) {
2921 /* 20 or 21 */
2922 return merged_entry(newtree, current, o);
2923 } else if (current && !oldtree && newtree &&
2924 S_ISSPARSEDIR(current->ce_mode) != S_ISSPARSEDIR(newtree->ce_mode) &&
2925 ce_stage(current) == 0) {
2927 * This case is a directory/file conflict across the sparse-index
2928 * boundary. When we are changing from one path to another via
2929 * 'git checkout', then we want to replace one entry with another
2930 * via merged_entry(). If there are staged changes, then we should
2931 * reject the merge instead.
2933 return merged_entry(newtree, current, o);
2934 } else if (S_ISSPARSEDIR(current->ce_mode)) {
2936 * The sparse directories differ, but we don't know whether that's
2937 * because of two different files in the directory being modified
2938 * (can be trivially merged) or if there is a real file conflict.
2939 * Merge the sparse directory by OID to compare file-by-file.
2941 return merged_sparse_dir(src, 3, o);
2942 } else
2943 return reject_merge(current, o);
2945 else if (newtree) {
2946 if (oldtree && !o->initial_checkout) {
2948 * deletion of the path was staged;
2950 if (same(oldtree, newtree))
2951 return 1;
2952 return reject_merge(oldtree, o);
2954 return merged_entry(newtree, current, o);
2956 return deleted_entry(oldtree, current, o);
2960 * Bind merge.
2962 * Keep the index entries at stage0, collapse stage1 but make sure
2963 * stage0 does not have anything there.
2965 int bind_merge(const struct cache_entry * const *src,
2966 struct unpack_trees_options *o)
2968 const struct cache_entry *old = src[0];
2969 const struct cache_entry *a = src[1];
2971 if (o->internal.merge_size != 1)
2972 return error("Cannot do a bind merge of %d trees",
2973 o->internal.merge_size);
2974 if (a && old)
2975 return o->quiet ? -1 :
2976 error(ERRORMSG(o, ERROR_BIND_OVERLAP),
2977 super_prefixed(a->name, o->super_prefix),
2978 super_prefixed(old->name, o->super_prefix));
2979 if (!a)
2980 return keep_entry(old, o);
2981 else
2982 return merged_entry(a, NULL, o);
2986 * One-way merge.
2988 * The rule is:
2989 * - take the stat information from stage0, take the data from stage1
2991 int oneway_merge(const struct cache_entry * const *src,
2992 struct unpack_trees_options *o)
2994 const struct cache_entry *old = src[0];
2995 const struct cache_entry *a = src[1];
2997 if (o->internal.merge_size != 1)
2998 return error("Cannot do a oneway merge of %d trees",
2999 o->internal.merge_size);
3001 if (!a || a == o->df_conflict_entry)
3002 return deleted_entry(old, old, o);
3004 if (old && same(old, a)) {
3005 int update = 0;
3006 if (o->reset && o->update && !ce_uptodate(old) && !ce_skip_worktree(old) &&
3007 !(old->ce_flags & CE_FSMONITOR_VALID)) {
3008 struct stat st;
3009 if (lstat(old->name, &st) ||
3010 ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE))
3011 update |= CE_UPDATE;
3013 if (o->update && S_ISGITLINK(old->ce_mode) &&
3014 should_update_submodules() && !verify_uptodate(old, o))
3015 update |= CE_UPDATE;
3016 add_entry(o, old, update, CE_STAGEMASK);
3017 return 0;
3019 return merged_entry(a, old, o);
3023 * Merge worktree and untracked entries in a stash entry.
3025 * Ignore all index entries. Collapse remaining trees but make sure that they
3026 * don't have any conflicting files.
3028 int stash_worktree_untracked_merge(const struct cache_entry * const *src,
3029 struct unpack_trees_options *o)
3031 const struct cache_entry *worktree = src[1];
3032 const struct cache_entry *untracked = src[2];
3034 if (o->internal.merge_size != 2)
3035 BUG("invalid merge_size: %d", o->internal.merge_size);
3037 if (worktree && untracked)
3038 return error(_("worktree and untracked commit have duplicate entries: %s"),
3039 super_prefixed(worktree->name, o->super_prefix));
3041 return merged_entry(worktree ? worktree : untracked, NULL, o);