Merge branch 'sb/blame-color'
[git.git] / unpack-trees.c
blob7051fcf7d841c9526f4e0e83dd32d6922835e181
1 #define NO_THE_INDEX_COMPATIBILITY_MACROS
2 #include "cache.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "dir.h"
6 #include "tree.h"
7 #include "tree-walk.h"
8 #include "cache-tree.h"
9 #include "unpack-trees.h"
10 #include "progress.h"
11 #include "refs.h"
12 #include "attr.h"
13 #include "split-index.h"
14 #include "dir.h"
15 #include "submodule.h"
16 #include "submodule-config.h"
17 #include "fsmonitor.h"
18 #include "fetch-object.h"
21 * Error messages expected by scripts out of plumbing commands such as
22 * read-tree. Non-scripted Porcelain is not required to use these messages
23 * and in fact are encouraged to reword them to better suit their particular
24 * situation better. See how "git checkout" and "git merge" replaces
25 * them using setup_unpack_trees_porcelain(), for example.
27 static const char *unpack_plumbing_errors[NB_UNPACK_TREES_ERROR_TYPES] = {
28 /* ERROR_WOULD_OVERWRITE */
29 "Entry '%s' would be overwritten by merge. Cannot merge.",
31 /* ERROR_NOT_UPTODATE_FILE */
32 "Entry '%s' not uptodate. Cannot merge.",
34 /* ERROR_NOT_UPTODATE_DIR */
35 "Updating '%s' would lose untracked files in it",
37 /* ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN */
38 "Untracked working tree file '%s' would be overwritten by merge.",
40 /* ERROR_WOULD_LOSE_UNTRACKED_REMOVED */
41 "Untracked working tree file '%s' would be removed by merge.",
43 /* ERROR_BIND_OVERLAP */
44 "Entry '%s' overlaps with '%s'. Cannot bind.",
46 /* ERROR_SPARSE_NOT_UPTODATE_FILE */
47 "Entry '%s' not uptodate. Cannot update sparse checkout.",
49 /* ERROR_WOULD_LOSE_ORPHANED_OVERWRITTEN */
50 "Working tree file '%s' would be overwritten by sparse checkout update.",
52 /* ERROR_WOULD_LOSE_ORPHANED_REMOVED */
53 "Working tree file '%s' would be removed by sparse checkout update.",
55 /* ERROR_WOULD_LOSE_SUBMODULE */
56 "Submodule '%s' cannot checkout new HEAD.",
59 #define ERRORMSG(o,type) \
60 ( ((o) && (o)->msgs[(type)]) \
61 ? ((o)->msgs[(type)]) \
62 : (unpack_plumbing_errors[(type)]) )
64 static const char *super_prefixed(const char *path)
67 * It is necessary and sufficient to have two static buffers
68 * here, as the return value of this function is fed to
69 * error() using the unpack_*_errors[] templates we see above.
71 static struct strbuf buf[2] = {STRBUF_INIT, STRBUF_INIT};
72 static int super_prefix_len = -1;
73 static unsigned idx = ARRAY_SIZE(buf) - 1;
75 if (super_prefix_len < 0) {
76 const char *super_prefix = get_super_prefix();
77 if (!super_prefix) {
78 super_prefix_len = 0;
79 } else {
80 int i;
81 for (i = 0; i < ARRAY_SIZE(buf); i++)
82 strbuf_addstr(&buf[i], super_prefix);
83 super_prefix_len = buf[0].len;
87 if (!super_prefix_len)
88 return path;
90 if (++idx >= ARRAY_SIZE(buf))
91 idx = 0;
93 strbuf_setlen(&buf[idx], super_prefix_len);
94 strbuf_addstr(&buf[idx], path);
96 return buf[idx].buf;
99 void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,
100 const char *cmd)
102 int i;
103 const char **msgs = opts->msgs;
104 const char *msg;
106 if (!strcmp(cmd, "checkout"))
107 msg = advice_commit_before_merge
108 ? _("Your local changes to the following files would be overwritten by checkout:\n%%s"
109 "Please commit your changes or stash them before you switch branches.")
110 : _("Your local changes to the following files would be overwritten by checkout:\n%%s");
111 else if (!strcmp(cmd, "merge"))
112 msg = advice_commit_before_merge
113 ? _("Your local changes to the following files would be overwritten by merge:\n%%s"
114 "Please commit your changes or stash them before you merge.")
115 : _("Your local changes to the following files would be overwritten by merge:\n%%s");
116 else
117 msg = advice_commit_before_merge
118 ? _("Your local changes to the following files would be overwritten by %s:\n%%s"
119 "Please commit your changes or stash them before you %s.")
120 : _("Your local changes to the following files would be overwritten by %s:\n%%s");
121 msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOT_UPTODATE_FILE] =
122 xstrfmt(msg, cmd, cmd);
124 msgs[ERROR_NOT_UPTODATE_DIR] =
125 _("Updating the following directories would lose untracked files in them:\n%s");
127 if (!strcmp(cmd, "checkout"))
128 msg = advice_commit_before_merge
129 ? _("The following untracked working tree files would be removed by checkout:\n%%s"
130 "Please move or remove them before you switch branches.")
131 : _("The following untracked working tree files would be removed by checkout:\n%%s");
132 else if (!strcmp(cmd, "merge"))
133 msg = advice_commit_before_merge
134 ? _("The following untracked working tree files would be removed by merge:\n%%s"
135 "Please move or remove them before you merge.")
136 : _("The following untracked working tree files would be removed by merge:\n%%s");
137 else
138 msg = advice_commit_before_merge
139 ? _("The following untracked working tree files would be removed by %s:\n%%s"
140 "Please move or remove them before you %s.")
141 : _("The following untracked working tree files would be removed by %s:\n%%s");
142 msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED] = xstrfmt(msg, cmd, cmd);
144 if (!strcmp(cmd, "checkout"))
145 msg = advice_commit_before_merge
146 ? _("The following untracked working tree files would be overwritten by checkout:\n%%s"
147 "Please move or remove them before you switch branches.")
148 : _("The following untracked working tree files would be overwritten by checkout:\n%%s");
149 else if (!strcmp(cmd, "merge"))
150 msg = advice_commit_before_merge
151 ? _("The following untracked working tree files would be overwritten by merge:\n%%s"
152 "Please move or remove them before you merge.")
153 : _("The following untracked working tree files would be overwritten by merge:\n%%s");
154 else
155 msg = advice_commit_before_merge
156 ? _("The following untracked working tree files would be overwritten by %s:\n%%s"
157 "Please move or remove them before you %s.")
158 : _("The following untracked working tree files would be overwritten by %s:\n%%s");
159 msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN] = xstrfmt(msg, cmd, cmd);
162 * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
163 * cannot easily display it as a list.
165 msgs[ERROR_BIND_OVERLAP] = _("Entry '%s' overlaps with '%s'. Cannot bind.");
167 msgs[ERROR_SPARSE_NOT_UPTODATE_FILE] =
168 _("Cannot update sparse checkout: the following entries are not up to date:\n%s");
169 msgs[ERROR_WOULD_LOSE_ORPHANED_OVERWRITTEN] =
170 _("The following working tree files would be overwritten by sparse checkout update:\n%s");
171 msgs[ERROR_WOULD_LOSE_ORPHANED_REMOVED] =
172 _("The following working tree files would be removed by sparse checkout update:\n%s");
173 msgs[ERROR_WOULD_LOSE_SUBMODULE] =
174 _("Cannot update submodule:\n%s");
176 opts->show_all_errors = 1;
177 /* rejected paths may not have a static buffer */
178 for (i = 0; i < ARRAY_SIZE(opts->unpack_rejects); i++)
179 opts->unpack_rejects[i].strdup_strings = 1;
182 static int do_add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
183 unsigned int set, unsigned int clear)
185 clear |= CE_HASHED;
187 if (set & CE_REMOVE)
188 set |= CE_WT_REMOVE;
190 ce->ce_flags = (ce->ce_flags & ~clear) | set;
191 return add_index_entry(&o->result, ce,
192 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
195 static struct cache_entry *dup_entry(const struct cache_entry *ce)
197 unsigned int size = ce_size(ce);
198 struct cache_entry *new_entry = xmalloc(size);
200 memcpy(new_entry, ce, size);
201 return new_entry;
204 static void add_entry(struct unpack_trees_options *o,
205 const struct cache_entry *ce,
206 unsigned int set, unsigned int clear)
208 do_add_entry(o, dup_entry(ce), set, clear);
212 * add error messages on path <path>
213 * corresponding to the type <e> with the message <msg>
214 * indicating if it should be display in porcelain or not
216 static int add_rejected_path(struct unpack_trees_options *o,
217 enum unpack_trees_error_types e,
218 const char *path)
220 if (!o->show_all_errors)
221 return error(ERRORMSG(o, e), super_prefixed(path));
224 * Otherwise, insert in a list for future display by
225 * display_error_msgs()
227 string_list_append(&o->unpack_rejects[e], path);
228 return -1;
232 * display all the error messages stored in a nice way
234 static void display_error_msgs(struct unpack_trees_options *o)
236 int e, i;
237 int something_displayed = 0;
238 for (e = 0; e < NB_UNPACK_TREES_ERROR_TYPES; e++) {
239 struct string_list *rejects = &o->unpack_rejects[e];
240 if (rejects->nr > 0) {
241 struct strbuf path = STRBUF_INIT;
242 something_displayed = 1;
243 for (i = 0; i < rejects->nr; i++)
244 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
245 error(ERRORMSG(o, e), super_prefixed(path.buf));
246 strbuf_release(&path);
248 string_list_clear(rejects, 0);
250 if (something_displayed)
251 fprintf(stderr, _("Aborting\n"));
254 static int check_submodule_move_head(const struct cache_entry *ce,
255 const char *old_id,
256 const char *new_id,
257 struct unpack_trees_options *o)
259 unsigned flags = SUBMODULE_MOVE_HEAD_DRY_RUN;
260 const struct submodule *sub = submodule_from_ce(ce);
262 if (!sub)
263 return 0;
265 if (o->reset)
266 flags |= SUBMODULE_MOVE_HEAD_FORCE;
268 if (submodule_move_head(ce->name, old_id, new_id, flags))
269 return o->gently ? -1 :
270 add_rejected_path(o, ERROR_WOULD_LOSE_SUBMODULE, ce->name);
271 return 0;
275 * Preform the loading of the repository's gitmodules file. This function is
276 * used by 'check_update()' to perform loading of the gitmodules file in two
277 * differnt situations:
278 * (1) before removing entries from the working tree if the gitmodules file has
279 * been marked for removal. This situation is specified by 'state' == NULL.
280 * (2) before checking out entries to the working tree if the gitmodules file
281 * has been marked for update. This situation is specified by 'state' != NULL.
283 static void load_gitmodules_file(struct index_state *index,
284 struct checkout *state)
286 int pos = index_name_pos(index, GITMODULES_FILE, strlen(GITMODULES_FILE));
288 if (pos >= 0) {
289 struct cache_entry *ce = index->cache[pos];
290 if (!state && ce->ce_flags & CE_WT_REMOVE) {
291 repo_read_gitmodules(the_repository);
292 } else if (state && (ce->ce_flags & CE_UPDATE)) {
293 submodule_free(the_repository);
294 checkout_entry(ce, state, NULL);
295 repo_read_gitmodules(the_repository);
301 * Unlink the last component and schedule the leading directories for
302 * removal, such that empty directories get removed.
304 static void unlink_entry(const struct cache_entry *ce)
306 const struct submodule *sub = submodule_from_ce(ce);
307 if (sub) {
308 /* state.force is set at the caller. */
309 submodule_move_head(ce->name, "HEAD", NULL,
310 SUBMODULE_MOVE_HEAD_FORCE);
312 if (!check_leading_path(ce->name, ce_namelen(ce)))
313 return;
314 if (remove_or_warn(ce->ce_mode, ce->name))
315 return;
316 schedule_dir_for_removal(ce->name, ce_namelen(ce));
319 static struct progress *get_progress(struct unpack_trees_options *o)
321 unsigned cnt = 0, total = 0;
322 struct index_state *index = &o->result;
324 if (!o->update || !o->verbose_update)
325 return NULL;
327 for (; cnt < index->cache_nr; cnt++) {
328 const struct cache_entry *ce = index->cache[cnt];
329 if (ce->ce_flags & (CE_UPDATE | CE_WT_REMOVE))
330 total++;
333 return start_delayed_progress(_("Checking out files"), total);
336 static int check_updates(struct unpack_trees_options *o)
338 unsigned cnt = 0;
339 int errs = 0;
340 struct progress *progress = NULL;
341 struct index_state *index = &o->result;
342 struct checkout state = CHECKOUT_INIT;
343 int i;
345 state.force = 1;
346 state.quiet = 1;
347 state.refresh_cache = 1;
348 state.istate = index;
350 progress = get_progress(o);
352 if (o->update)
353 git_attr_set_direction(GIT_ATTR_CHECKOUT, index);
355 if (should_update_submodules() && o->update && !o->dry_run)
356 load_gitmodules_file(index, NULL);
358 for (i = 0; i < index->cache_nr; i++) {
359 const struct cache_entry *ce = index->cache[i];
361 if (ce->ce_flags & CE_WT_REMOVE) {
362 display_progress(progress, ++cnt);
363 if (o->update && !o->dry_run)
364 unlink_entry(ce);
367 remove_marked_cache_entries(index);
368 remove_scheduled_dirs();
370 if (should_update_submodules() && o->update && !o->dry_run)
371 load_gitmodules_file(index, &state);
373 enable_delayed_checkout(&state);
374 if (repository_format_partial_clone && o->update && !o->dry_run) {
376 * Prefetch the objects that are to be checked out in the loop
377 * below.
379 struct oid_array to_fetch = OID_ARRAY_INIT;
380 int fetch_if_missing_store = fetch_if_missing;
381 fetch_if_missing = 0;
382 for (i = 0; i < index->cache_nr; i++) {
383 struct cache_entry *ce = index->cache[i];
384 if ((ce->ce_flags & CE_UPDATE) &&
385 !S_ISGITLINK(ce->ce_mode)) {
386 if (!has_object_file(&ce->oid))
387 oid_array_append(&to_fetch, &ce->oid);
390 if (to_fetch.nr)
391 fetch_objects(repository_format_partial_clone,
392 &to_fetch);
393 fetch_if_missing = fetch_if_missing_store;
394 oid_array_clear(&to_fetch);
396 for (i = 0; i < index->cache_nr; i++) {
397 struct cache_entry *ce = index->cache[i];
399 if (ce->ce_flags & CE_UPDATE) {
400 if (ce->ce_flags & CE_WT_REMOVE)
401 BUG("both update and delete flags are set on %s",
402 ce->name);
403 display_progress(progress, ++cnt);
404 ce->ce_flags &= ~CE_UPDATE;
405 if (o->update && !o->dry_run) {
406 errs |= checkout_entry(ce, &state, NULL);
410 stop_progress(&progress);
411 errs |= finish_delayed_checkout(&state);
412 if (o->update)
413 git_attr_set_direction(GIT_ATTR_CHECKIN, NULL);
414 return errs != 0;
417 static int verify_uptodate_sparse(const struct cache_entry *ce,
418 struct unpack_trees_options *o);
419 static int verify_absent_sparse(const struct cache_entry *ce,
420 enum unpack_trees_error_types,
421 struct unpack_trees_options *o);
423 static int apply_sparse_checkout(struct index_state *istate,
424 struct cache_entry *ce,
425 struct unpack_trees_options *o)
427 int was_skip_worktree = ce_skip_worktree(ce);
429 if (ce->ce_flags & CE_NEW_SKIP_WORKTREE)
430 ce->ce_flags |= CE_SKIP_WORKTREE;
431 else
432 ce->ce_flags &= ~CE_SKIP_WORKTREE;
433 if (was_skip_worktree != ce_skip_worktree(ce)) {
434 ce->ce_flags |= CE_UPDATE_IN_BASE;
435 mark_fsmonitor_invalid(istate, ce);
436 istate->cache_changed |= CE_ENTRY_CHANGED;
440 * if (!was_skip_worktree && !ce_skip_worktree()) {
441 * This is perfectly normal. Move on;
446 * Merge strategies may set CE_UPDATE|CE_REMOVE outside checkout
447 * area as a result of ce_skip_worktree() shortcuts in
448 * verify_absent() and verify_uptodate().
449 * Make sure they don't modify worktree if they are already
450 * outside checkout area
452 if (was_skip_worktree && ce_skip_worktree(ce)) {
453 ce->ce_flags &= ~CE_UPDATE;
456 * By default, when CE_REMOVE is on, CE_WT_REMOVE is also
457 * on to get that file removed from both index and worktree.
458 * If that file is already outside worktree area, don't
459 * bother remove it.
461 if (ce->ce_flags & CE_REMOVE)
462 ce->ce_flags &= ~CE_WT_REMOVE;
465 if (!was_skip_worktree && ce_skip_worktree(ce)) {
467 * If CE_UPDATE is set, verify_uptodate() must be called already
468 * also stat info may have lost after merged_entry() so calling
469 * verify_uptodate() again may fail
471 if (!(ce->ce_flags & CE_UPDATE) && verify_uptodate_sparse(ce, o))
472 return -1;
473 ce->ce_flags |= CE_WT_REMOVE;
474 ce->ce_flags &= ~CE_UPDATE;
476 if (was_skip_worktree && !ce_skip_worktree(ce)) {
477 if (verify_absent_sparse(ce, ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o))
478 return -1;
479 ce->ce_flags |= CE_UPDATE;
481 return 0;
484 static inline int call_unpack_fn(const struct cache_entry * const *src,
485 struct unpack_trees_options *o)
487 int ret = o->fn(src, o);
488 if (ret > 0)
489 ret = 0;
490 return ret;
493 static void mark_ce_used(struct cache_entry *ce, struct unpack_trees_options *o)
495 ce->ce_flags |= CE_UNPACKED;
497 if (o->cache_bottom < o->src_index->cache_nr &&
498 o->src_index->cache[o->cache_bottom] == ce) {
499 int bottom = o->cache_bottom;
500 while (bottom < o->src_index->cache_nr &&
501 o->src_index->cache[bottom]->ce_flags & CE_UNPACKED)
502 bottom++;
503 o->cache_bottom = bottom;
507 static void mark_all_ce_unused(struct index_state *index)
509 int i;
510 for (i = 0; i < index->cache_nr; i++)
511 index->cache[i]->ce_flags &= ~(CE_UNPACKED | CE_ADDED | CE_NEW_SKIP_WORKTREE);
514 static int locate_in_src_index(const struct cache_entry *ce,
515 struct unpack_trees_options *o)
517 struct index_state *index = o->src_index;
518 int len = ce_namelen(ce);
519 int pos = index_name_pos(index, ce->name, len);
520 if (pos < 0)
521 pos = -1 - pos;
522 return pos;
526 * We call unpack_index_entry() with an unmerged cache entry
527 * only in diff-index, and it wants a single callback. Skip
528 * the other unmerged entry with the same name.
530 static void mark_ce_used_same_name(struct cache_entry *ce,
531 struct unpack_trees_options *o)
533 struct index_state *index = o->src_index;
534 int len = ce_namelen(ce);
535 int pos;
537 for (pos = locate_in_src_index(ce, o); pos < index->cache_nr; pos++) {
538 struct cache_entry *next = index->cache[pos];
539 if (len != ce_namelen(next) ||
540 memcmp(ce->name, next->name, len))
541 break;
542 mark_ce_used(next, o);
546 static struct cache_entry *next_cache_entry(struct unpack_trees_options *o)
548 const struct index_state *index = o->src_index;
549 int pos = o->cache_bottom;
551 while (pos < index->cache_nr) {
552 struct cache_entry *ce = index->cache[pos];
553 if (!(ce->ce_flags & CE_UNPACKED))
554 return ce;
555 pos++;
557 return NULL;
560 static void add_same_unmerged(const struct cache_entry *ce,
561 struct unpack_trees_options *o)
563 struct index_state *index = o->src_index;
564 int len = ce_namelen(ce);
565 int pos = index_name_pos(index, ce->name, len);
567 if (0 <= pos)
568 die("programming error in a caller of mark_ce_used_same_name");
569 for (pos = -pos - 1; pos < index->cache_nr; pos++) {
570 struct cache_entry *next = index->cache[pos];
571 if (len != ce_namelen(next) ||
572 memcmp(ce->name, next->name, len))
573 break;
574 add_entry(o, next, 0, 0);
575 mark_ce_used(next, o);
579 static int unpack_index_entry(struct cache_entry *ce,
580 struct unpack_trees_options *o)
582 const struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
583 int ret;
585 src[0] = ce;
587 mark_ce_used(ce, o);
588 if (ce_stage(ce)) {
589 if (o->skip_unmerged) {
590 add_entry(o, ce, 0, 0);
591 return 0;
594 ret = call_unpack_fn(src, o);
595 if (ce_stage(ce))
596 mark_ce_used_same_name(ce, o);
597 return ret;
600 static int find_cache_pos(struct traverse_info *, const struct name_entry *);
602 static void restore_cache_bottom(struct traverse_info *info, int bottom)
604 struct unpack_trees_options *o = info->data;
606 if (o->diff_index_cached)
607 return;
608 o->cache_bottom = bottom;
611 static int switch_cache_bottom(struct traverse_info *info)
613 struct unpack_trees_options *o = info->data;
614 int ret, pos;
616 if (o->diff_index_cached)
617 return 0;
618 ret = o->cache_bottom;
619 pos = find_cache_pos(info->prev, &info->name);
621 if (pos < -1)
622 o->cache_bottom = -2 - pos;
623 else if (pos < 0)
624 o->cache_bottom = o->src_index->cache_nr;
625 return ret;
628 static inline int are_same_oid(struct name_entry *name_j, struct name_entry *name_k)
630 return name_j->oid && name_k->oid && !oidcmp(name_j->oid, name_k->oid);
633 static int traverse_trees_recursive(int n, unsigned long dirmask,
634 unsigned long df_conflicts,
635 struct name_entry *names,
636 struct traverse_info *info)
638 int i, ret, bottom;
639 int nr_buf = 0;
640 struct tree_desc t[MAX_UNPACK_TREES];
641 void *buf[MAX_UNPACK_TREES];
642 struct traverse_info newinfo;
643 struct name_entry *p;
645 p = names;
646 while (!p->mode)
647 p++;
649 newinfo = *info;
650 newinfo.prev = info;
651 newinfo.pathspec = info->pathspec;
652 newinfo.name = *p;
653 newinfo.pathlen += tree_entry_len(p) + 1;
654 newinfo.df_conflicts |= df_conflicts;
657 * Fetch the tree from the ODB for each peer directory in the
658 * n commits.
660 * For 2- and 3-way traversals, we try to avoid hitting the
661 * ODB twice for the same OID. This should yield a nice speed
662 * up in checkouts and merges when the commits are similar.
664 * We don't bother doing the full O(n^2) search for larger n,
665 * because wider traversals don't happen that often and we
666 * avoid the search setup.
668 * When 2 peer OIDs are the same, we just copy the tree
669 * descriptor data. This implicitly borrows the buffer
670 * data from the earlier cell.
672 for (i = 0; i < n; i++, dirmask >>= 1) {
673 if (i > 0 && are_same_oid(&names[i], &names[i - 1]))
674 t[i] = t[i - 1];
675 else if (i > 1 && are_same_oid(&names[i], &names[i - 2]))
676 t[i] = t[i - 2];
677 else {
678 const struct object_id *oid = NULL;
679 if (dirmask & 1)
680 oid = names[i].oid;
681 buf[nr_buf++] = fill_tree_descriptor(t + i, oid);
685 bottom = switch_cache_bottom(&newinfo);
686 ret = traverse_trees(n, t, &newinfo);
687 restore_cache_bottom(&newinfo, bottom);
689 for (i = 0; i < nr_buf; i++)
690 free(buf[i]);
692 return ret;
696 * Compare the traverse-path to the cache entry without actually
697 * having to generate the textual representation of the traverse
698 * path.
700 * NOTE! This *only* compares up to the size of the traverse path
701 * itself - the caller needs to do the final check for the cache
702 * entry having more data at the end!
704 static int do_compare_entry_piecewise(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
706 int len, pathlen, ce_len;
707 const char *ce_name;
709 if (info->prev) {
710 int cmp = do_compare_entry_piecewise(ce, info->prev,
711 &info->name);
712 if (cmp)
713 return cmp;
715 pathlen = info->pathlen;
716 ce_len = ce_namelen(ce);
718 /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
719 if (ce_len < pathlen)
720 return -1;
722 ce_len -= pathlen;
723 ce_name = ce->name + pathlen;
725 len = tree_entry_len(n);
726 return df_name_compare(ce_name, ce_len, S_IFREG, n->path, len, n->mode);
729 static int do_compare_entry(const struct cache_entry *ce,
730 const struct traverse_info *info,
731 const struct name_entry *n)
733 int len, pathlen, ce_len;
734 const char *ce_name;
735 int cmp;
738 * If we have not precomputed the traverse path, it is quicker
739 * to avoid doing so. But if we have precomputed it,
740 * it is quicker to use the precomputed version.
742 if (!info->traverse_path)
743 return do_compare_entry_piecewise(ce, info, n);
745 cmp = strncmp(ce->name, info->traverse_path, info->pathlen);
746 if (cmp)
747 return cmp;
749 pathlen = info->pathlen;
750 ce_len = ce_namelen(ce);
752 if (ce_len < pathlen)
753 return -1;
755 ce_len -= pathlen;
756 ce_name = ce->name + pathlen;
758 len = tree_entry_len(n);
759 return df_name_compare(ce_name, ce_len, S_IFREG, n->path, len, n->mode);
762 static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
764 int cmp = do_compare_entry(ce, info, n);
765 if (cmp)
766 return cmp;
769 * Even if the beginning compared identically, the ce should
770 * compare as bigger than a directory leading up to it!
772 return ce_namelen(ce) > traverse_path_len(info, n);
775 static int ce_in_traverse_path(const struct cache_entry *ce,
776 const struct traverse_info *info)
778 if (!info->prev)
779 return 1;
780 if (do_compare_entry(ce, info->prev, &info->name))
781 return 0;
783 * If ce (blob) is the same name as the path (which is a tree
784 * we will be descending into), it won't be inside it.
786 return (info->pathlen < ce_namelen(ce));
789 static struct cache_entry *create_ce_entry(const struct traverse_info *info, const struct name_entry *n, int stage)
791 int len = traverse_path_len(info, n);
792 struct cache_entry *ce = xcalloc(1, cache_entry_size(len));
794 ce->ce_mode = create_ce_mode(n->mode);
795 ce->ce_flags = create_ce_flags(stage);
796 ce->ce_namelen = len;
797 oidcpy(&ce->oid, n->oid);
798 make_traverse_path(ce->name, info, n);
800 return ce;
803 static int unpack_nondirectories(int n, unsigned long mask,
804 unsigned long dirmask,
805 struct cache_entry **src,
806 const struct name_entry *names,
807 const struct traverse_info *info)
809 int i;
810 struct unpack_trees_options *o = info->data;
811 unsigned long conflicts = info->df_conflicts | dirmask;
813 /* Do we have *only* directories? Nothing to do */
814 if (mask == dirmask && !src[0])
815 return 0;
818 * Ok, we've filled in up to any potential index entry in src[0],
819 * now do the rest.
821 for (i = 0; i < n; i++) {
822 int stage;
823 unsigned int bit = 1ul << i;
824 if (conflicts & bit) {
825 src[i + o->merge] = o->df_conflict_entry;
826 continue;
828 if (!(mask & bit))
829 continue;
830 if (!o->merge)
831 stage = 0;
832 else if (i + 1 < o->head_idx)
833 stage = 1;
834 else if (i + 1 > o->head_idx)
835 stage = 3;
836 else
837 stage = 2;
838 src[i + o->merge] = create_ce_entry(info, names + i, stage);
841 if (o->merge) {
842 int rc = call_unpack_fn((const struct cache_entry * const *)src,
844 for (i = 0; i < n; i++) {
845 struct cache_entry *ce = src[i + o->merge];
846 if (ce != o->df_conflict_entry)
847 free(ce);
849 return rc;
852 for (i = 0; i < n; i++)
853 if (src[i] && src[i] != o->df_conflict_entry)
854 if (do_add_entry(o, src[i], 0, 0))
855 return -1;
857 return 0;
860 static int unpack_failed(struct unpack_trees_options *o, const char *message)
862 discard_index(&o->result);
863 if (!o->gently && !o->exiting_early) {
864 if (message)
865 return error("%s", message);
866 return -1;
868 return -1;
872 * The tree traversal is looking at name p. If we have a matching entry,
873 * return it. If name p is a directory in the index, do not return
874 * anything, as we will want to match it when the traversal descends into
875 * the directory.
877 static int find_cache_pos(struct traverse_info *info,
878 const struct name_entry *p)
880 int pos;
881 struct unpack_trees_options *o = info->data;
882 struct index_state *index = o->src_index;
883 int pfxlen = info->pathlen;
884 int p_len = tree_entry_len(p);
886 for (pos = o->cache_bottom; pos < index->cache_nr; pos++) {
887 const struct cache_entry *ce = index->cache[pos];
888 const char *ce_name, *ce_slash;
889 int cmp, ce_len;
891 if (ce->ce_flags & CE_UNPACKED) {
893 * cache_bottom entry is already unpacked, so
894 * we can never match it; don't check it
895 * again.
897 if (pos == o->cache_bottom)
898 ++o->cache_bottom;
899 continue;
901 if (!ce_in_traverse_path(ce, info)) {
903 * Check if we can skip future cache checks
904 * (because we're already past all possible
905 * entries in the traverse path).
907 if (info->traverse_path) {
908 if (strncmp(ce->name, info->traverse_path,
909 info->pathlen) > 0)
910 break;
912 continue;
914 ce_name = ce->name + pfxlen;
915 ce_slash = strchr(ce_name, '/');
916 if (ce_slash)
917 ce_len = ce_slash - ce_name;
918 else
919 ce_len = ce_namelen(ce) - pfxlen;
920 cmp = name_compare(p->path, p_len, ce_name, ce_len);
922 * Exact match; if we have a directory we need to
923 * delay returning it.
925 if (!cmp)
926 return ce_slash ? -2 - pos : pos;
927 if (0 < cmp)
928 continue; /* keep looking */
930 * ce_name sorts after p->path; could it be that we
931 * have files under p->path directory in the index?
932 * E.g. ce_name == "t-i", and p->path == "t"; we may
933 * have "t/a" in the index.
935 if (p_len < ce_len && !memcmp(ce_name, p->path, p_len) &&
936 ce_name[p_len] < '/')
937 continue; /* keep looking */
938 break;
940 return -1;
943 static struct cache_entry *find_cache_entry(struct traverse_info *info,
944 const struct name_entry *p)
946 int pos = find_cache_pos(info, p);
947 struct unpack_trees_options *o = info->data;
949 if (0 <= pos)
950 return o->src_index->cache[pos];
951 else
952 return NULL;
955 static void debug_path(struct traverse_info *info)
957 if (info->prev) {
958 debug_path(info->prev);
959 if (*info->prev->name.path)
960 putchar('/');
962 printf("%s", info->name.path);
965 static void debug_name_entry(int i, struct name_entry *n)
967 printf("ent#%d %06o %s\n", i,
968 n->path ? n->mode : 0,
969 n->path ? n->path : "(missing)");
972 static void debug_unpack_callback(int n,
973 unsigned long mask,
974 unsigned long dirmask,
975 struct name_entry *names,
976 struct traverse_info *info)
978 int i;
979 printf("* unpack mask %lu, dirmask %lu, cnt %d ",
980 mask, dirmask, n);
981 debug_path(info);
982 putchar('\n');
983 for (i = 0; i < n; i++)
984 debug_name_entry(i, names + i);
987 static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
989 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
990 struct unpack_trees_options *o = info->data;
991 const struct name_entry *p = names;
993 /* Find first entry with a real name (we could use "mask" too) */
994 while (!p->mode)
995 p++;
997 if (o->debug_unpack)
998 debug_unpack_callback(n, mask, dirmask, names, info);
1000 /* Are we supposed to look at the index too? */
1001 if (o->merge) {
1002 while (1) {
1003 int cmp;
1004 struct cache_entry *ce;
1006 if (o->diff_index_cached)
1007 ce = next_cache_entry(o);
1008 else
1009 ce = find_cache_entry(info, p);
1011 if (!ce)
1012 break;
1013 cmp = compare_entry(ce, info, p);
1014 if (cmp < 0) {
1015 if (unpack_index_entry(ce, o) < 0)
1016 return unpack_failed(o, NULL);
1017 continue;
1019 if (!cmp) {
1020 if (ce_stage(ce)) {
1022 * If we skip unmerged index
1023 * entries, we'll skip this
1024 * entry *and* the tree
1025 * entries associated with it!
1027 if (o->skip_unmerged) {
1028 add_same_unmerged(ce, o);
1029 return mask;
1032 src[0] = ce;
1034 break;
1038 if (unpack_nondirectories(n, mask, dirmask, src, names, info) < 0)
1039 return -1;
1041 if (o->merge && src[0]) {
1042 if (ce_stage(src[0]))
1043 mark_ce_used_same_name(src[0], o);
1044 else
1045 mark_ce_used(src[0], o);
1048 /* Now handle any directories.. */
1049 if (dirmask) {
1050 /* special case: "diff-index --cached" looking at a tree */
1051 if (o->diff_index_cached &&
1052 n == 1 && dirmask == 1 && S_ISDIR(names->mode)) {
1053 int matches;
1054 matches = cache_tree_matches_traversal(o->src_index->cache_tree,
1055 names, info);
1057 * Everything under the name matches; skip the
1058 * entire hierarchy. diff_index_cached codepath
1059 * special cases D/F conflicts in such a way that
1060 * it does not do any look-ahead, so this is safe.
1062 if (matches) {
1063 o->cache_bottom += matches;
1064 return mask;
1068 if (traverse_trees_recursive(n, dirmask, mask & ~dirmask,
1069 names, info) < 0)
1070 return -1;
1071 return mask;
1074 return mask;
1077 static int clear_ce_flags_1(struct cache_entry **cache, int nr,
1078 struct strbuf *prefix,
1079 int select_mask, int clear_mask,
1080 struct exclude_list *el, int defval);
1082 /* Whole directory matching */
1083 static int clear_ce_flags_dir(struct cache_entry **cache, int nr,
1084 struct strbuf *prefix,
1085 char *basename,
1086 int select_mask, int clear_mask,
1087 struct exclude_list *el, int defval)
1089 struct cache_entry **cache_end;
1090 int dtype = DT_DIR;
1091 int ret = is_excluded_from_list(prefix->buf, prefix->len,
1092 basename, &dtype, el, &the_index);
1093 int rc;
1095 strbuf_addch(prefix, '/');
1097 /* If undecided, use matching result of parent dir in defval */
1098 if (ret < 0)
1099 ret = defval;
1101 for (cache_end = cache; cache_end != cache + nr; cache_end++) {
1102 struct cache_entry *ce = *cache_end;
1103 if (strncmp(ce->name, prefix->buf, prefix->len))
1104 break;
1108 * TODO: check el, if there are no patterns that may conflict
1109 * with ret (iow, we know in advance the incl/excl
1110 * decision for the entire directory), clear flag here without
1111 * calling clear_ce_flags_1(). That function will call
1112 * the expensive is_excluded_from_list() on every entry.
1114 rc = clear_ce_flags_1(cache, cache_end - cache,
1115 prefix,
1116 select_mask, clear_mask,
1117 el, ret);
1118 strbuf_setlen(prefix, prefix->len - 1);
1119 return rc;
1123 * Traverse the index, find every entry that matches according to
1124 * o->el. Do "ce_flags &= ~clear_mask" on those entries. Return the
1125 * number of traversed entries.
1127 * If select_mask is non-zero, only entries whose ce_flags has on of
1128 * those bits enabled are traversed.
1130 * cache : pointer to an index entry
1131 * prefix_len : an offset to its path
1133 * The current path ("prefix") including the trailing '/' is
1134 * cache[0]->name[0..(prefix_len-1)]
1135 * Top level path has prefix_len zero.
1137 static int clear_ce_flags_1(struct cache_entry **cache, int nr,
1138 struct strbuf *prefix,
1139 int select_mask, int clear_mask,
1140 struct exclude_list *el, int defval)
1142 struct cache_entry **cache_end = cache + nr;
1145 * Process all entries that have the given prefix and meet
1146 * select_mask condition
1148 while(cache != cache_end) {
1149 struct cache_entry *ce = *cache;
1150 const char *name, *slash;
1151 int len, dtype, ret;
1153 if (select_mask && !(ce->ce_flags & select_mask)) {
1154 cache++;
1155 continue;
1158 if (prefix->len && strncmp(ce->name, prefix->buf, prefix->len))
1159 break;
1161 name = ce->name + prefix->len;
1162 slash = strchr(name, '/');
1164 /* If it's a directory, try whole directory match first */
1165 if (slash) {
1166 int processed;
1168 len = slash - name;
1169 strbuf_add(prefix, name, len);
1171 processed = clear_ce_flags_dir(cache, cache_end - cache,
1172 prefix,
1173 prefix->buf + prefix->len - len,
1174 select_mask, clear_mask,
1175 el, defval);
1177 /* clear_c_f_dir eats a whole dir already? */
1178 if (processed) {
1179 cache += processed;
1180 strbuf_setlen(prefix, prefix->len - len);
1181 continue;
1184 strbuf_addch(prefix, '/');
1185 cache += clear_ce_flags_1(cache, cache_end - cache,
1186 prefix,
1187 select_mask, clear_mask, el, defval);
1188 strbuf_setlen(prefix, prefix->len - len - 1);
1189 continue;
1192 /* Non-directory */
1193 dtype = ce_to_dtype(ce);
1194 ret = is_excluded_from_list(ce->name, ce_namelen(ce),
1195 name, &dtype, el, &the_index);
1196 if (ret < 0)
1197 ret = defval;
1198 if (ret > 0)
1199 ce->ce_flags &= ~clear_mask;
1200 cache++;
1202 return nr - (cache_end - cache);
1205 static int clear_ce_flags(struct cache_entry **cache, int nr,
1206 int select_mask, int clear_mask,
1207 struct exclude_list *el)
1209 static struct strbuf prefix = STRBUF_INIT;
1211 strbuf_reset(&prefix);
1213 return clear_ce_flags_1(cache, nr,
1214 &prefix,
1215 select_mask, clear_mask,
1216 el, 0);
1220 * Set/Clear CE_NEW_SKIP_WORKTREE according to $GIT_DIR/info/sparse-checkout
1222 static void mark_new_skip_worktree(struct exclude_list *el,
1223 struct index_state *the_index,
1224 int select_flag, int skip_wt_flag)
1226 int i;
1229 * 1. Pretend the narrowest worktree: only unmerged entries
1230 * are checked out
1232 for (i = 0; i < the_index->cache_nr; i++) {
1233 struct cache_entry *ce = the_index->cache[i];
1235 if (select_flag && !(ce->ce_flags & select_flag))
1236 continue;
1238 if (!ce_stage(ce))
1239 ce->ce_flags |= skip_wt_flag;
1240 else
1241 ce->ce_flags &= ~skip_wt_flag;
1245 * 2. Widen worktree according to sparse-checkout file.
1246 * Matched entries will have skip_wt_flag cleared (i.e. "in")
1248 clear_ce_flags(the_index->cache, the_index->cache_nr,
1249 select_flag, skip_wt_flag, el);
1252 static int verify_absent(const struct cache_entry *,
1253 enum unpack_trees_error_types,
1254 struct unpack_trees_options *);
1256 * N-way merge "len" trees. Returns 0 on success, -1 on failure to manipulate the
1257 * resulting index, -2 on failure to reflect the changes to the work tree.
1259 * CE_ADDED, CE_UNPACKED and CE_NEW_SKIP_WORKTREE are used internally
1261 int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
1263 int i, ret;
1264 static struct cache_entry *dfc;
1265 struct exclude_list el;
1267 if (len > MAX_UNPACK_TREES)
1268 die("unpack_trees takes at most %d trees", MAX_UNPACK_TREES);
1270 memset(&el, 0, sizeof(el));
1271 if (!core_apply_sparse_checkout || !o->update)
1272 o->skip_sparse_checkout = 1;
1273 if (!o->skip_sparse_checkout) {
1274 char *sparse = git_pathdup("info/sparse-checkout");
1275 if (add_excludes_from_file_to_list(sparse, "", 0, &el, NULL) < 0)
1276 o->skip_sparse_checkout = 1;
1277 else
1278 o->el = &el;
1279 free(sparse);
1282 memset(&o->result, 0, sizeof(o->result));
1283 o->result.initialized = 1;
1284 o->result.timestamp.sec = o->src_index->timestamp.sec;
1285 o->result.timestamp.nsec = o->src_index->timestamp.nsec;
1286 o->result.version = o->src_index->version;
1287 if (!o->src_index->split_index) {
1288 o->result.split_index = NULL;
1289 } else if (o->src_index == o->dst_index) {
1291 * o->dst_index (and thus o->src_index) will be discarded
1292 * and overwritten with o->result at the end of this function,
1293 * so just use src_index's split_index to avoid having to
1294 * create a new one.
1296 o->result.split_index = o->src_index->split_index;
1297 o->result.split_index->refcount++;
1298 } else {
1299 o->result.split_index = init_split_index(&o->result);
1301 hashcpy(o->result.sha1, o->src_index->sha1);
1302 o->merge_size = len;
1303 mark_all_ce_unused(o->src_index);
1306 * Sparse checkout loop #1: set NEW_SKIP_WORKTREE on existing entries
1308 if (!o->skip_sparse_checkout)
1309 mark_new_skip_worktree(o->el, o->src_index, 0, CE_NEW_SKIP_WORKTREE);
1311 if (!dfc)
1312 dfc = xcalloc(1, cache_entry_size(0));
1313 o->df_conflict_entry = dfc;
1315 if (len) {
1316 const char *prefix = o->prefix ? o->prefix : "";
1317 struct traverse_info info;
1319 setup_traverse_info(&info, prefix);
1320 info.fn = unpack_callback;
1321 info.data = o;
1322 info.show_all_errors = o->show_all_errors;
1323 info.pathspec = o->pathspec;
1325 if (o->prefix) {
1327 * Unpack existing index entries that sort before the
1328 * prefix the tree is spliced into. Note that o->merge
1329 * is always true in this case.
1331 while (1) {
1332 struct cache_entry *ce = next_cache_entry(o);
1333 if (!ce)
1334 break;
1335 if (ce_in_traverse_path(ce, &info))
1336 break;
1337 if (unpack_index_entry(ce, o) < 0)
1338 goto return_failed;
1342 if (traverse_trees(len, t, &info) < 0)
1343 goto return_failed;
1346 /* Any left-over entries in the index? */
1347 if (o->merge) {
1348 while (1) {
1349 struct cache_entry *ce = next_cache_entry(o);
1350 if (!ce)
1351 break;
1352 if (unpack_index_entry(ce, o) < 0)
1353 goto return_failed;
1356 mark_all_ce_unused(o->src_index);
1358 if (o->trivial_merges_only && o->nontrivial_merge) {
1359 ret = unpack_failed(o, "Merge requires file-level merging");
1360 goto done;
1363 if (!o->skip_sparse_checkout) {
1364 int empty_worktree = 1;
1367 * Sparse checkout loop #2: set NEW_SKIP_WORKTREE on entries not in loop #1
1368 * If the will have NEW_SKIP_WORKTREE, also set CE_SKIP_WORKTREE
1369 * so apply_sparse_checkout() won't attempt to remove it from worktree
1371 mark_new_skip_worktree(o->el, &o->result, CE_ADDED, CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1373 ret = 0;
1374 for (i = 0; i < o->result.cache_nr; i++) {
1375 struct cache_entry *ce = o->result.cache[i];
1378 * Entries marked with CE_ADDED in merged_entry() do not have
1379 * verify_absent() check (the check is effectively disabled
1380 * because CE_NEW_SKIP_WORKTREE is set unconditionally).
1382 * Do the real check now because we have had
1383 * correct CE_NEW_SKIP_WORKTREE
1385 if (ce->ce_flags & CE_ADDED &&
1386 verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
1387 if (!o->show_all_errors)
1388 goto return_failed;
1389 ret = -1;
1392 if (apply_sparse_checkout(&o->result, ce, o)) {
1393 if (!o->show_all_errors)
1394 goto return_failed;
1395 ret = -1;
1397 if (!ce_skip_worktree(ce))
1398 empty_worktree = 0;
1401 if (ret < 0)
1402 goto return_failed;
1404 * Sparse checkout is meant to narrow down checkout area
1405 * but it does not make sense to narrow down to empty working
1406 * tree. This is usually a mistake in sparse checkout rules.
1407 * Do not allow users to do that.
1409 if (o->result.cache_nr && empty_worktree) {
1410 ret = unpack_failed(o, "Sparse checkout leaves no entry on working directory");
1411 goto done;
1415 ret = check_updates(o) ? (-2) : 0;
1416 if (o->dst_index) {
1417 if (!ret) {
1418 if (!o->result.cache_tree)
1419 o->result.cache_tree = cache_tree();
1420 if (!cache_tree_fully_valid(o->result.cache_tree))
1421 cache_tree_update(&o->result,
1422 WRITE_TREE_SILENT |
1423 WRITE_TREE_REPAIR);
1425 move_index_extensions(&o->result, o->src_index);
1426 discard_index(o->dst_index);
1427 *o->dst_index = o->result;
1428 } else {
1429 discard_index(&o->result);
1431 o->src_index = NULL;
1433 done:
1434 clear_exclude_list(&el);
1435 return ret;
1437 return_failed:
1438 if (o->show_all_errors)
1439 display_error_msgs(o);
1440 mark_all_ce_unused(o->src_index);
1441 ret = unpack_failed(o, NULL);
1442 if (o->exiting_early)
1443 ret = 0;
1444 goto done;
1447 /* Here come the merge functions */
1449 static int reject_merge(const struct cache_entry *ce,
1450 struct unpack_trees_options *o)
1452 return o->gently ? -1 :
1453 add_rejected_path(o, ERROR_WOULD_OVERWRITE, ce->name);
1456 static int same(const struct cache_entry *a, const struct cache_entry *b)
1458 if (!!a != !!b)
1459 return 0;
1460 if (!a && !b)
1461 return 1;
1462 if ((a->ce_flags | b->ce_flags) & CE_CONFLICTED)
1463 return 0;
1464 return a->ce_mode == b->ce_mode &&
1465 !oidcmp(&a->oid, &b->oid);
1470 * When a CE gets turned into an unmerged entry, we
1471 * want it to be up-to-date
1473 static int verify_uptodate_1(const struct cache_entry *ce,
1474 struct unpack_trees_options *o,
1475 enum unpack_trees_error_types error_type)
1477 struct stat st;
1479 if (o->index_only)
1480 return 0;
1483 * CE_VALID and CE_SKIP_WORKTREE cheat, we better check again
1484 * if this entry is truly up-to-date because this file may be
1485 * overwritten.
1487 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
1488 ; /* keep checking */
1489 else if (o->reset || ce_uptodate(ce))
1490 return 0;
1492 if (!lstat(ce->name, &st)) {
1493 int flags = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE;
1494 unsigned changed = ie_match_stat(o->src_index, ce, &st, flags);
1496 if (submodule_from_ce(ce)) {
1497 int r = check_submodule_move_head(ce,
1498 "HEAD", oid_to_hex(&ce->oid), o);
1499 if (r)
1500 return o->gently ? -1 :
1501 add_rejected_path(o, error_type, ce->name);
1502 return 0;
1505 if (!changed)
1506 return 0;
1508 * Historic default policy was to allow submodule to be out
1509 * of sync wrt the superproject index. If the submodule was
1510 * not considered interesting above, we don't care here.
1512 if (S_ISGITLINK(ce->ce_mode))
1513 return 0;
1515 errno = 0;
1517 if (errno == ENOENT)
1518 return 0;
1519 return o->gently ? -1 :
1520 add_rejected_path(o, error_type, ce->name);
1523 int verify_uptodate(const struct cache_entry *ce,
1524 struct unpack_trees_options *o)
1526 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
1527 return 0;
1528 return verify_uptodate_1(ce, o, ERROR_NOT_UPTODATE_FILE);
1531 static int verify_uptodate_sparse(const struct cache_entry *ce,
1532 struct unpack_trees_options *o)
1534 return verify_uptodate_1(ce, o, ERROR_SPARSE_NOT_UPTODATE_FILE);
1537 static void invalidate_ce_path(const struct cache_entry *ce,
1538 struct unpack_trees_options *o)
1540 if (!ce)
1541 return;
1542 cache_tree_invalidate_path(o->src_index, ce->name);
1543 untracked_cache_invalidate_path(o->src_index, ce->name, 1);
1547 * Check that checking out ce->sha1 in subdir ce->name is not
1548 * going to overwrite any working files.
1550 * Currently, git does not checkout subprojects during a superproject
1551 * checkout, so it is not going to overwrite anything.
1553 static int verify_clean_submodule(const char *old_sha1,
1554 const struct cache_entry *ce,
1555 enum unpack_trees_error_types error_type,
1556 struct unpack_trees_options *o)
1558 if (!submodule_from_ce(ce))
1559 return 0;
1561 return check_submodule_move_head(ce, old_sha1,
1562 oid_to_hex(&ce->oid), o);
1565 static int verify_clean_subdirectory(const struct cache_entry *ce,
1566 enum unpack_trees_error_types error_type,
1567 struct unpack_trees_options *o)
1570 * we are about to extract "ce->name"; we would not want to lose
1571 * anything in the existing directory there.
1573 int namelen;
1574 int i;
1575 struct dir_struct d;
1576 char *pathbuf;
1577 int cnt = 0;
1579 if (S_ISGITLINK(ce->ce_mode)) {
1580 struct object_id oid;
1581 int sub_head = resolve_gitlink_ref(ce->name, "HEAD", &oid);
1583 * If we are not going to update the submodule, then
1584 * we don't care.
1586 if (!sub_head && !oidcmp(&oid, &ce->oid))
1587 return 0;
1588 return verify_clean_submodule(sub_head ? NULL : oid_to_hex(&oid),
1589 ce, error_type, o);
1593 * First let's make sure we do not have a local modification
1594 * in that directory.
1596 namelen = ce_namelen(ce);
1597 for (i = locate_in_src_index(ce, o);
1598 i < o->src_index->cache_nr;
1599 i++) {
1600 struct cache_entry *ce2 = o->src_index->cache[i];
1601 int len = ce_namelen(ce2);
1602 if (len < namelen ||
1603 strncmp(ce->name, ce2->name, namelen) ||
1604 ce2->name[namelen] != '/')
1605 break;
1607 * ce2->name is an entry in the subdirectory to be
1608 * removed.
1610 if (!ce_stage(ce2)) {
1611 if (verify_uptodate(ce2, o))
1612 return -1;
1613 add_entry(o, ce2, CE_REMOVE, 0);
1614 mark_ce_used(ce2, o);
1616 cnt++;
1620 * Then we need to make sure that we do not lose a locally
1621 * present file that is not ignored.
1623 pathbuf = xstrfmt("%.*s/", namelen, ce->name);
1625 memset(&d, 0, sizeof(d));
1626 if (o->dir)
1627 d.exclude_per_dir = o->dir->exclude_per_dir;
1628 i = read_directory(&d, &the_index, pathbuf, namelen+1, NULL);
1629 if (i)
1630 return o->gently ? -1 :
1631 add_rejected_path(o, ERROR_NOT_UPTODATE_DIR, ce->name);
1632 free(pathbuf);
1633 return cnt;
1637 * This gets called when there was no index entry for the tree entry 'dst',
1638 * but we found a file in the working tree that 'lstat()' said was fine,
1639 * and we're on a case-insensitive filesystem.
1641 * See if we can find a case-insensitive match in the index that also
1642 * matches the stat information, and assume it's that other file!
1644 static int icase_exists(struct unpack_trees_options *o, const char *name, int len, struct stat *st)
1646 const struct cache_entry *src;
1648 src = index_file_exists(o->src_index, name, len, 1);
1649 return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
1652 static int check_ok_to_remove(const char *name, int len, int dtype,
1653 const struct cache_entry *ce, struct stat *st,
1654 enum unpack_trees_error_types error_type,
1655 struct unpack_trees_options *o)
1657 const struct cache_entry *result;
1660 * It may be that the 'lstat()' succeeded even though
1661 * target 'ce' was absent, because there is an old
1662 * entry that is different only in case..
1664 * Ignore that lstat() if it matches.
1666 if (ignore_case && icase_exists(o, name, len, st))
1667 return 0;
1669 if (o->dir &&
1670 is_excluded(o->dir, &the_index, name, &dtype))
1672 * ce->name is explicitly excluded, so it is Ok to
1673 * overwrite it.
1675 return 0;
1676 if (S_ISDIR(st->st_mode)) {
1678 * We are checking out path "foo" and
1679 * found "foo/." in the working tree.
1680 * This is tricky -- if we have modified
1681 * files that are in "foo/" we would lose
1682 * them.
1684 if (verify_clean_subdirectory(ce, error_type, o) < 0)
1685 return -1;
1686 return 0;
1690 * The previous round may already have decided to
1691 * delete this path, which is in a subdirectory that
1692 * is being replaced with a blob.
1694 result = index_file_exists(&o->result, name, len, 0);
1695 if (result) {
1696 if (result->ce_flags & CE_REMOVE)
1697 return 0;
1700 return o->gently ? -1 :
1701 add_rejected_path(o, error_type, name);
1705 * We do not want to remove or overwrite a working tree file that
1706 * is not tracked, unless it is ignored.
1708 static int verify_absent_1(const struct cache_entry *ce,
1709 enum unpack_trees_error_types error_type,
1710 struct unpack_trees_options *o)
1712 int len;
1713 struct stat st;
1715 if (o->index_only || o->reset || !o->update)
1716 return 0;
1718 len = check_leading_path(ce->name, ce_namelen(ce));
1719 if (!len)
1720 return 0;
1721 else if (len > 0) {
1722 char *path;
1723 int ret;
1725 path = xmemdupz(ce->name, len);
1726 if (lstat(path, &st))
1727 ret = error_errno("cannot stat '%s'", path);
1728 else {
1729 if (submodule_from_ce(ce))
1730 ret = check_submodule_move_head(ce,
1731 oid_to_hex(&ce->oid),
1732 NULL, o);
1733 else
1734 ret = check_ok_to_remove(path, len, DT_UNKNOWN, NULL,
1735 &st, error_type, o);
1737 free(path);
1738 return ret;
1739 } else if (lstat(ce->name, &st)) {
1740 if (errno != ENOENT)
1741 return error_errno("cannot stat '%s'", ce->name);
1742 return 0;
1743 } else {
1744 if (submodule_from_ce(ce))
1745 return check_submodule_move_head(ce, oid_to_hex(&ce->oid),
1746 NULL, o);
1748 return check_ok_to_remove(ce->name, ce_namelen(ce),
1749 ce_to_dtype(ce), ce, &st,
1750 error_type, o);
1754 static int verify_absent(const struct cache_entry *ce,
1755 enum unpack_trees_error_types error_type,
1756 struct unpack_trees_options *o)
1758 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
1759 return 0;
1760 return verify_absent_1(ce, error_type, o);
1763 static int verify_absent_sparse(const struct cache_entry *ce,
1764 enum unpack_trees_error_types error_type,
1765 struct unpack_trees_options *o)
1767 enum unpack_trees_error_types orphaned_error = error_type;
1768 if (orphaned_error == ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN)
1769 orphaned_error = ERROR_WOULD_LOSE_ORPHANED_OVERWRITTEN;
1771 return verify_absent_1(ce, orphaned_error, o);
1774 static int merged_entry(const struct cache_entry *ce,
1775 const struct cache_entry *old,
1776 struct unpack_trees_options *o)
1778 int update = CE_UPDATE;
1779 struct cache_entry *merge = dup_entry(ce);
1781 if (!old) {
1783 * New index entries. In sparse checkout, the following
1784 * verify_absent() will be delayed until after
1785 * traverse_trees() finishes in unpack_trees(), then:
1787 * - CE_NEW_SKIP_WORKTREE will be computed correctly
1788 * - verify_absent() be called again, this time with
1789 * correct CE_NEW_SKIP_WORKTREE
1791 * verify_absent() call here does nothing in sparse
1792 * checkout (i.e. o->skip_sparse_checkout == 0)
1794 update |= CE_ADDED;
1795 merge->ce_flags |= CE_NEW_SKIP_WORKTREE;
1797 if (verify_absent(merge,
1798 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
1799 free(merge);
1800 return -1;
1802 invalidate_ce_path(merge, o);
1804 if (submodule_from_ce(ce)) {
1805 int ret = check_submodule_move_head(ce, NULL,
1806 oid_to_hex(&ce->oid),
1808 if (ret)
1809 return ret;
1812 } else if (!(old->ce_flags & CE_CONFLICTED)) {
1814 * See if we can re-use the old CE directly?
1815 * That way we get the uptodate stat info.
1817 * This also removes the UPDATE flag on a match; otherwise
1818 * we will end up overwriting local changes in the work tree.
1820 if (same(old, merge)) {
1821 copy_cache_entry(merge, old);
1822 update = 0;
1823 } else {
1824 if (verify_uptodate(old, o)) {
1825 free(merge);
1826 return -1;
1828 /* Migrate old flags over */
1829 update |= old->ce_flags & (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1830 invalidate_ce_path(old, o);
1833 if (submodule_from_ce(ce)) {
1834 int ret = check_submodule_move_head(ce, oid_to_hex(&old->oid),
1835 oid_to_hex(&ce->oid),
1837 if (ret)
1838 return ret;
1840 } else {
1842 * Previously unmerged entry left as an existence
1843 * marker by read_index_unmerged();
1845 invalidate_ce_path(old, o);
1848 do_add_entry(o, merge, update, CE_STAGEMASK);
1849 return 1;
1852 static int deleted_entry(const struct cache_entry *ce,
1853 const struct cache_entry *old,
1854 struct unpack_trees_options *o)
1856 /* Did it exist in the index? */
1857 if (!old) {
1858 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
1859 return -1;
1860 return 0;
1862 if (!(old->ce_flags & CE_CONFLICTED) && verify_uptodate(old, o))
1863 return -1;
1864 add_entry(o, ce, CE_REMOVE, 0);
1865 invalidate_ce_path(ce, o);
1866 return 1;
1869 static int keep_entry(const struct cache_entry *ce,
1870 struct unpack_trees_options *o)
1872 add_entry(o, ce, 0, 0);
1873 return 1;
1876 #if DBRT_DEBUG
1877 static void show_stage_entry(FILE *o,
1878 const char *label, const struct cache_entry *ce)
1880 if (!ce)
1881 fprintf(o, "%s (missing)\n", label);
1882 else
1883 fprintf(o, "%s%06o %s %d\t%s\n",
1884 label,
1885 ce->ce_mode,
1886 oid_to_hex(&ce->oid),
1887 ce_stage(ce),
1888 ce->name);
1890 #endif
1892 int threeway_merge(const struct cache_entry * const *stages,
1893 struct unpack_trees_options *o)
1895 const struct cache_entry *index;
1896 const struct cache_entry *head;
1897 const struct cache_entry *remote = stages[o->head_idx + 1];
1898 int count;
1899 int head_match = 0;
1900 int remote_match = 0;
1902 int df_conflict_head = 0;
1903 int df_conflict_remote = 0;
1905 int any_anc_missing = 0;
1906 int no_anc_exists = 1;
1907 int i;
1909 for (i = 1; i < o->head_idx; i++) {
1910 if (!stages[i] || stages[i] == o->df_conflict_entry)
1911 any_anc_missing = 1;
1912 else
1913 no_anc_exists = 0;
1916 index = stages[0];
1917 head = stages[o->head_idx];
1919 if (head == o->df_conflict_entry) {
1920 df_conflict_head = 1;
1921 head = NULL;
1924 if (remote == o->df_conflict_entry) {
1925 df_conflict_remote = 1;
1926 remote = NULL;
1930 * First, if there's a #16 situation, note that to prevent #13
1931 * and #14.
1933 if (!same(remote, head)) {
1934 for (i = 1; i < o->head_idx; i++) {
1935 if (same(stages[i], head)) {
1936 head_match = i;
1938 if (same(stages[i], remote)) {
1939 remote_match = i;
1945 * We start with cases where the index is allowed to match
1946 * something other than the head: #14(ALT) and #2ALT, where it
1947 * is permitted to match the result instead.
1949 /* #14, #14ALT, #2ALT */
1950 if (remote && !df_conflict_head && head_match && !remote_match) {
1951 if (index && !same(index, remote) && !same(index, head))
1952 return reject_merge(index, o);
1953 return merged_entry(remote, index, o);
1956 * If we have an entry in the index cache, then we want to
1957 * make sure that it matches head.
1959 if (index && !same(index, head))
1960 return reject_merge(index, o);
1962 if (head) {
1963 /* #5ALT, #15 */
1964 if (same(head, remote))
1965 return merged_entry(head, index, o);
1966 /* #13, #3ALT */
1967 if (!df_conflict_remote && remote_match && !head_match)
1968 return merged_entry(head, index, o);
1971 /* #1 */
1972 if (!head && !remote && any_anc_missing)
1973 return 0;
1976 * Under the "aggressive" rule, we resolve mostly trivial
1977 * cases that we historically had git-merge-one-file resolve.
1979 if (o->aggressive) {
1980 int head_deleted = !head;
1981 int remote_deleted = !remote;
1982 const struct cache_entry *ce = NULL;
1984 if (index)
1985 ce = index;
1986 else if (head)
1987 ce = head;
1988 else if (remote)
1989 ce = remote;
1990 else {
1991 for (i = 1; i < o->head_idx; i++) {
1992 if (stages[i] && stages[i] != o->df_conflict_entry) {
1993 ce = stages[i];
1994 break;
2000 * Deleted in both.
2001 * Deleted in one and unchanged in the other.
2003 if ((head_deleted && remote_deleted) ||
2004 (head_deleted && remote && remote_match) ||
2005 (remote_deleted && head && head_match)) {
2006 if (index)
2007 return deleted_entry(index, index, o);
2008 if (ce && !head_deleted) {
2009 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2010 return -1;
2012 return 0;
2015 * Added in both, identically.
2017 if (no_anc_exists && head && remote && same(head, remote))
2018 return merged_entry(head, index, o);
2022 /* Below are "no merge" cases, which require that the index be
2023 * up-to-date to avoid the files getting overwritten with
2024 * conflict resolution files.
2026 if (index) {
2027 if (verify_uptodate(index, o))
2028 return -1;
2031 o->nontrivial_merge = 1;
2033 /* #2, #3, #4, #6, #7, #9, #10, #11. */
2034 count = 0;
2035 if (!head_match || !remote_match) {
2036 for (i = 1; i < o->head_idx; i++) {
2037 if (stages[i] && stages[i] != o->df_conflict_entry) {
2038 keep_entry(stages[i], o);
2039 count++;
2040 break;
2044 #if DBRT_DEBUG
2045 else {
2046 fprintf(stderr, "read-tree: warning #16 detected\n");
2047 show_stage_entry(stderr, "head ", stages[head_match]);
2048 show_stage_entry(stderr, "remote ", stages[remote_match]);
2050 #endif
2051 if (head) { count += keep_entry(head, o); }
2052 if (remote) { count += keep_entry(remote, o); }
2053 return count;
2057 * Two-way merge.
2059 * The rule is to "carry forward" what is in the index without losing
2060 * information across a "fast-forward", favoring a successful merge
2061 * over a merge failure when it makes sense. For details of the
2062 * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
2065 int twoway_merge(const struct cache_entry * const *src,
2066 struct unpack_trees_options *o)
2068 const struct cache_entry *current = src[0];
2069 const struct cache_entry *oldtree = src[1];
2070 const struct cache_entry *newtree = src[2];
2072 if (o->merge_size != 2)
2073 return error("Cannot do a twoway merge of %d trees",
2074 o->merge_size);
2076 if (oldtree == o->df_conflict_entry)
2077 oldtree = NULL;
2078 if (newtree == o->df_conflict_entry)
2079 newtree = NULL;
2081 if (current) {
2082 if (current->ce_flags & CE_CONFLICTED) {
2083 if (same(oldtree, newtree) || o->reset) {
2084 if (!newtree)
2085 return deleted_entry(current, current, o);
2086 else
2087 return merged_entry(newtree, current, o);
2089 return reject_merge(current, o);
2090 } else if ((!oldtree && !newtree) || /* 4 and 5 */
2091 (!oldtree && newtree &&
2092 same(current, newtree)) || /* 6 and 7 */
2093 (oldtree && newtree &&
2094 same(oldtree, newtree)) || /* 14 and 15 */
2095 (oldtree && newtree &&
2096 !same(oldtree, newtree) && /* 18 and 19 */
2097 same(current, newtree))) {
2098 return keep_entry(current, o);
2099 } else if (oldtree && !newtree && same(current, oldtree)) {
2100 /* 10 or 11 */
2101 return deleted_entry(oldtree, current, o);
2102 } else if (oldtree && newtree &&
2103 same(current, oldtree) && !same(current, newtree)) {
2104 /* 20 or 21 */
2105 return merged_entry(newtree, current, o);
2106 } else
2107 return reject_merge(current, o);
2109 else if (newtree) {
2110 if (oldtree && !o->initial_checkout) {
2112 * deletion of the path was staged;
2114 if (same(oldtree, newtree))
2115 return 1;
2116 return reject_merge(oldtree, o);
2118 return merged_entry(newtree, current, o);
2120 return deleted_entry(oldtree, current, o);
2124 * Bind merge.
2126 * Keep the index entries at stage0, collapse stage1 but make sure
2127 * stage0 does not have anything there.
2129 int bind_merge(const struct cache_entry * const *src,
2130 struct unpack_trees_options *o)
2132 const struct cache_entry *old = src[0];
2133 const struct cache_entry *a = src[1];
2135 if (o->merge_size != 1)
2136 return error("Cannot do a bind merge of %d trees",
2137 o->merge_size);
2138 if (a && old)
2139 return o->gently ? -1 :
2140 error(ERRORMSG(o, ERROR_BIND_OVERLAP),
2141 super_prefixed(a->name),
2142 super_prefixed(old->name));
2143 if (!a)
2144 return keep_entry(old, o);
2145 else
2146 return merged_entry(a, NULL, o);
2150 * One-way merge.
2152 * The rule is:
2153 * - take the stat information from stage0, take the data from stage1
2155 int oneway_merge(const struct cache_entry * const *src,
2156 struct unpack_trees_options *o)
2158 const struct cache_entry *old = src[0];
2159 const struct cache_entry *a = src[1];
2161 if (o->merge_size != 1)
2162 return error("Cannot do a oneway merge of %d trees",
2163 o->merge_size);
2165 if (!a || a == o->df_conflict_entry)
2166 return deleted_entry(old, old, o);
2168 if (old && same(old, a)) {
2169 int update = 0;
2170 if (o->reset && o->update && !ce_uptodate(old) && !ce_skip_worktree(old)) {
2171 struct stat st;
2172 if (lstat(old->name, &st) ||
2173 ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE))
2174 update |= CE_UPDATE;
2176 if (o->update && S_ISGITLINK(old->ce_mode) &&
2177 should_update_submodules() && !verify_uptodate(old, o))
2178 update |= CE_UPDATE;
2179 add_entry(o, old, update, 0);
2180 return 0;
2182 return merged_entry(a, old, o);