Git 2.18.5
[git/debian.git] / unpack-trees.c
blob8c246a1db3887a750e919feedfb3b499bed4740f
1 #define NO_THE_INDEX_COMPATIBILITY_MACROS
2 #include "cache.h"
3 #include "argv-array.h"
4 #include "repository.h"
5 #include "config.h"
6 #include "dir.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 "dir.h"
16 #include "submodule.h"
17 #include "submodule-config.h"
18 #include "fsmonitor.h"
19 #include "fetch-object.h"
22 * Error messages expected by scripts out of plumbing commands such as
23 * read-tree. Non-scripted Porcelain is not required to use these messages
24 * and in fact are encouraged to reword them to better suit their particular
25 * situation better. See how "git checkout" and "git merge" replaces
26 * them using setup_unpack_trees_porcelain(), for example.
28 static const char *unpack_plumbing_errors[NB_UNPACK_TREES_ERROR_TYPES] = {
29 /* ERROR_WOULD_OVERWRITE */
30 "Entry '%s' would be overwritten by merge. Cannot merge.",
32 /* ERROR_NOT_UPTODATE_FILE */
33 "Entry '%s' not uptodate. Cannot merge.",
35 /* ERROR_NOT_UPTODATE_DIR */
36 "Updating '%s' would lose untracked files in it",
38 /* ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN */
39 "Untracked working tree file '%s' would be overwritten by merge.",
41 /* ERROR_WOULD_LOSE_UNTRACKED_REMOVED */
42 "Untracked working tree file '%s' would be removed by merge.",
44 /* ERROR_BIND_OVERLAP */
45 "Entry '%s' overlaps with '%s'. Cannot bind.",
47 /* ERROR_SPARSE_NOT_UPTODATE_FILE */
48 "Entry '%s' not uptodate. Cannot update sparse checkout.",
50 /* ERROR_WOULD_LOSE_ORPHANED_OVERWRITTEN */
51 "Working tree file '%s' would be overwritten by sparse checkout update.",
53 /* ERROR_WOULD_LOSE_ORPHANED_REMOVED */
54 "Working tree file '%s' would be removed by sparse checkout update.",
56 /* ERROR_WOULD_LOSE_SUBMODULE */
57 "Submodule '%s' cannot checkout new HEAD.",
60 #define ERRORMSG(o,type) \
61 ( ((o) && (o)->msgs[(type)]) \
62 ? ((o)->msgs[(type)]) \
63 : (unpack_plumbing_errors[(type)]) )
65 static const char *super_prefixed(const char *path)
68 * It is necessary and sufficient to have two static buffers
69 * here, as the return value of this function is fed to
70 * error() using the unpack_*_errors[] templates we see above.
72 static struct strbuf buf[2] = {STRBUF_INIT, STRBUF_INIT};
73 static int super_prefix_len = -1;
74 static unsigned idx = ARRAY_SIZE(buf) - 1;
76 if (super_prefix_len < 0) {
77 const char *super_prefix = get_super_prefix();
78 if (!super_prefix) {
79 super_prefix_len = 0;
80 } else {
81 int i;
82 for (i = 0; i < ARRAY_SIZE(buf); i++)
83 strbuf_addstr(&buf[i], super_prefix);
84 super_prefix_len = buf[0].len;
88 if (!super_prefix_len)
89 return path;
91 if (++idx >= ARRAY_SIZE(buf))
92 idx = 0;
94 strbuf_setlen(&buf[idx], super_prefix_len);
95 strbuf_addstr(&buf[idx], path);
97 return buf[idx].buf;
100 void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,
101 const char *cmd)
103 int i;
104 const char **msgs = opts->msgs;
105 const char *msg;
107 argv_array_init(&opts->msgs_to_free);
109 if (!strcmp(cmd, "checkout"))
110 msg = advice_commit_before_merge
111 ? _("Your local changes to the following files would be overwritten by checkout:\n%%s"
112 "Please commit your changes or stash them before you switch branches.")
113 : _("Your local changes to the following files would be overwritten by checkout:\n%%s");
114 else if (!strcmp(cmd, "merge"))
115 msg = advice_commit_before_merge
116 ? _("Your local changes to the following files would be overwritten by merge:\n%%s"
117 "Please commit your changes or stash them before you merge.")
118 : _("Your local changes to the following files would be overwritten by merge:\n%%s");
119 else
120 msg = advice_commit_before_merge
121 ? _("Your local changes to the following files would be overwritten by %s:\n%%s"
122 "Please commit your changes or stash them before you %s.")
123 : _("Your local changes to the following files would be overwritten by %s:\n%%s");
124 msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOT_UPTODATE_FILE] =
125 argv_array_pushf(&opts->msgs_to_free, msg, cmd, cmd);
127 msgs[ERROR_NOT_UPTODATE_DIR] =
128 _("Updating the following directories would lose untracked files in them:\n%s");
130 if (!strcmp(cmd, "checkout"))
131 msg = advice_commit_before_merge
132 ? _("The following untracked working tree files would be removed by checkout:\n%%s"
133 "Please move or remove them before you switch branches.")
134 : _("The following untracked working tree files would be removed by checkout:\n%%s");
135 else if (!strcmp(cmd, "merge"))
136 msg = advice_commit_before_merge
137 ? _("The following untracked working tree files would be removed by merge:\n%%s"
138 "Please move or remove them before you merge.")
139 : _("The following untracked working tree files would be removed by merge:\n%%s");
140 else
141 msg = advice_commit_before_merge
142 ? _("The following untracked working tree files would be removed by %s:\n%%s"
143 "Please move or remove them before you %s.")
144 : _("The following untracked working tree files would be removed by %s:\n%%s");
145 msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED] =
146 argv_array_pushf(&opts->msgs_to_free, msg, cmd, cmd);
148 if (!strcmp(cmd, "checkout"))
149 msg = advice_commit_before_merge
150 ? _("The following untracked working tree files would be overwritten by checkout:\n%%s"
151 "Please move or remove them before you switch branches.")
152 : _("The following untracked working tree files would be overwritten by checkout:\n%%s");
153 else if (!strcmp(cmd, "merge"))
154 msg = advice_commit_before_merge
155 ? _("The following untracked working tree files would be overwritten by merge:\n%%s"
156 "Please move or remove them before you merge.")
157 : _("The following untracked working tree files would be overwritten by merge:\n%%s");
158 else
159 msg = advice_commit_before_merge
160 ? _("The following untracked working tree files would be overwritten by %s:\n%%s"
161 "Please move or remove them before you %s.")
162 : _("The following untracked working tree files would be overwritten by %s:\n%%s");
163 msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN] =
164 argv_array_pushf(&opts->msgs_to_free, msg, cmd, cmd);
167 * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
168 * cannot easily display it as a list.
170 msgs[ERROR_BIND_OVERLAP] = _("Entry '%s' overlaps with '%s'. Cannot bind.");
172 msgs[ERROR_SPARSE_NOT_UPTODATE_FILE] =
173 _("Cannot update sparse checkout: the following entries are not up to date:\n%s");
174 msgs[ERROR_WOULD_LOSE_ORPHANED_OVERWRITTEN] =
175 _("The following working tree files would be overwritten by sparse checkout update:\n%s");
176 msgs[ERROR_WOULD_LOSE_ORPHANED_REMOVED] =
177 _("The following working tree files would be removed by sparse checkout update:\n%s");
178 msgs[ERROR_WOULD_LOSE_SUBMODULE] =
179 _("Cannot update submodule:\n%s");
181 opts->show_all_errors = 1;
182 /* rejected paths may not have a static buffer */
183 for (i = 0; i < ARRAY_SIZE(opts->unpack_rejects); i++)
184 opts->unpack_rejects[i].strdup_strings = 1;
187 void clear_unpack_trees_porcelain(struct unpack_trees_options *opts)
189 argv_array_clear(&opts->msgs_to_free);
190 memset(opts->msgs, 0, sizeof(opts->msgs));
193 static int do_add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
194 unsigned int set, unsigned int clear)
196 clear |= CE_HASHED;
198 if (set & CE_REMOVE)
199 set |= CE_WT_REMOVE;
201 ce->ce_flags = (ce->ce_flags & ~clear) | set;
202 return add_index_entry(&o->result, ce,
203 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
206 static struct cache_entry *dup_entry(const struct cache_entry *ce)
208 unsigned int size = ce_size(ce);
209 struct cache_entry *new_entry = xmalloc(size);
211 memcpy(new_entry, ce, size);
212 return new_entry;
215 static void add_entry(struct unpack_trees_options *o,
216 const struct cache_entry *ce,
217 unsigned int set, unsigned int clear)
219 do_add_entry(o, dup_entry(ce), set, clear);
223 * add error messages on path <path>
224 * corresponding to the type <e> with the message <msg>
225 * indicating if it should be display in porcelain or not
227 static int add_rejected_path(struct unpack_trees_options *o,
228 enum unpack_trees_error_types e,
229 const char *path)
231 if (!o->show_all_errors)
232 return error(ERRORMSG(o, e), super_prefixed(path));
235 * Otherwise, insert in a list for future display by
236 * display_error_msgs()
238 string_list_append(&o->unpack_rejects[e], path);
239 return -1;
243 * display all the error messages stored in a nice way
245 static void display_error_msgs(struct unpack_trees_options *o)
247 int e, i;
248 int something_displayed = 0;
249 for (e = 0; e < NB_UNPACK_TREES_ERROR_TYPES; e++) {
250 struct string_list *rejects = &o->unpack_rejects[e];
251 if (rejects->nr > 0) {
252 struct strbuf path = STRBUF_INIT;
253 something_displayed = 1;
254 for (i = 0; i < rejects->nr; i++)
255 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
256 error(ERRORMSG(o, e), super_prefixed(path.buf));
257 strbuf_release(&path);
259 string_list_clear(rejects, 0);
261 if (something_displayed)
262 fprintf(stderr, _("Aborting\n"));
265 static int check_submodule_move_head(const struct cache_entry *ce,
266 const char *old_id,
267 const char *new_id,
268 struct unpack_trees_options *o)
270 unsigned flags = SUBMODULE_MOVE_HEAD_DRY_RUN;
271 const struct submodule *sub = submodule_from_ce(ce);
273 if (!sub)
274 return 0;
276 if (o->reset)
277 flags |= SUBMODULE_MOVE_HEAD_FORCE;
279 if (submodule_move_head(ce->name, old_id, new_id, flags))
280 return o->gently ? -1 :
281 add_rejected_path(o, ERROR_WOULD_LOSE_SUBMODULE, ce->name);
282 return 0;
286 * Preform the loading of the repository's gitmodules file. This function is
287 * used by 'check_update()' to perform loading of the gitmodules file in two
288 * differnt situations:
289 * (1) before removing entries from the working tree if the gitmodules file has
290 * been marked for removal. This situation is specified by 'state' == NULL.
291 * (2) before checking out entries to the working tree if the gitmodules file
292 * has been marked for update. This situation is specified by 'state' != NULL.
294 static void load_gitmodules_file(struct index_state *index,
295 struct checkout *state)
297 int pos = index_name_pos(index, GITMODULES_FILE, strlen(GITMODULES_FILE));
299 if (pos >= 0) {
300 struct cache_entry *ce = index->cache[pos];
301 if (!state && ce->ce_flags & CE_WT_REMOVE) {
302 repo_read_gitmodules(the_repository);
303 } else if (state && (ce->ce_flags & CE_UPDATE)) {
304 submodule_free(the_repository);
305 checkout_entry(ce, state, NULL);
306 repo_read_gitmodules(the_repository);
312 * Unlink the last component and schedule the leading directories for
313 * removal, such that empty directories get removed.
315 static void unlink_entry(const struct cache_entry *ce)
317 const struct submodule *sub = submodule_from_ce(ce);
318 if (sub) {
319 /* state.force is set at the caller. */
320 submodule_move_head(ce->name, "HEAD", NULL,
321 SUBMODULE_MOVE_HEAD_FORCE);
323 if (!check_leading_path(ce->name, ce_namelen(ce)))
324 return;
325 if (remove_or_warn(ce->ce_mode, ce->name))
326 return;
327 schedule_dir_for_removal(ce->name, ce_namelen(ce));
330 static struct progress *get_progress(struct unpack_trees_options *o)
332 unsigned cnt = 0, total = 0;
333 struct index_state *index = &o->result;
335 if (!o->update || !o->verbose_update)
336 return NULL;
338 for (; cnt < index->cache_nr; cnt++) {
339 const struct cache_entry *ce = index->cache[cnt];
340 if (ce->ce_flags & (CE_UPDATE | CE_WT_REMOVE))
341 total++;
344 return start_delayed_progress(_("Checking out files"), total);
347 static int check_updates(struct unpack_trees_options *o)
349 unsigned cnt = 0;
350 int errs = 0;
351 struct progress *progress = NULL;
352 struct index_state *index = &o->result;
353 struct checkout state = CHECKOUT_INIT;
354 int i;
356 state.force = 1;
357 state.quiet = 1;
358 state.refresh_cache = 1;
359 state.istate = index;
361 progress = get_progress(o);
363 /* Start with clean cache to avoid using any possibly outdated info. */
364 invalidate_lstat_cache();
366 if (o->update)
367 git_attr_set_direction(GIT_ATTR_CHECKOUT, index);
369 if (should_update_submodules() && o->update && !o->dry_run)
370 load_gitmodules_file(index, NULL);
372 for (i = 0; i < index->cache_nr; i++) {
373 const struct cache_entry *ce = index->cache[i];
375 if (ce->ce_flags & CE_WT_REMOVE) {
376 display_progress(progress, ++cnt);
377 if (o->update && !o->dry_run)
378 unlink_entry(ce);
381 remove_marked_cache_entries(index);
382 remove_scheduled_dirs();
384 if (should_update_submodules() && o->update && !o->dry_run)
385 load_gitmodules_file(index, &state);
387 enable_delayed_checkout(&state);
388 if (repository_format_partial_clone && o->update && !o->dry_run) {
390 * Prefetch the objects that are to be checked out in the loop
391 * below.
393 struct oid_array to_fetch = OID_ARRAY_INIT;
394 int fetch_if_missing_store = fetch_if_missing;
395 fetch_if_missing = 0;
396 for (i = 0; i < index->cache_nr; i++) {
397 struct cache_entry *ce = index->cache[i];
398 if ((ce->ce_flags & CE_UPDATE) &&
399 !S_ISGITLINK(ce->ce_mode)) {
400 if (!has_object_file(&ce->oid))
401 oid_array_append(&to_fetch, &ce->oid);
404 if (to_fetch.nr)
405 fetch_objects(repository_format_partial_clone,
406 &to_fetch);
407 fetch_if_missing = fetch_if_missing_store;
408 oid_array_clear(&to_fetch);
410 for (i = 0; i < index->cache_nr; i++) {
411 struct cache_entry *ce = index->cache[i];
413 if (ce->ce_flags & CE_UPDATE) {
414 if (ce->ce_flags & CE_WT_REMOVE)
415 BUG("both update and delete flags are set on %s",
416 ce->name);
417 display_progress(progress, ++cnt);
418 ce->ce_flags &= ~CE_UPDATE;
419 if (o->update && !o->dry_run) {
420 errs |= checkout_entry(ce, &state, NULL);
424 stop_progress(&progress);
425 errs |= finish_delayed_checkout(&state);
426 if (o->update)
427 git_attr_set_direction(GIT_ATTR_CHECKIN, NULL);
428 return errs != 0;
431 static int verify_uptodate_sparse(const struct cache_entry *ce,
432 struct unpack_trees_options *o);
433 static int verify_absent_sparse(const struct cache_entry *ce,
434 enum unpack_trees_error_types,
435 struct unpack_trees_options *o);
437 static int apply_sparse_checkout(struct index_state *istate,
438 struct cache_entry *ce,
439 struct unpack_trees_options *o)
441 int was_skip_worktree = ce_skip_worktree(ce);
443 if (ce->ce_flags & CE_NEW_SKIP_WORKTREE)
444 ce->ce_flags |= CE_SKIP_WORKTREE;
445 else
446 ce->ce_flags &= ~CE_SKIP_WORKTREE;
447 if (was_skip_worktree != ce_skip_worktree(ce)) {
448 ce->ce_flags |= CE_UPDATE_IN_BASE;
449 mark_fsmonitor_invalid(istate, ce);
450 istate->cache_changed |= CE_ENTRY_CHANGED;
454 * if (!was_skip_worktree && !ce_skip_worktree()) {
455 * This is perfectly normal. Move on;
460 * Merge strategies may set CE_UPDATE|CE_REMOVE outside checkout
461 * area as a result of ce_skip_worktree() shortcuts in
462 * verify_absent() and verify_uptodate().
463 * Make sure they don't modify worktree if they are already
464 * outside checkout area
466 if (was_skip_worktree && ce_skip_worktree(ce)) {
467 ce->ce_flags &= ~CE_UPDATE;
470 * By default, when CE_REMOVE is on, CE_WT_REMOVE is also
471 * on to get that file removed from both index and worktree.
472 * If that file is already outside worktree area, don't
473 * bother remove it.
475 if (ce->ce_flags & CE_REMOVE)
476 ce->ce_flags &= ~CE_WT_REMOVE;
479 if (!was_skip_worktree && ce_skip_worktree(ce)) {
481 * If CE_UPDATE is set, verify_uptodate() must be called already
482 * also stat info may have lost after merged_entry() so calling
483 * verify_uptodate() again may fail
485 if (!(ce->ce_flags & CE_UPDATE) && verify_uptodate_sparse(ce, o))
486 return -1;
487 ce->ce_flags |= CE_WT_REMOVE;
488 ce->ce_flags &= ~CE_UPDATE;
490 if (was_skip_worktree && !ce_skip_worktree(ce)) {
491 if (verify_absent_sparse(ce, ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o))
492 return -1;
493 ce->ce_flags |= CE_UPDATE;
495 return 0;
498 static inline int call_unpack_fn(const struct cache_entry * const *src,
499 struct unpack_trees_options *o)
501 int ret = o->fn(src, o);
502 if (ret > 0)
503 ret = 0;
504 return ret;
507 static void mark_ce_used(struct cache_entry *ce, struct unpack_trees_options *o)
509 ce->ce_flags |= CE_UNPACKED;
511 if (o->cache_bottom < o->src_index->cache_nr &&
512 o->src_index->cache[o->cache_bottom] == ce) {
513 int bottom = o->cache_bottom;
514 while (bottom < o->src_index->cache_nr &&
515 o->src_index->cache[bottom]->ce_flags & CE_UNPACKED)
516 bottom++;
517 o->cache_bottom = bottom;
521 static void mark_all_ce_unused(struct index_state *index)
523 int i;
524 for (i = 0; i < index->cache_nr; i++)
525 index->cache[i]->ce_flags &= ~(CE_UNPACKED | CE_ADDED | CE_NEW_SKIP_WORKTREE);
528 static int locate_in_src_index(const struct cache_entry *ce,
529 struct unpack_trees_options *o)
531 struct index_state *index = o->src_index;
532 int len = ce_namelen(ce);
533 int pos = index_name_pos(index, ce->name, len);
534 if (pos < 0)
535 pos = -1 - pos;
536 return pos;
540 * We call unpack_index_entry() with an unmerged cache entry
541 * only in diff-index, and it wants a single callback. Skip
542 * the other unmerged entry with the same name.
544 static void mark_ce_used_same_name(struct cache_entry *ce,
545 struct unpack_trees_options *o)
547 struct index_state *index = o->src_index;
548 int len = ce_namelen(ce);
549 int pos;
551 for (pos = locate_in_src_index(ce, o); pos < index->cache_nr; pos++) {
552 struct cache_entry *next = index->cache[pos];
553 if (len != ce_namelen(next) ||
554 memcmp(ce->name, next->name, len))
555 break;
556 mark_ce_used(next, o);
560 static struct cache_entry *next_cache_entry(struct unpack_trees_options *o)
562 const struct index_state *index = o->src_index;
563 int pos = o->cache_bottom;
565 while (pos < index->cache_nr) {
566 struct cache_entry *ce = index->cache[pos];
567 if (!(ce->ce_flags & CE_UNPACKED))
568 return ce;
569 pos++;
571 return NULL;
574 static void add_same_unmerged(const struct cache_entry *ce,
575 struct unpack_trees_options *o)
577 struct index_state *index = o->src_index;
578 int len = ce_namelen(ce);
579 int pos = index_name_pos(index, ce->name, len);
581 if (0 <= pos)
582 die("programming error in a caller of mark_ce_used_same_name");
583 for (pos = -pos - 1; pos < index->cache_nr; pos++) {
584 struct cache_entry *next = index->cache[pos];
585 if (len != ce_namelen(next) ||
586 memcmp(ce->name, next->name, len))
587 break;
588 add_entry(o, next, 0, 0);
589 mark_ce_used(next, o);
593 static int unpack_index_entry(struct cache_entry *ce,
594 struct unpack_trees_options *o)
596 const struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
597 int ret;
599 src[0] = ce;
601 mark_ce_used(ce, o);
602 if (ce_stage(ce)) {
603 if (o->skip_unmerged) {
604 add_entry(o, ce, 0, 0);
605 return 0;
608 ret = call_unpack_fn(src, o);
609 if (ce_stage(ce))
610 mark_ce_used_same_name(ce, o);
611 return ret;
614 static int find_cache_pos(struct traverse_info *, const struct name_entry *);
616 static void restore_cache_bottom(struct traverse_info *info, int bottom)
618 struct unpack_trees_options *o = info->data;
620 if (o->diff_index_cached)
621 return;
622 o->cache_bottom = bottom;
625 static int switch_cache_bottom(struct traverse_info *info)
627 struct unpack_trees_options *o = info->data;
628 int ret, pos;
630 if (o->diff_index_cached)
631 return 0;
632 ret = o->cache_bottom;
633 pos = find_cache_pos(info->prev, &info->name);
635 if (pos < -1)
636 o->cache_bottom = -2 - pos;
637 else if (pos < 0)
638 o->cache_bottom = o->src_index->cache_nr;
639 return ret;
642 static inline int are_same_oid(struct name_entry *name_j, struct name_entry *name_k)
644 return name_j->oid && name_k->oid && !oidcmp(name_j->oid, name_k->oid);
647 static int traverse_trees_recursive(int n, unsigned long dirmask,
648 unsigned long df_conflicts,
649 struct name_entry *names,
650 struct traverse_info *info)
652 int i, ret, bottom;
653 int nr_buf = 0;
654 struct tree_desc t[MAX_UNPACK_TREES];
655 void *buf[MAX_UNPACK_TREES];
656 struct traverse_info newinfo;
657 struct name_entry *p;
659 p = names;
660 while (!p->mode)
661 p++;
663 newinfo = *info;
664 newinfo.prev = info;
665 newinfo.pathspec = info->pathspec;
666 newinfo.name = *p;
667 newinfo.pathlen += tree_entry_len(p) + 1;
668 newinfo.df_conflicts |= df_conflicts;
671 * Fetch the tree from the ODB for each peer directory in the
672 * n commits.
674 * For 2- and 3-way traversals, we try to avoid hitting the
675 * ODB twice for the same OID. This should yield a nice speed
676 * up in checkouts and merges when the commits are similar.
678 * We don't bother doing the full O(n^2) search for larger n,
679 * because wider traversals don't happen that often and we
680 * avoid the search setup.
682 * When 2 peer OIDs are the same, we just copy the tree
683 * descriptor data. This implicitly borrows the buffer
684 * data from the earlier cell.
686 for (i = 0; i < n; i++, dirmask >>= 1) {
687 if (i > 0 && are_same_oid(&names[i], &names[i - 1]))
688 t[i] = t[i - 1];
689 else if (i > 1 && are_same_oid(&names[i], &names[i - 2]))
690 t[i] = t[i - 2];
691 else {
692 const struct object_id *oid = NULL;
693 if (dirmask & 1)
694 oid = names[i].oid;
695 buf[nr_buf++] = fill_tree_descriptor(t + i, oid);
699 bottom = switch_cache_bottom(&newinfo);
700 ret = traverse_trees(n, t, &newinfo);
701 restore_cache_bottom(&newinfo, bottom);
703 for (i = 0; i < nr_buf; i++)
704 free(buf[i]);
706 return ret;
710 * Compare the traverse-path to the cache entry without actually
711 * having to generate the textual representation of the traverse
712 * path.
714 * NOTE! This *only* compares up to the size of the traverse path
715 * itself - the caller needs to do the final check for the cache
716 * entry having more data at the end!
718 static int do_compare_entry_piecewise(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
720 int len, pathlen, ce_len;
721 const char *ce_name;
723 if (info->prev) {
724 int cmp = do_compare_entry_piecewise(ce, info->prev,
725 &info->name);
726 if (cmp)
727 return cmp;
729 pathlen = info->pathlen;
730 ce_len = ce_namelen(ce);
732 /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
733 if (ce_len < pathlen)
734 return -1;
736 ce_len -= pathlen;
737 ce_name = ce->name + pathlen;
739 len = tree_entry_len(n);
740 return df_name_compare(ce_name, ce_len, S_IFREG, n->path, len, n->mode);
743 static int do_compare_entry(const struct cache_entry *ce,
744 const struct traverse_info *info,
745 const struct name_entry *n)
747 int len, pathlen, ce_len;
748 const char *ce_name;
749 int cmp;
752 * If we have not precomputed the traverse path, it is quicker
753 * to avoid doing so. But if we have precomputed it,
754 * it is quicker to use the precomputed version.
756 if (!info->traverse_path)
757 return do_compare_entry_piecewise(ce, info, n);
759 cmp = strncmp(ce->name, info->traverse_path, info->pathlen);
760 if (cmp)
761 return cmp;
763 pathlen = info->pathlen;
764 ce_len = ce_namelen(ce);
766 if (ce_len < pathlen)
767 return -1;
769 ce_len -= pathlen;
770 ce_name = ce->name + pathlen;
772 len = tree_entry_len(n);
773 return df_name_compare(ce_name, ce_len, S_IFREG, n->path, len, n->mode);
776 static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
778 int cmp = do_compare_entry(ce, info, n);
779 if (cmp)
780 return cmp;
783 * Even if the beginning compared identically, the ce should
784 * compare as bigger than a directory leading up to it!
786 return ce_namelen(ce) > traverse_path_len(info, n);
789 static int ce_in_traverse_path(const struct cache_entry *ce,
790 const struct traverse_info *info)
792 if (!info->prev)
793 return 1;
794 if (do_compare_entry(ce, info->prev, &info->name))
795 return 0;
797 * If ce (blob) is the same name as the path (which is a tree
798 * we will be descending into), it won't be inside it.
800 return (info->pathlen < ce_namelen(ce));
803 static struct cache_entry *create_ce_entry(const struct traverse_info *info, const struct name_entry *n, int stage)
805 int len = traverse_path_len(info, n);
806 struct cache_entry *ce = xcalloc(1, cache_entry_size(len));
808 ce->ce_mode = create_ce_mode(n->mode);
809 ce->ce_flags = create_ce_flags(stage);
810 ce->ce_namelen = len;
811 oidcpy(&ce->oid, n->oid);
812 make_traverse_path(ce->name, info, n);
814 return ce;
817 static int unpack_nondirectories(int n, unsigned long mask,
818 unsigned long dirmask,
819 struct cache_entry **src,
820 const struct name_entry *names,
821 const struct traverse_info *info)
823 int i;
824 struct unpack_trees_options *o = info->data;
825 unsigned long conflicts = info->df_conflicts | dirmask;
827 /* Do we have *only* directories? Nothing to do */
828 if (mask == dirmask && !src[0])
829 return 0;
832 * Ok, we've filled in up to any potential index entry in src[0],
833 * now do the rest.
835 for (i = 0; i < n; i++) {
836 int stage;
837 unsigned int bit = 1ul << i;
838 if (conflicts & bit) {
839 src[i + o->merge] = o->df_conflict_entry;
840 continue;
842 if (!(mask & bit))
843 continue;
844 if (!o->merge)
845 stage = 0;
846 else if (i + 1 < o->head_idx)
847 stage = 1;
848 else if (i + 1 > o->head_idx)
849 stage = 3;
850 else
851 stage = 2;
852 src[i + o->merge] = create_ce_entry(info, names + i, stage);
855 if (o->merge) {
856 int rc = call_unpack_fn((const struct cache_entry * const *)src,
858 for (i = 0; i < n; i++) {
859 struct cache_entry *ce = src[i + o->merge];
860 if (ce != o->df_conflict_entry)
861 free(ce);
863 return rc;
866 for (i = 0; i < n; i++)
867 if (src[i] && src[i] != o->df_conflict_entry)
868 if (do_add_entry(o, src[i], 0, 0))
869 return -1;
871 return 0;
874 static int unpack_failed(struct unpack_trees_options *o, const char *message)
876 discard_index(&o->result);
877 if (!o->gently && !o->exiting_early) {
878 if (message)
879 return error("%s", message);
880 return -1;
882 return -1;
886 * The tree traversal is looking at name p. If we have a matching entry,
887 * return it. If name p is a directory in the index, do not return
888 * anything, as we will want to match it when the traversal descends into
889 * the directory.
891 static int find_cache_pos(struct traverse_info *info,
892 const struct name_entry *p)
894 int pos;
895 struct unpack_trees_options *o = info->data;
896 struct index_state *index = o->src_index;
897 int pfxlen = info->pathlen;
898 int p_len = tree_entry_len(p);
900 for (pos = o->cache_bottom; pos < index->cache_nr; pos++) {
901 const struct cache_entry *ce = index->cache[pos];
902 const char *ce_name, *ce_slash;
903 int cmp, ce_len;
905 if (ce->ce_flags & CE_UNPACKED) {
907 * cache_bottom entry is already unpacked, so
908 * we can never match it; don't check it
909 * again.
911 if (pos == o->cache_bottom)
912 ++o->cache_bottom;
913 continue;
915 if (!ce_in_traverse_path(ce, info)) {
917 * Check if we can skip future cache checks
918 * (because we're already past all possible
919 * entries in the traverse path).
921 if (info->traverse_path) {
922 if (strncmp(ce->name, info->traverse_path,
923 info->pathlen) > 0)
924 break;
926 continue;
928 ce_name = ce->name + pfxlen;
929 ce_slash = strchr(ce_name, '/');
930 if (ce_slash)
931 ce_len = ce_slash - ce_name;
932 else
933 ce_len = ce_namelen(ce) - pfxlen;
934 cmp = name_compare(p->path, p_len, ce_name, ce_len);
936 * Exact match; if we have a directory we need to
937 * delay returning it.
939 if (!cmp)
940 return ce_slash ? -2 - pos : pos;
941 if (0 < cmp)
942 continue; /* keep looking */
944 * ce_name sorts after p->path; could it be that we
945 * have files under p->path directory in the index?
946 * E.g. ce_name == "t-i", and p->path == "t"; we may
947 * have "t/a" in the index.
949 if (p_len < ce_len && !memcmp(ce_name, p->path, p_len) &&
950 ce_name[p_len] < '/')
951 continue; /* keep looking */
952 break;
954 return -1;
957 static struct cache_entry *find_cache_entry(struct traverse_info *info,
958 const struct name_entry *p)
960 int pos = find_cache_pos(info, p);
961 struct unpack_trees_options *o = info->data;
963 if (0 <= pos)
964 return o->src_index->cache[pos];
965 else
966 return NULL;
969 static void debug_path(struct traverse_info *info)
971 if (info->prev) {
972 debug_path(info->prev);
973 if (*info->prev->name.path)
974 putchar('/');
976 printf("%s", info->name.path);
979 static void debug_name_entry(int i, struct name_entry *n)
981 printf("ent#%d %06o %s\n", i,
982 n->path ? n->mode : 0,
983 n->path ? n->path : "(missing)");
986 static void debug_unpack_callback(int n,
987 unsigned long mask,
988 unsigned long dirmask,
989 struct name_entry *names,
990 struct traverse_info *info)
992 int i;
993 printf("* unpack mask %lu, dirmask %lu, cnt %d ",
994 mask, dirmask, n);
995 debug_path(info);
996 putchar('\n');
997 for (i = 0; i < n; i++)
998 debug_name_entry(i, names + i);
1001 static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1003 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1004 struct unpack_trees_options *o = info->data;
1005 const struct name_entry *p = names;
1007 /* Find first entry with a real name (we could use "mask" too) */
1008 while (!p->mode)
1009 p++;
1011 if (o->debug_unpack)
1012 debug_unpack_callback(n, mask, dirmask, names, info);
1014 /* Are we supposed to look at the index too? */
1015 if (o->merge) {
1016 while (1) {
1017 int cmp;
1018 struct cache_entry *ce;
1020 if (o->diff_index_cached)
1021 ce = next_cache_entry(o);
1022 else
1023 ce = find_cache_entry(info, p);
1025 if (!ce)
1026 break;
1027 cmp = compare_entry(ce, info, p);
1028 if (cmp < 0) {
1029 if (unpack_index_entry(ce, o) < 0)
1030 return unpack_failed(o, NULL);
1031 continue;
1033 if (!cmp) {
1034 if (ce_stage(ce)) {
1036 * If we skip unmerged index
1037 * entries, we'll skip this
1038 * entry *and* the tree
1039 * entries associated with it!
1041 if (o->skip_unmerged) {
1042 add_same_unmerged(ce, o);
1043 return mask;
1046 src[0] = ce;
1048 break;
1052 if (unpack_nondirectories(n, mask, dirmask, src, names, info) < 0)
1053 return -1;
1055 if (o->merge && src[0]) {
1056 if (ce_stage(src[0]))
1057 mark_ce_used_same_name(src[0], o);
1058 else
1059 mark_ce_used(src[0], o);
1062 /* Now handle any directories.. */
1063 if (dirmask) {
1064 /* special case: "diff-index --cached" looking at a tree */
1065 if (o->diff_index_cached &&
1066 n == 1 && dirmask == 1 && S_ISDIR(names->mode)) {
1067 int matches;
1068 matches = cache_tree_matches_traversal(o->src_index->cache_tree,
1069 names, info);
1071 * Everything under the name matches; skip the
1072 * entire hierarchy. diff_index_cached codepath
1073 * special cases D/F conflicts in such a way that
1074 * it does not do any look-ahead, so this is safe.
1076 if (matches) {
1077 o->cache_bottom += matches;
1078 return mask;
1082 if (traverse_trees_recursive(n, dirmask, mask & ~dirmask,
1083 names, info) < 0)
1084 return -1;
1085 return mask;
1088 return mask;
1091 static int clear_ce_flags_1(struct cache_entry **cache, int nr,
1092 struct strbuf *prefix,
1093 int select_mask, int clear_mask,
1094 struct exclude_list *el, int defval);
1096 /* Whole directory matching */
1097 static int clear_ce_flags_dir(struct cache_entry **cache, int nr,
1098 struct strbuf *prefix,
1099 char *basename,
1100 int select_mask, int clear_mask,
1101 struct exclude_list *el, int defval)
1103 struct cache_entry **cache_end;
1104 int dtype = DT_DIR;
1105 int ret = is_excluded_from_list(prefix->buf, prefix->len,
1106 basename, &dtype, el, &the_index);
1107 int rc;
1109 strbuf_addch(prefix, '/');
1111 /* If undecided, use matching result of parent dir in defval */
1112 if (ret < 0)
1113 ret = defval;
1115 for (cache_end = cache; cache_end != cache + nr; cache_end++) {
1116 struct cache_entry *ce = *cache_end;
1117 if (strncmp(ce->name, prefix->buf, prefix->len))
1118 break;
1122 * TODO: check el, if there are no patterns that may conflict
1123 * with ret (iow, we know in advance the incl/excl
1124 * decision for the entire directory), clear flag here without
1125 * calling clear_ce_flags_1(). That function will call
1126 * the expensive is_excluded_from_list() on every entry.
1128 rc = clear_ce_flags_1(cache, cache_end - cache,
1129 prefix,
1130 select_mask, clear_mask,
1131 el, ret);
1132 strbuf_setlen(prefix, prefix->len - 1);
1133 return rc;
1137 * Traverse the index, find every entry that matches according to
1138 * o->el. Do "ce_flags &= ~clear_mask" on those entries. Return the
1139 * number of traversed entries.
1141 * If select_mask is non-zero, only entries whose ce_flags has on of
1142 * those bits enabled are traversed.
1144 * cache : pointer to an index entry
1145 * prefix_len : an offset to its path
1147 * The current path ("prefix") including the trailing '/' is
1148 * cache[0]->name[0..(prefix_len-1)]
1149 * Top level path has prefix_len zero.
1151 static int clear_ce_flags_1(struct cache_entry **cache, int nr,
1152 struct strbuf *prefix,
1153 int select_mask, int clear_mask,
1154 struct exclude_list *el, int defval)
1156 struct cache_entry **cache_end = cache + nr;
1159 * Process all entries that have the given prefix and meet
1160 * select_mask condition
1162 while(cache != cache_end) {
1163 struct cache_entry *ce = *cache;
1164 const char *name, *slash;
1165 int len, dtype, ret;
1167 if (select_mask && !(ce->ce_flags & select_mask)) {
1168 cache++;
1169 continue;
1172 if (prefix->len && strncmp(ce->name, prefix->buf, prefix->len))
1173 break;
1175 name = ce->name + prefix->len;
1176 slash = strchr(name, '/');
1178 /* If it's a directory, try whole directory match first */
1179 if (slash) {
1180 int processed;
1182 len = slash - name;
1183 strbuf_add(prefix, name, len);
1185 processed = clear_ce_flags_dir(cache, cache_end - cache,
1186 prefix,
1187 prefix->buf + prefix->len - len,
1188 select_mask, clear_mask,
1189 el, defval);
1191 /* clear_c_f_dir eats a whole dir already? */
1192 if (processed) {
1193 cache += processed;
1194 strbuf_setlen(prefix, prefix->len - len);
1195 continue;
1198 strbuf_addch(prefix, '/');
1199 cache += clear_ce_flags_1(cache, cache_end - cache,
1200 prefix,
1201 select_mask, clear_mask, el, defval);
1202 strbuf_setlen(prefix, prefix->len - len - 1);
1203 continue;
1206 /* Non-directory */
1207 dtype = ce_to_dtype(ce);
1208 ret = is_excluded_from_list(ce->name, ce_namelen(ce),
1209 name, &dtype, el, &the_index);
1210 if (ret < 0)
1211 ret = defval;
1212 if (ret > 0)
1213 ce->ce_flags &= ~clear_mask;
1214 cache++;
1216 return nr - (cache_end - cache);
1219 static int clear_ce_flags(struct cache_entry **cache, int nr,
1220 int select_mask, int clear_mask,
1221 struct exclude_list *el)
1223 static struct strbuf prefix = STRBUF_INIT;
1225 strbuf_reset(&prefix);
1227 return clear_ce_flags_1(cache, nr,
1228 &prefix,
1229 select_mask, clear_mask,
1230 el, 0);
1234 * Set/Clear CE_NEW_SKIP_WORKTREE according to $GIT_DIR/info/sparse-checkout
1236 static void mark_new_skip_worktree(struct exclude_list *el,
1237 struct index_state *the_index,
1238 int select_flag, int skip_wt_flag)
1240 int i;
1243 * 1. Pretend the narrowest worktree: only unmerged entries
1244 * are checked out
1246 for (i = 0; i < the_index->cache_nr; i++) {
1247 struct cache_entry *ce = the_index->cache[i];
1249 if (select_flag && !(ce->ce_flags & select_flag))
1250 continue;
1252 if (!ce_stage(ce))
1253 ce->ce_flags |= skip_wt_flag;
1254 else
1255 ce->ce_flags &= ~skip_wt_flag;
1259 * 2. Widen worktree according to sparse-checkout file.
1260 * Matched entries will have skip_wt_flag cleared (i.e. "in")
1262 clear_ce_flags(the_index->cache, the_index->cache_nr,
1263 select_flag, skip_wt_flag, el);
1266 static int verify_absent(const struct cache_entry *,
1267 enum unpack_trees_error_types,
1268 struct unpack_trees_options *);
1270 * N-way merge "len" trees. Returns 0 on success, -1 on failure to manipulate the
1271 * resulting index, -2 on failure to reflect the changes to the work tree.
1273 * CE_ADDED, CE_UNPACKED and CE_NEW_SKIP_WORKTREE are used internally
1275 int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
1277 int i, ret;
1278 static struct cache_entry *dfc;
1279 struct exclude_list el;
1281 if (len > MAX_UNPACK_TREES)
1282 die("unpack_trees takes at most %d trees", MAX_UNPACK_TREES);
1284 memset(&el, 0, sizeof(el));
1285 if (!core_apply_sparse_checkout || !o->update)
1286 o->skip_sparse_checkout = 1;
1287 if (!o->skip_sparse_checkout) {
1288 char *sparse = git_pathdup("info/sparse-checkout");
1289 if (add_excludes_from_file_to_list(sparse, "", 0, &el, NULL) < 0)
1290 o->skip_sparse_checkout = 1;
1291 else
1292 o->el = &el;
1293 free(sparse);
1296 memset(&o->result, 0, sizeof(o->result));
1297 o->result.initialized = 1;
1298 o->result.timestamp.sec = o->src_index->timestamp.sec;
1299 o->result.timestamp.nsec = o->src_index->timestamp.nsec;
1300 o->result.version = o->src_index->version;
1301 if (!o->src_index->split_index) {
1302 o->result.split_index = NULL;
1303 } else if (o->src_index == o->dst_index) {
1305 * o->dst_index (and thus o->src_index) will be discarded
1306 * and overwritten with o->result at the end of this function,
1307 * so just use src_index's split_index to avoid having to
1308 * create a new one.
1310 o->result.split_index = o->src_index->split_index;
1311 o->result.split_index->refcount++;
1312 } else {
1313 o->result.split_index = init_split_index(&o->result);
1315 oidcpy(&o->result.oid, &o->src_index->oid);
1316 o->merge_size = len;
1317 mark_all_ce_unused(o->src_index);
1320 * Sparse checkout loop #1: set NEW_SKIP_WORKTREE on existing entries
1322 if (!o->skip_sparse_checkout)
1323 mark_new_skip_worktree(o->el, o->src_index, 0, CE_NEW_SKIP_WORKTREE);
1325 if (!dfc)
1326 dfc = xcalloc(1, cache_entry_size(0));
1327 o->df_conflict_entry = dfc;
1329 if (len) {
1330 const char *prefix = o->prefix ? o->prefix : "";
1331 struct traverse_info info;
1333 setup_traverse_info(&info, prefix);
1334 info.fn = unpack_callback;
1335 info.data = o;
1336 info.show_all_errors = o->show_all_errors;
1337 info.pathspec = o->pathspec;
1339 if (o->prefix) {
1341 * Unpack existing index entries that sort before the
1342 * prefix the tree is spliced into. Note that o->merge
1343 * is always true in this case.
1345 while (1) {
1346 struct cache_entry *ce = next_cache_entry(o);
1347 if (!ce)
1348 break;
1349 if (ce_in_traverse_path(ce, &info))
1350 break;
1351 if (unpack_index_entry(ce, o) < 0)
1352 goto return_failed;
1356 if (traverse_trees(len, t, &info) < 0)
1357 goto return_failed;
1360 /* Any left-over entries in the index? */
1361 if (o->merge) {
1362 while (1) {
1363 struct cache_entry *ce = next_cache_entry(o);
1364 if (!ce)
1365 break;
1366 if (unpack_index_entry(ce, o) < 0)
1367 goto return_failed;
1370 mark_all_ce_unused(o->src_index);
1372 if (o->trivial_merges_only && o->nontrivial_merge) {
1373 ret = unpack_failed(o, "Merge requires file-level merging");
1374 goto done;
1377 if (!o->skip_sparse_checkout) {
1378 int empty_worktree = 1;
1381 * Sparse checkout loop #2: set NEW_SKIP_WORKTREE on entries not in loop #1
1382 * If the will have NEW_SKIP_WORKTREE, also set CE_SKIP_WORKTREE
1383 * so apply_sparse_checkout() won't attempt to remove it from worktree
1385 mark_new_skip_worktree(o->el, &o->result, CE_ADDED, CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1387 ret = 0;
1388 for (i = 0; i < o->result.cache_nr; i++) {
1389 struct cache_entry *ce = o->result.cache[i];
1392 * Entries marked with CE_ADDED in merged_entry() do not have
1393 * verify_absent() check (the check is effectively disabled
1394 * because CE_NEW_SKIP_WORKTREE is set unconditionally).
1396 * Do the real check now because we have had
1397 * correct CE_NEW_SKIP_WORKTREE
1399 if (ce->ce_flags & CE_ADDED &&
1400 verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
1401 if (!o->show_all_errors)
1402 goto return_failed;
1403 ret = -1;
1406 if (apply_sparse_checkout(&o->result, ce, o)) {
1407 if (!o->show_all_errors)
1408 goto return_failed;
1409 ret = -1;
1411 if (!ce_skip_worktree(ce))
1412 empty_worktree = 0;
1415 if (ret < 0)
1416 goto return_failed;
1418 * Sparse checkout is meant to narrow down checkout area
1419 * but it does not make sense to narrow down to empty working
1420 * tree. This is usually a mistake in sparse checkout rules.
1421 * Do not allow users to do that.
1423 if (o->result.cache_nr && empty_worktree) {
1424 ret = unpack_failed(o, "Sparse checkout leaves no entry on working directory");
1425 goto done;
1429 ret = check_updates(o) ? (-2) : 0;
1430 if (o->dst_index) {
1431 if (!ret) {
1432 if (!o->result.cache_tree)
1433 o->result.cache_tree = cache_tree();
1434 if (!cache_tree_fully_valid(o->result.cache_tree))
1435 cache_tree_update(&o->result,
1436 WRITE_TREE_SILENT |
1437 WRITE_TREE_REPAIR);
1439 move_index_extensions(&o->result, o->src_index);
1440 discard_index(o->dst_index);
1441 *o->dst_index = o->result;
1442 } else {
1443 discard_index(&o->result);
1445 o->src_index = NULL;
1447 done:
1448 clear_exclude_list(&el);
1449 return ret;
1451 return_failed:
1452 if (o->show_all_errors)
1453 display_error_msgs(o);
1454 mark_all_ce_unused(o->src_index);
1455 ret = unpack_failed(o, NULL);
1456 if (o->exiting_early)
1457 ret = 0;
1458 goto done;
1461 /* Here come the merge functions */
1463 static int reject_merge(const struct cache_entry *ce,
1464 struct unpack_trees_options *o)
1466 return o->gently ? -1 :
1467 add_rejected_path(o, ERROR_WOULD_OVERWRITE, ce->name);
1470 static int same(const struct cache_entry *a, const struct cache_entry *b)
1472 if (!!a != !!b)
1473 return 0;
1474 if (!a && !b)
1475 return 1;
1476 if ((a->ce_flags | b->ce_flags) & CE_CONFLICTED)
1477 return 0;
1478 return a->ce_mode == b->ce_mode &&
1479 !oidcmp(&a->oid, &b->oid);
1484 * When a CE gets turned into an unmerged entry, we
1485 * want it to be up-to-date
1487 static int verify_uptodate_1(const struct cache_entry *ce,
1488 struct unpack_trees_options *o,
1489 enum unpack_trees_error_types error_type)
1491 struct stat st;
1493 if (o->index_only)
1494 return 0;
1497 * CE_VALID and CE_SKIP_WORKTREE cheat, we better check again
1498 * if this entry is truly up-to-date because this file may be
1499 * overwritten.
1501 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
1502 ; /* keep checking */
1503 else if (o->reset || ce_uptodate(ce))
1504 return 0;
1506 if (!lstat(ce->name, &st)) {
1507 int flags = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE;
1508 unsigned changed = ie_match_stat(o->src_index, ce, &st, flags);
1510 if (submodule_from_ce(ce)) {
1511 int r = check_submodule_move_head(ce,
1512 "HEAD", oid_to_hex(&ce->oid), o);
1513 if (r)
1514 return o->gently ? -1 :
1515 add_rejected_path(o, error_type, ce->name);
1516 return 0;
1519 if (!changed)
1520 return 0;
1522 * Historic default policy was to allow submodule to be out
1523 * of sync wrt the superproject index. If the submodule was
1524 * not considered interesting above, we don't care here.
1526 if (S_ISGITLINK(ce->ce_mode))
1527 return 0;
1529 errno = 0;
1531 if (errno == ENOENT)
1532 return 0;
1533 return o->gently ? -1 :
1534 add_rejected_path(o, error_type, ce->name);
1537 int verify_uptodate(const struct cache_entry *ce,
1538 struct unpack_trees_options *o)
1540 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
1541 return 0;
1542 return verify_uptodate_1(ce, o, ERROR_NOT_UPTODATE_FILE);
1545 static int verify_uptodate_sparse(const struct cache_entry *ce,
1546 struct unpack_trees_options *o)
1548 return verify_uptodate_1(ce, o, ERROR_SPARSE_NOT_UPTODATE_FILE);
1551 static void invalidate_ce_path(const struct cache_entry *ce,
1552 struct unpack_trees_options *o)
1554 if (!ce)
1555 return;
1556 cache_tree_invalidate_path(o->src_index, ce->name);
1557 untracked_cache_invalidate_path(o->src_index, ce->name, 1);
1561 * Check that checking out ce->sha1 in subdir ce->name is not
1562 * going to overwrite any working files.
1564 * Currently, git does not checkout subprojects during a superproject
1565 * checkout, so it is not going to overwrite anything.
1567 static int verify_clean_submodule(const char *old_sha1,
1568 const struct cache_entry *ce,
1569 enum unpack_trees_error_types error_type,
1570 struct unpack_trees_options *o)
1572 if (!submodule_from_ce(ce))
1573 return 0;
1575 return check_submodule_move_head(ce, old_sha1,
1576 oid_to_hex(&ce->oid), o);
1579 static int verify_clean_subdirectory(const struct cache_entry *ce,
1580 enum unpack_trees_error_types error_type,
1581 struct unpack_trees_options *o)
1584 * we are about to extract "ce->name"; we would not want to lose
1585 * anything in the existing directory there.
1587 int namelen;
1588 int i;
1589 struct dir_struct d;
1590 char *pathbuf;
1591 int cnt = 0;
1593 if (S_ISGITLINK(ce->ce_mode)) {
1594 struct object_id oid;
1595 int sub_head = resolve_gitlink_ref(ce->name, "HEAD", &oid);
1597 * If we are not going to update the submodule, then
1598 * we don't care.
1600 if (!sub_head && !oidcmp(&oid, &ce->oid))
1601 return 0;
1602 return verify_clean_submodule(sub_head ? NULL : oid_to_hex(&oid),
1603 ce, error_type, o);
1607 * First let's make sure we do not have a local modification
1608 * in that directory.
1610 namelen = ce_namelen(ce);
1611 for (i = locate_in_src_index(ce, o);
1612 i < o->src_index->cache_nr;
1613 i++) {
1614 struct cache_entry *ce2 = o->src_index->cache[i];
1615 int len = ce_namelen(ce2);
1616 if (len < namelen ||
1617 strncmp(ce->name, ce2->name, namelen) ||
1618 ce2->name[namelen] != '/')
1619 break;
1621 * ce2->name is an entry in the subdirectory to be
1622 * removed.
1624 if (!ce_stage(ce2)) {
1625 if (verify_uptodate(ce2, o))
1626 return -1;
1627 add_entry(o, ce2, CE_REMOVE, 0);
1628 mark_ce_used(ce2, o);
1630 cnt++;
1634 * Then we need to make sure that we do not lose a locally
1635 * present file that is not ignored.
1637 pathbuf = xstrfmt("%.*s/", namelen, ce->name);
1639 memset(&d, 0, sizeof(d));
1640 if (o->dir)
1641 d.exclude_per_dir = o->dir->exclude_per_dir;
1642 i = read_directory(&d, &the_index, pathbuf, namelen+1, NULL);
1643 if (i)
1644 return o->gently ? -1 :
1645 add_rejected_path(o, ERROR_NOT_UPTODATE_DIR, ce->name);
1646 free(pathbuf);
1647 return cnt;
1651 * This gets called when there was no index entry for the tree entry 'dst',
1652 * but we found a file in the working tree that 'lstat()' said was fine,
1653 * and we're on a case-insensitive filesystem.
1655 * See if we can find a case-insensitive match in the index that also
1656 * matches the stat information, and assume it's that other file!
1658 static int icase_exists(struct unpack_trees_options *o, const char *name, int len, struct stat *st)
1660 const struct cache_entry *src;
1662 src = index_file_exists(o->src_index, name, len, 1);
1663 return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
1666 static int check_ok_to_remove(const char *name, int len, int dtype,
1667 const struct cache_entry *ce, struct stat *st,
1668 enum unpack_trees_error_types error_type,
1669 struct unpack_trees_options *o)
1671 const struct cache_entry *result;
1674 * It may be that the 'lstat()' succeeded even though
1675 * target 'ce' was absent, because there is an old
1676 * entry that is different only in case..
1678 * Ignore that lstat() if it matches.
1680 if (ignore_case && icase_exists(o, name, len, st))
1681 return 0;
1683 if (o->dir &&
1684 is_excluded(o->dir, &the_index, name, &dtype))
1686 * ce->name is explicitly excluded, so it is Ok to
1687 * overwrite it.
1689 return 0;
1690 if (S_ISDIR(st->st_mode)) {
1692 * We are checking out path "foo" and
1693 * found "foo/." in the working tree.
1694 * This is tricky -- if we have modified
1695 * files that are in "foo/" we would lose
1696 * them.
1698 if (verify_clean_subdirectory(ce, error_type, o) < 0)
1699 return -1;
1700 return 0;
1704 * The previous round may already have decided to
1705 * delete this path, which is in a subdirectory that
1706 * is being replaced with a blob.
1708 result = index_file_exists(&o->result, name, len, 0);
1709 if (result) {
1710 if (result->ce_flags & CE_REMOVE)
1711 return 0;
1714 return o->gently ? -1 :
1715 add_rejected_path(o, error_type, name);
1719 * We do not want to remove or overwrite a working tree file that
1720 * is not tracked, unless it is ignored.
1722 static int verify_absent_1(const struct cache_entry *ce,
1723 enum unpack_trees_error_types error_type,
1724 struct unpack_trees_options *o)
1726 int len;
1727 struct stat st;
1729 if (o->index_only || o->reset || !o->update)
1730 return 0;
1732 len = check_leading_path(ce->name, ce_namelen(ce));
1733 if (!len)
1734 return 0;
1735 else if (len > 0) {
1736 char *path;
1737 int ret;
1739 path = xmemdupz(ce->name, len);
1740 if (lstat(path, &st))
1741 ret = error_errno("cannot stat '%s'", path);
1742 else {
1743 if (submodule_from_ce(ce))
1744 ret = check_submodule_move_head(ce,
1745 oid_to_hex(&ce->oid),
1746 NULL, o);
1747 else
1748 ret = check_ok_to_remove(path, len, DT_UNKNOWN, NULL,
1749 &st, error_type, o);
1751 free(path);
1752 return ret;
1753 } else if (lstat(ce->name, &st)) {
1754 if (errno != ENOENT)
1755 return error_errno("cannot stat '%s'", ce->name);
1756 return 0;
1757 } else {
1758 if (submodule_from_ce(ce))
1759 return check_submodule_move_head(ce, oid_to_hex(&ce->oid),
1760 NULL, o);
1762 return check_ok_to_remove(ce->name, ce_namelen(ce),
1763 ce_to_dtype(ce), ce, &st,
1764 error_type, o);
1768 static int verify_absent(const struct cache_entry *ce,
1769 enum unpack_trees_error_types error_type,
1770 struct unpack_trees_options *o)
1772 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
1773 return 0;
1774 return verify_absent_1(ce, error_type, o);
1777 static int verify_absent_sparse(const struct cache_entry *ce,
1778 enum unpack_trees_error_types error_type,
1779 struct unpack_trees_options *o)
1781 enum unpack_trees_error_types orphaned_error = error_type;
1782 if (orphaned_error == ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN)
1783 orphaned_error = ERROR_WOULD_LOSE_ORPHANED_OVERWRITTEN;
1785 return verify_absent_1(ce, orphaned_error, o);
1788 static int merged_entry(const struct cache_entry *ce,
1789 const struct cache_entry *old,
1790 struct unpack_trees_options *o)
1792 int update = CE_UPDATE;
1793 struct cache_entry *merge = dup_entry(ce);
1795 if (!old) {
1797 * New index entries. In sparse checkout, the following
1798 * verify_absent() will be delayed until after
1799 * traverse_trees() finishes in unpack_trees(), then:
1801 * - CE_NEW_SKIP_WORKTREE will be computed correctly
1802 * - verify_absent() be called again, this time with
1803 * correct CE_NEW_SKIP_WORKTREE
1805 * verify_absent() call here does nothing in sparse
1806 * checkout (i.e. o->skip_sparse_checkout == 0)
1808 update |= CE_ADDED;
1809 merge->ce_flags |= CE_NEW_SKIP_WORKTREE;
1811 if (verify_absent(merge,
1812 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
1813 free(merge);
1814 return -1;
1816 invalidate_ce_path(merge, o);
1818 if (submodule_from_ce(ce)) {
1819 int ret = check_submodule_move_head(ce, NULL,
1820 oid_to_hex(&ce->oid),
1822 if (ret)
1823 return ret;
1826 } else if (!(old->ce_flags & CE_CONFLICTED)) {
1828 * See if we can re-use the old CE directly?
1829 * That way we get the uptodate stat info.
1831 * This also removes the UPDATE flag on a match; otherwise
1832 * we will end up overwriting local changes in the work tree.
1834 if (same(old, merge)) {
1835 copy_cache_entry(merge, old);
1836 update = 0;
1837 } else {
1838 if (verify_uptodate(old, o)) {
1839 free(merge);
1840 return -1;
1842 /* Migrate old flags over */
1843 update |= old->ce_flags & (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1844 invalidate_ce_path(old, o);
1847 if (submodule_from_ce(ce)) {
1848 int ret = check_submodule_move_head(ce, oid_to_hex(&old->oid),
1849 oid_to_hex(&ce->oid),
1851 if (ret)
1852 return ret;
1854 } else {
1856 * Previously unmerged entry left as an existence
1857 * marker by read_index_unmerged();
1859 invalidate_ce_path(old, o);
1862 if (do_add_entry(o, merge, update, CE_STAGEMASK) < 0)
1863 return -1;
1864 return 1;
1867 static int deleted_entry(const struct cache_entry *ce,
1868 const struct cache_entry *old,
1869 struct unpack_trees_options *o)
1871 /* Did it exist in the index? */
1872 if (!old) {
1873 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
1874 return -1;
1875 return 0;
1877 if (!(old->ce_flags & CE_CONFLICTED) && verify_uptodate(old, o))
1878 return -1;
1879 add_entry(o, ce, CE_REMOVE, 0);
1880 invalidate_ce_path(ce, o);
1881 return 1;
1884 static int keep_entry(const struct cache_entry *ce,
1885 struct unpack_trees_options *o)
1887 add_entry(o, ce, 0, 0);
1888 return 1;
1891 #if DBRT_DEBUG
1892 static void show_stage_entry(FILE *o,
1893 const char *label, const struct cache_entry *ce)
1895 if (!ce)
1896 fprintf(o, "%s (missing)\n", label);
1897 else
1898 fprintf(o, "%s%06o %s %d\t%s\n",
1899 label,
1900 ce->ce_mode,
1901 oid_to_hex(&ce->oid),
1902 ce_stage(ce),
1903 ce->name);
1905 #endif
1907 int threeway_merge(const struct cache_entry * const *stages,
1908 struct unpack_trees_options *o)
1910 const struct cache_entry *index;
1911 const struct cache_entry *head;
1912 const struct cache_entry *remote = stages[o->head_idx + 1];
1913 int count;
1914 int head_match = 0;
1915 int remote_match = 0;
1917 int df_conflict_head = 0;
1918 int df_conflict_remote = 0;
1920 int any_anc_missing = 0;
1921 int no_anc_exists = 1;
1922 int i;
1924 for (i = 1; i < o->head_idx; i++) {
1925 if (!stages[i] || stages[i] == o->df_conflict_entry)
1926 any_anc_missing = 1;
1927 else
1928 no_anc_exists = 0;
1931 index = stages[0];
1932 head = stages[o->head_idx];
1934 if (head == o->df_conflict_entry) {
1935 df_conflict_head = 1;
1936 head = NULL;
1939 if (remote == o->df_conflict_entry) {
1940 df_conflict_remote = 1;
1941 remote = NULL;
1945 * First, if there's a #16 situation, note that to prevent #13
1946 * and #14.
1948 if (!same(remote, head)) {
1949 for (i = 1; i < o->head_idx; i++) {
1950 if (same(stages[i], head)) {
1951 head_match = i;
1953 if (same(stages[i], remote)) {
1954 remote_match = i;
1960 * We start with cases where the index is allowed to match
1961 * something other than the head: #14(ALT) and #2ALT, where it
1962 * is permitted to match the result instead.
1964 /* #14, #14ALT, #2ALT */
1965 if (remote && !df_conflict_head && head_match && !remote_match) {
1966 if (index && !same(index, remote) && !same(index, head))
1967 return reject_merge(index, o);
1968 return merged_entry(remote, index, o);
1971 * If we have an entry in the index cache, then we want to
1972 * make sure that it matches head.
1974 if (index && !same(index, head))
1975 return reject_merge(index, o);
1977 if (head) {
1978 /* #5ALT, #15 */
1979 if (same(head, remote))
1980 return merged_entry(head, index, o);
1981 /* #13, #3ALT */
1982 if (!df_conflict_remote && remote_match && !head_match)
1983 return merged_entry(head, index, o);
1986 /* #1 */
1987 if (!head && !remote && any_anc_missing)
1988 return 0;
1991 * Under the "aggressive" rule, we resolve mostly trivial
1992 * cases that we historically had git-merge-one-file resolve.
1994 if (o->aggressive) {
1995 int head_deleted = !head;
1996 int remote_deleted = !remote;
1997 const struct cache_entry *ce = NULL;
1999 if (index)
2000 ce = index;
2001 else if (head)
2002 ce = head;
2003 else if (remote)
2004 ce = remote;
2005 else {
2006 for (i = 1; i < o->head_idx; i++) {
2007 if (stages[i] && stages[i] != o->df_conflict_entry) {
2008 ce = stages[i];
2009 break;
2015 * Deleted in both.
2016 * Deleted in one and unchanged in the other.
2018 if ((head_deleted && remote_deleted) ||
2019 (head_deleted && remote && remote_match) ||
2020 (remote_deleted && head && head_match)) {
2021 if (index)
2022 return deleted_entry(index, index, o);
2023 if (ce && !head_deleted) {
2024 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2025 return -1;
2027 return 0;
2030 * Added in both, identically.
2032 if (no_anc_exists && head && remote && same(head, remote))
2033 return merged_entry(head, index, o);
2037 /* Below are "no merge" cases, which require that the index be
2038 * up-to-date to avoid the files getting overwritten with
2039 * conflict resolution files.
2041 if (index) {
2042 if (verify_uptodate(index, o))
2043 return -1;
2046 o->nontrivial_merge = 1;
2048 /* #2, #3, #4, #6, #7, #9, #10, #11. */
2049 count = 0;
2050 if (!head_match || !remote_match) {
2051 for (i = 1; i < o->head_idx; i++) {
2052 if (stages[i] && stages[i] != o->df_conflict_entry) {
2053 keep_entry(stages[i], o);
2054 count++;
2055 break;
2059 #if DBRT_DEBUG
2060 else {
2061 fprintf(stderr, "read-tree: warning #16 detected\n");
2062 show_stage_entry(stderr, "head ", stages[head_match]);
2063 show_stage_entry(stderr, "remote ", stages[remote_match]);
2065 #endif
2066 if (head) { count += keep_entry(head, o); }
2067 if (remote) { count += keep_entry(remote, o); }
2068 return count;
2072 * Two-way merge.
2074 * The rule is to "carry forward" what is in the index without losing
2075 * information across a "fast-forward", favoring a successful merge
2076 * over a merge failure when it makes sense. For details of the
2077 * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
2080 int twoway_merge(const struct cache_entry * const *src,
2081 struct unpack_trees_options *o)
2083 const struct cache_entry *current = src[0];
2084 const struct cache_entry *oldtree = src[1];
2085 const struct cache_entry *newtree = src[2];
2087 if (o->merge_size != 2)
2088 return error("Cannot do a twoway merge of %d trees",
2089 o->merge_size);
2091 if (oldtree == o->df_conflict_entry)
2092 oldtree = NULL;
2093 if (newtree == o->df_conflict_entry)
2094 newtree = NULL;
2096 if (current) {
2097 if (current->ce_flags & CE_CONFLICTED) {
2098 if (same(oldtree, newtree) || o->reset) {
2099 if (!newtree)
2100 return deleted_entry(current, current, o);
2101 else
2102 return merged_entry(newtree, current, o);
2104 return reject_merge(current, o);
2105 } else if ((!oldtree && !newtree) || /* 4 and 5 */
2106 (!oldtree && newtree &&
2107 same(current, newtree)) || /* 6 and 7 */
2108 (oldtree && newtree &&
2109 same(oldtree, newtree)) || /* 14 and 15 */
2110 (oldtree && newtree &&
2111 !same(oldtree, newtree) && /* 18 and 19 */
2112 same(current, newtree))) {
2113 return keep_entry(current, o);
2114 } else if (oldtree && !newtree && same(current, oldtree)) {
2115 /* 10 or 11 */
2116 return deleted_entry(oldtree, current, o);
2117 } else if (oldtree && newtree &&
2118 same(current, oldtree) && !same(current, newtree)) {
2119 /* 20 or 21 */
2120 return merged_entry(newtree, current, o);
2121 } else
2122 return reject_merge(current, o);
2124 else if (newtree) {
2125 if (oldtree && !o->initial_checkout) {
2127 * deletion of the path was staged;
2129 if (same(oldtree, newtree))
2130 return 1;
2131 return reject_merge(oldtree, o);
2133 return merged_entry(newtree, current, o);
2135 return deleted_entry(oldtree, current, o);
2139 * Bind merge.
2141 * Keep the index entries at stage0, collapse stage1 but make sure
2142 * stage0 does not have anything there.
2144 int bind_merge(const struct cache_entry * const *src,
2145 struct unpack_trees_options *o)
2147 const struct cache_entry *old = src[0];
2148 const struct cache_entry *a = src[1];
2150 if (o->merge_size != 1)
2151 return error("Cannot do a bind merge of %d trees",
2152 o->merge_size);
2153 if (a && old)
2154 return o->gently ? -1 :
2155 error(ERRORMSG(o, ERROR_BIND_OVERLAP),
2156 super_prefixed(a->name),
2157 super_prefixed(old->name));
2158 if (!a)
2159 return keep_entry(old, o);
2160 else
2161 return merged_entry(a, NULL, o);
2165 * One-way merge.
2167 * The rule is:
2168 * - take the stat information from stage0, take the data from stage1
2170 int oneway_merge(const struct cache_entry * const *src,
2171 struct unpack_trees_options *o)
2173 const struct cache_entry *old = src[0];
2174 const struct cache_entry *a = src[1];
2176 if (o->merge_size != 1)
2177 return error("Cannot do a oneway merge of %d trees",
2178 o->merge_size);
2180 if (!a || a == o->df_conflict_entry)
2181 return deleted_entry(old, old, o);
2183 if (old && same(old, a)) {
2184 int update = 0;
2185 if (o->reset && o->update && !ce_uptodate(old) && !ce_skip_worktree(old)) {
2186 struct stat st;
2187 if (lstat(old->name, &st) ||
2188 ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE))
2189 update |= CE_UPDATE;
2191 if (o->update && S_ISGITLINK(old->ce_mode) &&
2192 should_update_submodules() && !verify_uptodate(old, o))
2193 update |= CE_UPDATE;
2194 add_entry(o, old, update, 0);
2195 return 0;
2197 return merged_entry(a, old, o);