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