interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / unpack-trees.c

3075 lines · 86789 bytes Raw Blame History
1#define USE_THE_REPOSITORY_VARIABLE
2#define DISABLE_SIGN_COMPARE_WARNINGS
3
4#include "git-compat-util.h"
5#include "advice.h"
6#include "strvec.h"
7#include "repository.h"
8#include "parse.h"
9#include "dir.h"
10#include "environment.h"
11#include "gettext.h"
12#include "hex.h"
13#include "name-hash.h"
14#include "tree.h"
15#include "tree-walk.h"
16#include "cache-tree.h"
17#include "unpack-trees.h"
18#include "progress.h"
19#include "refs.h"
20#include "attr.h"
21#include "read-cache.h"
22#include "split-index.h"
23#include "sparse-index.h"
24#include "submodule.h"
25#include "submodule-config.h"
26#include "symlinks.h"
27#include "trace2.h"
28#include "fsmonitor.h"
29#include "odb.h"
30#include "promisor-remote.h"
31#include "entry.h"
32#include "parallel-checkout.h"
33#include "setup.h"
34
35/*
36 * Error messages expected by scripts out of plumbing commands such as
37 * read-tree. Non-scripted Porcelain is not required to use these messages
38 * and in fact are encouraged to reword them to better suit their particular
39 * situation better. See how "git checkout" and "git merge" replaces
40 * them using setup_unpack_trees_porcelain(), for example.
41 */
42static const char *unpack_plumbing_errors[NB_UNPACK_TREES_WARNING_TYPES] = {
43 /* ERROR_WOULD_OVERWRITE */
44 "Entry '%s' would be overwritten by merge. Cannot merge.",
45
46 /* ERROR_NOT_UPTODATE_FILE */
47 "Entry '%s' not uptodate. Cannot merge.",
48
49 /* ERROR_NOT_UPTODATE_DIR */
50 "Updating '%s' would lose untracked files in it",
51
52 /* ERROR_CWD_IN_THE_WAY */
53 "Refusing to remove '%s' since it is the current working directory.",
54
55 /* ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN */
56 "Untracked working tree file '%s' would be overwritten by merge.",
57
58 /* ERROR_WOULD_LOSE_UNTRACKED_REMOVED */
59 "Untracked working tree file '%s' would be removed by merge.",
60
61 /* ERROR_BIND_OVERLAP */
62 "Entry '%s' overlaps with '%s'. Cannot bind.",
63
64 /* ERROR_WOULD_LOSE_SUBMODULE */
65 "Submodule '%s' cannot checkout new HEAD.",
66
67 /* NB_UNPACK_TREES_ERROR_TYPES; just a meta value */
68 "",
69
70 /* WARNING_SPARSE_NOT_UPTODATE_FILE */
71 "Path '%s' not uptodate; will not remove from working tree.",
72
73 /* WARNING_SPARSE_UNMERGED_FILE */
74 "Path '%s' unmerged; will not remove from working tree.",
75
76 /* WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN */
77 "Path '%s' already present; will not overwrite with sparse update.",
78};
79
80#define ERRORMSG(o,type) \
81 ( ((o) && (o)->internal.msgs[(type)]) \
82 ? ((o)->internal.msgs[(type)]) \
83 : (unpack_plumbing_errors[(type)]) )
84
85static const char *super_prefixed(const char *path, const char *super_prefix)
86{
87 /*
88 * It is necessary and sufficient to have two static buffers
89 * here, as the return value of this function is fed to
90 * error() using the unpack_*_errors[] templates we see above.
91 */
92 static struct strbuf buf[2] = {STRBUF_INIT, STRBUF_INIT};
93 static int super_prefix_len = -1;
94 static unsigned idx = ARRAY_SIZE(buf) - 1;
95
96 if (super_prefix_len < 0) {
97 if (!super_prefix) {
98 super_prefix_len = 0;
99 } else {
100 int i;
101 for (i = 0; i < ARRAY_SIZE(buf); i++)
102 strbuf_addstr(&buf[i], super_prefix);
103 super_prefix_len = buf[0].len;
104 }
105 }
106
107 if (!super_prefix_len)
108 return path;
109
110 if (++idx >= ARRAY_SIZE(buf))
111 idx = 0;
112
113 strbuf_setlen(&buf[idx], super_prefix_len);
114 strbuf_addstr(&buf[idx], path);
115
116 return buf[idx].buf;
117}
118
119void setup_unpack_trees_porcelain(struct unpack_trees_options *opts,
120 const char *cmd)
121{
122 int i;
123 const char **msgs = opts->internal.msgs;
124 const char *msg;
125
126 strvec_init(&opts->internal.msgs_to_free);
127
128 if (!strcmp(cmd, "checkout"))
129 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
130 ? _("Your local changes to the following files would be overwritten by checkout:\n%%s"
131 "Please commit your changes or stash them before you switch branches.")
132 : _("Your local changes to the following files would be overwritten by checkout:\n%%s");
133 else if (!strcmp(cmd, "merge"))
134 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
135 ? _("Your local changes to the following files would be overwritten by merge:\n%%s"
136 "Please commit your changes or stash them before you merge.")
137 : _("Your local changes to the following files would be overwritten by merge:\n%%s");
138 else
139 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
140 ? _("Your local changes to the following files would be overwritten by %s:\n%%s"
141 "Please commit your changes or stash them before you %s.")
142 : _("Your local changes to the following files would be overwritten by %s:\n%%s");
143 msgs[ERROR_WOULD_OVERWRITE] = msgs[ERROR_NOT_UPTODATE_FILE] =
144 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
145
146 msgs[ERROR_NOT_UPTODATE_DIR] =
147 _("Updating the following directories would lose untracked files in them:\n%s");
148
149 msgs[ERROR_CWD_IN_THE_WAY] =
150 _("Refusing to remove the current working directory:\n%s");
151
152 if (!strcmp(cmd, "checkout"))
153 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
154 ? _("The following untracked working tree files would be removed by checkout:\n%%s"
155 "Please move or remove them before you switch branches.")
156 : _("The following untracked working tree files would be removed by checkout:\n%%s");
157 else if (!strcmp(cmd, "merge"))
158 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
159 ? _("The following untracked working tree files would be removed by merge:\n%%s"
160 "Please move or remove them before you merge.")
161 : _("The following untracked working tree files would be removed by merge:\n%%s");
162 else
163 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
164 ? _("The following untracked working tree files would be removed by %s:\n%%s"
165 "Please move or remove them before you %s.")
166 : _("The following untracked working tree files would be removed by %s:\n%%s");
167 msgs[ERROR_WOULD_LOSE_UNTRACKED_REMOVED] =
168 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
169
170 if (!strcmp(cmd, "checkout"))
171 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
172 ? _("The following untracked working tree files would be overwritten by checkout:\n%%s"
173 "Please move or remove them before you switch branches.")
174 : _("The following untracked working tree files would be overwritten by checkout:\n%%s");
175 else if (!strcmp(cmd, "merge"))
176 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
177 ? _("The following untracked working tree files would be overwritten by merge:\n%%s"
178 "Please move or remove them before you merge.")
179 : _("The following untracked working tree files would be overwritten by merge:\n%%s");
180 else
181 msg = advice_enabled(ADVICE_COMMIT_BEFORE_MERGE)
182 ? _("The following untracked working tree files would be overwritten by %s:\n%%s"
183 "Please move or remove them before you %s.")
184 : _("The following untracked working tree files would be overwritten by %s:\n%%s");
185 msgs[ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN] =
186 strvec_pushf(&opts->internal.msgs_to_free, msg, cmd, cmd);
187
188 /*
189 * Special case: ERROR_BIND_OVERLAP refers to a pair of paths, we
190 * cannot easily display it as a list.
191 */
192 msgs[ERROR_BIND_OVERLAP] = _("Entry '%s' overlaps with '%s'. Cannot bind.");
193
194 msgs[ERROR_WOULD_LOSE_SUBMODULE] =
195 _("Cannot update submodule:\n%s");
196
197 msgs[WARNING_SPARSE_NOT_UPTODATE_FILE] =
198 _("The following paths are not up to date and were left despite sparse patterns:\n%s");
199 msgs[WARNING_SPARSE_UNMERGED_FILE] =
200 _("The following paths are unmerged and were left despite sparse patterns:\n%s");
201 msgs[WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN] =
202 _("The following paths were already present and thus not updated despite sparse patterns:\n%s");
203
204 opts->internal.show_all_errors = 1;
205 /* rejected paths may not have a static buffer */
206 for (i = 0; i < ARRAY_SIZE(opts->internal.unpack_rejects); i++)
207 opts->internal.unpack_rejects[i].strdup_strings = 1;
208}
209
210void clear_unpack_trees_porcelain(struct unpack_trees_options *opts)
211{
212 strvec_clear(&opts->internal.msgs_to_free);
213 memset(opts->internal.msgs, 0, sizeof(opts->internal.msgs));
214 discard_index(&opts->internal.result);
215}
216
217static int do_add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
218 unsigned int set, unsigned int clear)
219{
220 clear |= CE_HASHED;
221
222 if (set & CE_REMOVE)
223 set |= CE_WT_REMOVE;
224
225 ce->ce_flags = (ce->ce_flags & ~clear) | set;
226 return add_index_entry(&o->internal.result, ce,
227 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
228}
229
230static void add_entry(struct unpack_trees_options *o,
231 const struct cache_entry *ce,
232 unsigned int set, unsigned int clear)
233{
234 do_add_entry(o, dup_cache_entry(ce, &o->internal.result), set, clear);
235}
236
237/*
238 * add error messages on path <path>
239 * corresponding to the type <e> with the message <msg>
240 * indicating if it should be display in porcelain or not
241 */
242static int add_rejected_path(struct unpack_trees_options *o,
243 enum unpack_trees_error_types e,
244 const char *path)
245{
246 if (o->quiet)
247 return -1;
248
249 if (!o->internal.show_all_errors)
250 return error(ERRORMSG(o, e), super_prefixed(path,
251 o->super_prefix));
252
253 /*
254 * Otherwise, insert in a list for future display by
255 * display_(error|warning)_msgs()
256 */
257 string_list_append(&o->internal.unpack_rejects[e], path);
258 return -1;
259}
260
261/*
262 * display all the error messages stored in a nice way
263 */
264static void display_error_msgs(struct unpack_trees_options *o)
265{
266 int e;
267 unsigned error_displayed = 0;
268 for (e = 0; e < NB_UNPACK_TREES_ERROR_TYPES; e++) {
269 struct string_list *rejects = &o->internal.unpack_rejects[e];
270
271 if (rejects->nr > 0) {
272 int i;
273 struct strbuf path = STRBUF_INIT;
274
275 error_displayed = 1;
276 for (i = 0; i < rejects->nr; i++)
277 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
278 error(ERRORMSG(o, e), super_prefixed(path.buf,
279 o->super_prefix));
280 strbuf_release(&path);
281 }
282 string_list_clear(rejects, 0);
283 }
284 if (error_displayed)
285 fprintf(stderr, _("Aborting\n"));
286}
287
288/*
289 * display all the warning messages stored in a nice way
290 */
291static void display_warning_msgs(struct unpack_trees_options *o)
292{
293 int e;
294 unsigned warning_displayed = 0;
295 for (e = NB_UNPACK_TREES_ERROR_TYPES + 1;
296 e < NB_UNPACK_TREES_WARNING_TYPES; e++) {
297 struct string_list *rejects = &o->internal.unpack_rejects[e];
298
299 if (rejects->nr > 0) {
300 int i;
301 struct strbuf path = STRBUF_INIT;
302
303 warning_displayed = 1;
304 for (i = 0; i < rejects->nr; i++)
305 strbuf_addf(&path, "\t%s\n", rejects->items[i].string);
306 warning(ERRORMSG(o, e), super_prefixed(path.buf,
307 o->super_prefix));
308 strbuf_release(&path);
309 }
310 string_list_clear(rejects, 0);
311 }
312 if (warning_displayed)
313 fprintf(stderr, _("After fixing the above paths, you may want to run `git sparse-checkout reapply`.\n"));
314}
315static int check_submodule_move_head(const struct cache_entry *ce,
316 const char *old_id,
317 const char *new_id,
318 struct unpack_trees_options *o)
319{
320 unsigned flags = SUBMODULE_MOVE_HEAD_DRY_RUN;
321 const struct submodule *sub = submodule_from_ce(ce);
322
323 if (!sub)
324 return 0;
325
326 if (o->reset)
327 flags |= SUBMODULE_MOVE_HEAD_FORCE;
328
329 if (submodule_move_head(ce->name, o->super_prefix, old_id, new_id,
330 flags))
331 return add_rejected_path(o, ERROR_WOULD_LOSE_SUBMODULE, ce->name);
332 return 0;
333}
334
335/*
336 * Perform the loading of the repository's gitmodules file. This function is
337 * used by 'check_update()' to perform loading of the gitmodules file in two
338 * different situations:
339 * (1) before removing entries from the working tree if the gitmodules file has
340 * been marked for removal. This situation is specified by 'state' == NULL.
341 * (2) before checking out entries to the working tree if the gitmodules file
342 * has been marked for update. This situation is specified by 'state' != NULL.
343 */
344static void load_gitmodules_file(struct index_state *index,
345 struct checkout *state)
346{
347 int pos = index_name_pos(index, GITMODULES_FILE, strlen(GITMODULES_FILE));
348
349 if (pos >= 0) {
350 struct cache_entry *ce = index->cache[pos];
351 if (!state && ce->ce_flags & CE_WT_REMOVE) {
352 repo_read_gitmodules(the_repository, 0);
353 } else if (state && (ce->ce_flags & CE_UPDATE)) {
354 submodule_free(the_repository);
355 checkout_entry(ce, state, NULL, NULL);
356 repo_read_gitmodules(the_repository, 0);
357 }
358 }
359}
360
361static struct progress *get_progress(struct unpack_trees_options *o,
362 struct index_state *index)
363{
364 unsigned cnt = 0, total = 0;
365
366 if (!o->update || !o->verbose_update)
367 return NULL;
368
369 for (; cnt < index->cache_nr; cnt++) {
370 const struct cache_entry *ce = index->cache[cnt];
371 if (ce->ce_flags & (CE_UPDATE | CE_WT_REMOVE))
372 total++;
373 }
374
375 return start_delayed_progress(the_repository,
376 _("Updating files"), total);
377}
378
379static void setup_collided_checkout_detection(struct checkout *state,
380 struct index_state *index)
381{
382 int i;
383
384 state->clone = 1;
385 for (i = 0; i < index->cache_nr; i++)
386 index->cache[i]->ce_flags &= ~CE_MATCHED;
387}
388
389static void report_collided_checkout(struct index_state *index)
390{
391 struct string_list list = STRING_LIST_INIT_NODUP;
392 int i;
393
394 for (i = 0; i < index->cache_nr; i++) {
395 struct cache_entry *ce = index->cache[i];
396
397 if (!(ce->ce_flags & CE_MATCHED))
398 continue;
399
400 string_list_append(&list, ce->name);
401 ce->ce_flags &= ~CE_MATCHED;
402 }
403
404 list.cmp = fspathcmp;
405 string_list_sort(&list);
406
407 if (list.nr) {
408 warning(_("the following paths have collided (e.g. case-sensitive paths\n"
409 "on a case-insensitive filesystem) and only one from the same\n"
410 "colliding group is in the working tree:\n"));
411
412 for (i = 0; i < list.nr; i++)
413 fprintf(stderr, " '%s'\n", list.items[i].string);
414 }
415
416 string_list_clear(&list, 0);
417}
418
419static int must_checkout(const struct cache_entry *ce,
420 void *cb_data UNUSED)
421{
422 return ce->ce_flags & CE_UPDATE;
423}
424
425static int check_updates(struct unpack_trees_options *o,
426 struct index_state *index)
427{
428 unsigned cnt = 0;
429 int errs = 0;
430 struct progress *progress;
431 struct checkout state = CHECKOUT_INIT;
432 int i, pc_workers, pc_threshold;
433
434 trace_performance_enter();
435 state.super_prefix = o->super_prefix;
436 state.force = 1;
437 state.quiet = 1;
438 state.refresh_cache = 1;
439 state.istate = index;
440 clone_checkout_metadata(&state.meta, &o->meta, NULL);
441
442 if (!o->update || o->dry_run) {
443 remove_marked_cache_entries(index, 0);
444 trace_performance_leave("check_updates");
445 return 0;
446 }
447
448 if (o->clone)
449 setup_collided_checkout_detection(&state, index);
450
451 progress = get_progress(o, index);
452
453 /* Start with clean cache to avoid using any possibly outdated info. */
454 invalidate_lstat_cache();
455
456 git_attr_set_direction(GIT_ATTR_CHECKOUT);
457
458 if (should_update_submodules())
459 load_gitmodules_file(index, NULL);
460
461 for (i = 0; i < index->cache_nr; i++) {
462 const struct cache_entry *ce = index->cache[i];
463
464 if (ce->ce_flags & CE_WT_REMOVE) {
465 display_progress(progress, ++cnt);
466 unlink_entry(ce, o->super_prefix);
467 }
468 }
469
470 remove_marked_cache_entries(index, 0);
471 remove_scheduled_dirs();
472
473 if (should_update_submodules())
474 load_gitmodules_file(index, &state);
475
476 if (repo_has_promisor_remote(the_repository))
477 /*
478 * Prefetch the objects that are to be checked out in the loop
479 * below.
480 */
481 prefetch_cache_entries(index, must_checkout, NULL);
482
483 get_parallel_checkout_configs(&pc_workers, &pc_threshold);
484
485 enable_delayed_checkout(&state);
486 if (pc_workers > 1)
487 init_parallel_checkout();
488 for (i = 0; i < index->cache_nr; i++) {
489 struct cache_entry *ce = index->cache[i];
490
491 if (must_checkout(ce, NULL)) {
492 size_t last_pc_queue_size = pc_queue_size();
493
494 if (ce->ce_flags & CE_WT_REMOVE)
495 BUG("both update and delete flags are set on %s",
496 ce->name);
497 ce->ce_flags &= ~CE_UPDATE;
498 errs |= checkout_entry(ce, &state, NULL, NULL);
499
500 if (last_pc_queue_size == pc_queue_size())
501 display_progress(progress, ++cnt);
502 }
503 }
504 if (pc_workers > 1)
505 errs |= run_parallel_checkout(&state, pc_workers, pc_threshold,
506 progress, &cnt);
507 stop_progress(&progress);
508 errs |= finish_delayed_checkout(&state, o->verbose_update);
509 git_attr_set_direction(GIT_ATTR_CHECKIN);
510
511 if (o->clone)
512 report_collided_checkout(index);
513
514 trace_performance_leave("check_updates");
515 return errs != 0;
516}
517
518static int verify_uptodate_sparse(const struct cache_entry *ce,
519 struct unpack_trees_options *o);
520static int verify_absent_sparse(const struct cache_entry *ce,
521 enum unpack_trees_error_types,
522 struct unpack_trees_options *o);
523
524static int apply_sparse_checkout(struct index_state *istate,
525 struct cache_entry *ce,
526 struct unpack_trees_options *o)
527{
528 int was_skip_worktree = ce_skip_worktree(ce);
529
530 if (ce->ce_flags & CE_NEW_SKIP_WORKTREE)
531 ce->ce_flags |= CE_SKIP_WORKTREE;
532 else
533 ce->ce_flags &= ~CE_SKIP_WORKTREE;
534 if (was_skip_worktree != ce_skip_worktree(ce)) {
535 ce->ce_flags |= CE_UPDATE_IN_BASE;
536 mark_fsmonitor_invalid(istate, ce);
537 istate->cache_changed |= CE_ENTRY_CHANGED;
538 }
539
540 /*
541 * if (!was_skip_worktree && !ce_skip_worktree()) {
542 * This is perfectly normal. Move on;
543 * }
544 */
545
546 /*
547 * Merge strategies may set CE_UPDATE|CE_REMOVE outside checkout
548 * area as a result of ce_skip_worktree() shortcuts in
549 * verify_absent() and verify_uptodate().
550 * Make sure they don't modify worktree if they are already
551 * outside checkout area
552 */
553 if (was_skip_worktree && ce_skip_worktree(ce)) {
554 ce->ce_flags &= ~CE_UPDATE;
555
556 /*
557 * By default, when CE_REMOVE is on, CE_WT_REMOVE is also
558 * on to get that file removed from both index and worktree.
559 * If that file is already outside worktree area, don't
560 * bother remove it.
561 */
562 if (ce->ce_flags & CE_REMOVE)
563 ce->ce_flags &= ~CE_WT_REMOVE;
564 }
565
566 if (!was_skip_worktree && ce_skip_worktree(ce)) {
567 /*
568 * If CE_UPDATE is set, verify_uptodate() must be called already
569 * also stat info may have lost after merged_entry() so calling
570 * verify_uptodate() again may fail
571 */
572 if (!(ce->ce_flags & CE_UPDATE) &&
573 verify_uptodate_sparse(ce, o)) {
574 ce->ce_flags &= ~CE_SKIP_WORKTREE;
575 return -1;
576 }
577 ce->ce_flags |= CE_WT_REMOVE;
578 ce->ce_flags &= ~CE_UPDATE;
579 }
580 if (was_skip_worktree && !ce_skip_worktree(ce)) {
581 if (verify_absent_sparse(ce, WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN, o))
582 return -1;
583 ce->ce_flags |= CE_UPDATE;
584 }
585 return 0;
586}
587
588static int warn_conflicted_path(struct index_state *istate,
589 int i,
590 struct unpack_trees_options *o)
591{
592 char *conflicting_path = istate->cache[i]->name;
593 int count = 0;
594
595 add_rejected_path(o, WARNING_SPARSE_UNMERGED_FILE, conflicting_path);
596
597 /* Find out how many higher stage entries are at same path */
598 while ((++count) + i < istate->cache_nr &&
599 !strcmp(conflicting_path, istate->cache[count + i]->name))
600 ; /* do nothing */
601
602 return count;
603}
604
605static inline int call_unpack_fn(const struct cache_entry * const *src,
606 struct unpack_trees_options *o)
607{
608 int ret = o->fn(src, o);
609 if (ret > 0)
610 ret = 0;
611 return ret;
612}
613
614static void mark_ce_used(struct cache_entry *ce, struct unpack_trees_options *o)
615{
616 ce->ce_flags |= CE_UNPACKED;
617
618 if (o->internal.cache_bottom < o->src_index->cache_nr &&
619 o->src_index->cache[o->internal.cache_bottom] == ce) {
620 int bottom = o->internal.cache_bottom;
621
622 while (bottom < o->src_index->cache_nr &&
623 o->src_index->cache[bottom]->ce_flags & CE_UNPACKED)
624 bottom++;
625 o->internal.cache_bottom = bottom;
626 }
627}
628
629static void mark_all_ce_unused(struct index_state *index)
630{
631 int i;
632 for (i = 0; i < index->cache_nr; i++)
633 index->cache[i]->ce_flags &= ~(CE_UNPACKED | CE_ADDED | CE_NEW_SKIP_WORKTREE);
634}
635
636static int locate_in_src_index(const struct cache_entry *ce,
637 struct unpack_trees_options *o)
638{
639 struct index_state *index = o->src_index;
640 int len = ce_namelen(ce);
641 int pos = index_name_pos(index, ce->name, len);
642 if (pos < 0)
643 pos = -1 - pos;
644 return pos;
645}
646
647/*
648 * We call unpack_index_entry() with an unmerged cache entry
649 * only in diff-index, and it wants a single callback. Skip
650 * the other unmerged entry with the same name.
651 */
652static void mark_ce_used_same_name(struct cache_entry *ce,
653 struct unpack_trees_options *o)
654{
655 struct index_state *index = o->src_index;
656 int len = ce_namelen(ce);
657 int pos;
658
659 for (pos = locate_in_src_index(ce, o); pos < index->cache_nr; pos++) {
660 struct cache_entry *next = index->cache[pos];
661 if (len != ce_namelen(next) ||
662 memcmp(ce->name, next->name, len))
663 break;
664 mark_ce_used(next, o);
665 }
666}
667
668static struct cache_entry *next_cache_entry(struct unpack_trees_options *o)
669{
670 const struct index_state *index = o->src_index;
671 int pos = o->internal.cache_bottom;
672
673 while (pos < index->cache_nr) {
674 struct cache_entry *ce = index->cache[pos];
675 if (!(ce->ce_flags & CE_UNPACKED)) {
676 o->internal.cache_bottom = pos;
677 return ce;
678 }
679 pos++;
680 }
681 return NULL;
682}
683
684static void add_same_unmerged(const struct cache_entry *ce,
685 struct unpack_trees_options *o)
686{
687 struct index_state *index = o->src_index;
688 int len = ce_namelen(ce);
689 int pos = index_name_pos(index, ce->name, len);
690
691 if (0 <= pos)
692 die("programming error in a caller of mark_ce_used_same_name");
693 for (pos = -pos - 1; pos < index->cache_nr; pos++) {
694 struct cache_entry *next = index->cache[pos];
695 if (len != ce_namelen(next) ||
696 memcmp(ce->name, next->name, len))
697 break;
698 add_entry(o, next, 0, 0);
699 mark_ce_used(next, o);
700 }
701}
702
703static int unpack_index_entry(struct cache_entry *ce,
704 struct unpack_trees_options *o)
705{
706 const struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
707 int ret;
708
709 src[0] = ce;
710
711 mark_ce_used(ce, o);
712 if (ce_stage(ce)) {
713 if (o->skip_unmerged) {
714 add_entry(o, ce, 0, 0);
715 return 0;
716 }
717 }
718 ret = call_unpack_fn(src, o);
719 if (ce_stage(ce))
720 mark_ce_used_same_name(ce, o);
721 return ret;
722}
723
724static int find_cache_pos(struct traverse_info *, const char *p, size_t len);
725
726static void restore_cache_bottom(struct traverse_info *info, int bottom)
727{
728 struct unpack_trees_options *o = info->data;
729
730 if (o->diff_index_cached)
731 return;
732 o->internal.cache_bottom = bottom;
733}
734
735static int switch_cache_bottom(struct traverse_info *info)
736{
737 struct unpack_trees_options *o = info->data;
738 int ret, pos;
739
740 if (o->diff_index_cached)
741 return 0;
742 ret = o->internal.cache_bottom;
743 pos = find_cache_pos(info->prev, info->name, info->namelen);
744
745 if (pos < -1)
746 o->internal.cache_bottom = -2 - pos;
747 else if (pos < 0)
748 o->internal.cache_bottom = o->src_index->cache_nr;
749 return ret;
750}
751
752static inline int are_same_oid(struct name_entry *name_j, struct name_entry *name_k)
753{
754 return !is_null_oid(&name_j->oid) && !is_null_oid(&name_k->oid) && oideq(&name_j->oid, &name_k->oid);
755}
756
757static int all_trees_same_as_cache_tree(int n, unsigned long dirmask,
758 struct name_entry *names,
759 struct traverse_info *info)
760{
761 struct unpack_trees_options *o = info->data;
762 int i;
763
764 if (!o->merge || dirmask != ((1 << n) - 1))
765 return 0;
766
767 for (i = 1; i < n; i++)
768 if (!are_same_oid(names, names + i))
769 return 0;
770
771 return cache_tree_matches_traversal(o->src_index->cache_tree, names, info);
772}
773
774static int index_pos_by_traverse_info(struct name_entry *names,
775 struct traverse_info *info)
776{
777 struct unpack_trees_options *o = info->data;
778 struct strbuf name = STRBUF_INIT;
779 int pos;
780
781 strbuf_make_traverse_path(&name, info, names->path, names->pathlen);
782 strbuf_addch(&name, '/');
783 pos = index_name_pos(o->src_index, name.buf, name.len);
784 if (pos >= 0) {
785 if (!o->src_index->sparse_index ||
786 !(o->src_index->cache[pos]->ce_flags & CE_SKIP_WORKTREE))
787 BUG("This is a directory and should not exist in index");
788 } else {
789 pos = -pos - 1;
790 }
791 if (pos >= o->src_index->cache_nr ||
792 !starts_with(o->src_index->cache[pos]->name, name.buf) ||
793 (pos > 0 && starts_with(o->src_index->cache[pos-1]->name, name.buf)))
794 BUG("pos %d doesn't point to the first entry of %s in index",
795 pos, name.buf);
796 strbuf_release(&name);
797 return pos;
798}
799
800/*
801 * Fast path if we detect that all trees are the same as cache-tree at this
802 * path. We'll walk these trees in an iterative loop using cache-tree/index
803 * instead of ODB since we already know what these trees contain.
804 */
805static int traverse_by_cache_tree(int pos, int nr_entries, int nr_names,
806 struct traverse_info *info)
807{
808 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
809 struct unpack_trees_options *o = info->data;
810 struct cache_entry *tree_ce = NULL;
811 int ce_len = 0;
812 int i, d;
813
814 if (!o->merge)
815 BUG("We need cache-tree to do this optimization");
816 if (nr_entries + pos > o->src_index->cache_nr)
817 return error(_("corrupted cache-tree has entries not present in index"));
818
819 /*
820 * Do what unpack_callback() and unpack_single_entry() normally
821 * do. But we walk all paths in an iterative loop instead.
822 *
823 * D/F conflicts and higher stage entries are not a concern
824 * because cache-tree would be invalidated and we would never
825 * get here in the first place.
826 */
827 for (i = 0; i < nr_entries; i++) {
828 int new_ce_len, len, rc;
829
830 src[0] = o->src_index->cache[pos + i];
831
832 len = ce_namelen(src[0]);
833 new_ce_len = cache_entry_size(len);
834
835 if (new_ce_len > ce_len) {
836 new_ce_len <<= 1;
837 tree_ce = xrealloc(tree_ce, new_ce_len);
838 memset(tree_ce, 0, new_ce_len);
839 ce_len = new_ce_len;
840
841 tree_ce->ce_flags = create_ce_flags(0);
842
843 for (d = 1; d <= nr_names; d++)
844 src[d] = tree_ce;
845 }
846
847 tree_ce->ce_mode = src[0]->ce_mode;
848 tree_ce->ce_namelen = len;
849 oidcpy(&tree_ce->oid, &src[0]->oid);
850 memcpy(tree_ce->name, src[0]->name, len + 1);
851
852 rc = call_unpack_fn((const struct cache_entry * const *)src, o);
853 if (rc < 0) {
854 free(tree_ce);
855 return rc;
856 }
857
858 mark_ce_used(src[0], o);
859 }
860 free(tree_ce);
861 if (o->internal.debug_unpack)
862 printf("Unpacked %d entries from %s to %s using cache-tree\n",
863 nr_entries,
864 o->src_index->cache[pos]->name,
865 o->src_index->cache[pos + nr_entries - 1]->name);
866 return 0;
867}
868
869static int traverse_trees_recursive(int n, unsigned long dirmask,
870 unsigned long df_conflicts,
871 struct name_entry *names,
872 struct traverse_info *info)
873{
874 struct unpack_trees_options *o = info->data;
875 int i, ret, bottom;
876 int nr_buf = 0;
877 struct tree_desc *t;
878 void **buf;
879 struct traverse_info newinfo;
880 struct name_entry *p;
881 int nr_entries;
882
883 nr_entries = all_trees_same_as_cache_tree(n, dirmask, names, info);
884 if (nr_entries > 0) {
885 int pos = index_pos_by_traverse_info(names, info);
886
887 if (!o->merge || df_conflicts)
888 BUG("Wrong condition to get here buddy");
889
890 /*
891 * All entries up to 'pos' must have been processed
892 * (i.e. marked CE_UNPACKED) at this point. But to be safe,
893 * save and restore cache_bottom anyway to not miss
894 * unprocessed entries before 'pos'.
895 */
896 bottom = o->internal.cache_bottom;
897 ret = traverse_by_cache_tree(pos, nr_entries, n, info);
898 o->internal.cache_bottom = bottom;
899 return ret;
900 }
901
902 p = names;
903 while (!p->mode)
904 p++;
905
906 newinfo = *info;
907 newinfo.prev = info;
908 newinfo.pathspec = info->pathspec;
909 newinfo.name = p->path;
910 newinfo.namelen = p->pathlen;
911 newinfo.mode = p->mode;
912 newinfo.pathlen = st_add3(newinfo.pathlen, tree_entry_len(p), 1);
913 newinfo.df_conflicts |= df_conflicts;
914
915 ALLOC_ARRAY(t, n);
916 ALLOC_ARRAY(buf, n);
917
918 /*
919 * Fetch the tree from the ODB for each peer directory in the
920 * n commits.
921 *
922 * For 2- and 3-way traversals, we try to avoid hitting the
923 * ODB twice for the same OID. This should yield a nice speed
924 * up in checkouts and merges when the commits are similar.
925 *
926 * We don't bother doing the full O(n^2) search for larger n,
927 * because wider traversals don't happen that often and we
928 * avoid the search setup.
929 *
930 * When 2 peer OIDs are the same, we just copy the tree
931 * descriptor data. This implicitly borrows the buffer
932 * data from the earlier cell.
933 */
934 for (i = 0; i < n; i++, dirmask >>= 1) {
935 if (i > 0 && are_same_oid(&names[i], &names[i - 1]))
936 t[i] = t[i - 1];
937 else if (i > 1 && are_same_oid(&names[i], &names[i - 2]))
938 t[i] = t[i - 2];
939 else {
940 const struct object_id *oid = NULL;
941 if (dirmask & 1)
942 oid = &names[i].oid;
943 buf[nr_buf++] = fill_tree_descriptor(the_repository, t + i, oid);
944 }
945 }
946
947 bottom = switch_cache_bottom(&newinfo);
948 ret = traverse_trees(o->src_index, n, t, &newinfo);
949 restore_cache_bottom(&newinfo, bottom);
950
951 for (i = 0; i < nr_buf; i++)
952 free(buf[i]);
953 free(buf);
954 free(t);
955
956 return ret;
957}
958
959/*
960 * Compare the traverse-path to the cache entry without actually
961 * having to generate the textual representation of the traverse
962 * path.
963 *
964 * NOTE! This *only* compares up to the size of the traverse path
965 * itself - the caller needs to do the final check for the cache
966 * entry having more data at the end!
967 */
968static int do_compare_entry_piecewise(const struct cache_entry *ce,
969 const struct traverse_info *info,
970 const char *name, size_t namelen,
971 unsigned mode)
972{
973 int pathlen, ce_len;
974 const char *ce_name;
975
976 if (info->prev) {
977 int cmp = do_compare_entry_piecewise(ce, info->prev,
978 info->name, info->namelen,
979 info->mode);
980 if (cmp)
981 return cmp;
982 }
983 pathlen = info->pathlen;
984 ce_len = ce_namelen(ce);
985
986 /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
987 if (ce_len < pathlen)
988 return -1;
989
990 ce_len -= pathlen;
991 ce_name = ce->name + pathlen;
992
993 return df_name_compare(ce_name, ce_len, S_IFREG, name, namelen, mode);
994}
995
996static int do_compare_entry(const struct cache_entry *ce,
997 const struct traverse_info *info,
998 const char *name, size_t namelen,
999 unsigned mode)
1000{
1001 int pathlen, ce_len;
1002 const char *ce_name;
1003 int cmp;
1004 unsigned ce_mode;
1005
1006 /*
1007 * If we have not precomputed the traverse path, it is quicker
1008 * to avoid doing so. But if we have precomputed it,
1009 * it is quicker to use the precomputed version.
1010 */
1011 if (!info->traverse_path)
1012 return do_compare_entry_piecewise(ce, info, name, namelen, mode);
1013
1014 cmp = strncmp(ce->name, info->traverse_path, info->pathlen);
1015 if (cmp)
1016 return cmp;
1017
1018 pathlen = info->pathlen;
1019 ce_len = ce_namelen(ce);
1020
1021 if (ce_len < pathlen)
1022 return -1;
1023
1024 ce_len -= pathlen;
1025 ce_name = ce->name + pathlen;
1026
1027 ce_mode = S_ISSPARSEDIR(ce->ce_mode) ? S_IFDIR : S_IFREG;
1028 return df_name_compare(ce_name, ce_len, ce_mode, name, namelen, mode);
1029}
1030
1031static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
1032{
1033 int cmp = do_compare_entry(ce, info, n->path, n->pathlen, n->mode);
1034 if (cmp)
1035 return cmp;
1036
1037 /*
1038 * At this point, we know that we have a prefix match. If ce
1039 * is a sparse directory, then allow an exact match. This only
1040 * works when the input name is a directory, since ce->name
1041 * ends in a directory separator.
1042 */
1043 if (S_ISSPARSEDIR(ce->ce_mode) &&
1044 ce->ce_namelen == traverse_path_len(info, tree_entry_len(n)) + 1)
1045 return 0;
1046
1047 /*
1048 * Even if the beginning compared identically, the ce should
1049 * compare as bigger than a directory leading up to it!
1050 */
1051 return ce_namelen(ce) > traverse_path_len(info, tree_entry_len(n));
1052}
1053
1054static int ce_in_traverse_path(const struct cache_entry *ce,
1055 const struct traverse_info *info)
1056{
1057 if (!info->prev)
1058 return 1;
1059 if (do_compare_entry(ce, info->prev,
1060 info->name, info->namelen, info->mode))
1061 return 0;
1062 /*
1063 * If ce (blob) is the same name as the path (which is a tree
1064 * we will be descending into), it won't be inside it.
1065 */
1066 return (info->pathlen < ce_namelen(ce));
1067}
1068
1069static struct cache_entry *create_ce_entry(const struct traverse_info *info,
1070 const struct name_entry *n,
1071 int stage,
1072 struct index_state *istate,
1073 int is_transient,
1074 int is_sparse_directory)
1075{
1076 size_t len = traverse_path_len(info, tree_entry_len(n));
1077 size_t alloc_len = is_sparse_directory ? len + 1 : len;
1078 struct cache_entry *ce =
1079 is_transient ?
1080 make_empty_transient_cache_entry(alloc_len, NULL) :
1081 make_empty_cache_entry(istate, alloc_len);
1082
1083 ce->ce_mode = create_ce_mode(n->mode);
1084 ce->ce_flags = create_ce_flags(stage);
1085 ce->ce_namelen = len;
1086 oidcpy(&ce->oid, &n->oid);
1087 /* len+1 because the cache_entry allocates space for NUL */
1088 make_traverse_path(ce->name, len + 1, info, n->path, n->pathlen);
1089
1090 if (is_sparse_directory) {
1091 ce->name[len] = '/';
1092 ce->name[len + 1] = '\0';
1093 ce->ce_namelen++;
1094 ce->ce_flags |= CE_SKIP_WORKTREE;
1095 }
1096
1097 return ce;
1098}
1099
1100/*
1101 * Determine whether the path specified by 'p' should be unpacked as a new
1102 * sparse directory in a sparse index. A new sparse directory 'A/':
1103 * - must be outside the sparse cone.
1104 * - must not already be in the index (i.e., no index entry with name 'A/'
1105 * exists).
1106 * - must not have any child entries in the index (i.e., no index entry
1107 * 'A/<something>' exists).
1108 * If 'p' meets the above requirements, return 1; otherwise, return 0.
1109 */
1110static int entry_is_new_sparse_dir(const struct traverse_info *info,
1111 const struct name_entry *p)
1112{
1113 int res, pos;
1114 struct strbuf dirpath = STRBUF_INIT;
1115 struct unpack_trees_options *o = info->data;
1116
1117 if (!S_ISDIR(p->mode))
1118 return 0;
1119
1120 /*
1121 * If the path is inside the sparse cone, it can't be a sparse directory.
1122 */
1123 strbuf_add(&dirpath, info->traverse_path, info->pathlen);
1124 strbuf_add(&dirpath, p->path, p->pathlen);
1125 strbuf_addch(&dirpath, '/');
1126 if (path_in_cone_mode_sparse_checkout(dirpath.buf, o->src_index)) {
1127 res = 0;
1128 goto cleanup;
1129 }
1130
1131 pos = index_name_pos_sparse(o->src_index, dirpath.buf, dirpath.len);
1132 if (pos >= 0) {
1133 /* Path is already in the index, not a new sparse dir */
1134 res = 0;
1135 goto cleanup;
1136 }
1137
1138 /* Where would this sparse dir be inserted into the index? */
1139 pos = -pos - 1;
1140 if (pos >= o->src_index->cache_nr) {
1141 /*
1142 * Sparse dir would be inserted at the end of the index, so we
1143 * know it has no child entries.
1144 */
1145 res = 1;
1146 goto cleanup;
1147 }
1148
1149 /*
1150 * If the dir has child entries in the index, the first would be at the
1151 * position the sparse directory would be inserted. If the entry at this
1152 * position is inside the dir, not a new sparse dir.
1153 */
1154 res = strncmp(o->src_index->cache[pos]->name, dirpath.buf, dirpath.len);
1155
1156cleanup:
1157 strbuf_release(&dirpath);
1158 return res;
1159}
1160
1161/*
1162 * Note that traverse_by_cache_tree() duplicates some logic in this function
1163 * without actually calling it. If you change the logic here you may need to
1164 * check and change there as well.
1165 */
1166static int unpack_single_entry(int n, unsigned long mask,
1167 unsigned long dirmask,
1168 struct cache_entry **src,
1169 const struct name_entry *names,
1170 const struct traverse_info *info,
1171 int *is_new_sparse_dir)
1172{
1173 int i;
1174 struct unpack_trees_options *o = info->data;
1175 unsigned long conflicts = info->df_conflicts | dirmask;
1176 const struct name_entry *p = names;
1177
1178 *is_new_sparse_dir = 0;
1179 if (mask == dirmask && !src[0]) {
1180 /*
1181 * If we're not in a sparse index, we can't unpack a directory
1182 * without recursing into it, so we return.
1183 */
1184 if (!o->src_index->sparse_index)
1185 return 0;
1186
1187 /* Find first entry with a real name (we could use "mask" too) */
1188 while (!p->mode)
1189 p++;
1190
1191 /*
1192 * If the directory is completely missing from the index but
1193 * would otherwise be a sparse directory, we should unpack it.
1194 * If not, we'll return and continue recursively traversing the
1195 * tree.
1196 */
1197 *is_new_sparse_dir = entry_is_new_sparse_dir(info, p);
1198 if (!*is_new_sparse_dir)
1199 return 0;
1200 }
1201
1202 /*
1203 * When we are unpacking a sparse directory, then this isn't necessarily
1204 * a directory-file conflict.
1205 */
1206 if (mask == dirmask &&
1207 (*is_new_sparse_dir || (src[0] && S_ISSPARSEDIR(src[0]->ce_mode))))
1208 conflicts = 0;
1209
1210 /*
1211 * Ok, we've filled in up to any potential index entry in src[0],
1212 * now do the rest.
1213 */
1214 for (i = 0; i < n; i++) {
1215 int stage;
1216 unsigned int bit = 1ul << i;
1217 if (conflicts & bit) {
1218 src[i + o->merge] = o->df_conflict_entry;
1219 continue;
1220 }
1221 if (!(mask & bit))
1222 continue;
1223 if (!o->merge)
1224 stage = 0;
1225 else if (i + 1 < o->head_idx)
1226 stage = 1;
1227 else if (i + 1 > o->head_idx)
1228 stage = 3;
1229 else
1230 stage = 2;
1231
1232 /*
1233 * If the merge bit is set, then the cache entries are
1234 * discarded in the following block. In this case,
1235 * construct "transient" cache_entries, as they are
1236 * not stored in the index. otherwise construct the
1237 * cache entry from the index aware logic.
1238 */
1239 src[i + o->merge] = create_ce_entry(info, names + i, stage,
1240 &o->internal.result,
1241 o->merge, bit & dirmask);
1242 }
1243
1244 if (o->merge) {
1245 int rc = call_unpack_fn((const struct cache_entry * const *)src,
1246 o);
1247 for (i = 0; i < n; i++) {
1248 struct cache_entry *ce = src[i + o->merge];
1249 if (ce != o->df_conflict_entry)
1250 discard_cache_entry(ce);
1251 }
1252 return rc;
1253 }
1254
1255 for (i = 0; i < n; i++)
1256 if (src[i] && src[i] != o->df_conflict_entry)
1257 if (do_add_entry(o, src[i], 0, 0))
1258 return -1;
1259
1260 return 0;
1261}
1262
1263static int unpack_failed(struct unpack_trees_options *o, const char *message)
1264{
1265 discard_index(&o->internal.result);
1266 if (!o->quiet && !o->exiting_early) {
1267 if (message)
1268 return error("%s", message);
1269 return -1;
1270 }
1271 return -1;
1272}
1273
1274/*
1275 * The tree traversal is looking at name p. If we have a matching entry,
1276 * return it. If name p is a directory in the index, do not return
1277 * anything, as we will want to match it when the traversal descends into
1278 * the directory.
1279 */
1280static int find_cache_pos(struct traverse_info *info,
1281 const char *p, size_t p_len)
1282{
1283 int pos;
1284 struct unpack_trees_options *o = info->data;
1285 struct index_state *index = o->src_index;
1286 int pfxlen = info->pathlen;
1287
1288 for (pos = o->internal.cache_bottom; pos < index->cache_nr; pos++) {
1289 const struct cache_entry *ce = index->cache[pos];
1290 const char *ce_name, *ce_slash;
1291 int cmp, ce_len;
1292
1293 if (ce->ce_flags & CE_UNPACKED) {
1294 /*
1295 * cache_bottom entry is already unpacked, so
1296 * we can never match it; don't check it
1297 * again.
1298 */
1299 if (pos == o->internal.cache_bottom)
1300 ++o->internal.cache_bottom;
1301 continue;
1302 }
1303 if (!ce_in_traverse_path(ce, info)) {
1304 /*
1305 * Check if we can skip future cache checks
1306 * (because we're already past all possible
1307 * entries in the traverse path).
1308 */
1309 if (info->traverse_path) {
1310 if (strncmp(ce->name, info->traverse_path,
1311 info->pathlen) > 0)
1312 break;
1313 }
1314 continue;
1315 }
1316 ce_name = ce->name + pfxlen;
1317 ce_slash = strchr(ce_name, '/');
1318 if (ce_slash)
1319 ce_len = ce_slash - ce_name;
1320 else
1321 ce_len = ce_namelen(ce) - pfxlen;
1322 cmp = name_compare(p, p_len, ce_name, ce_len);
1323 /*
1324 * Exact match; if we have a directory we need to
1325 * delay returning it.
1326 */
1327 if (!cmp)
1328 return ce_slash ? -2 - pos : pos;
1329 if (0 < cmp)
1330 continue; /* keep looking */
1331 /*
1332 * ce_name sorts after p->path; could it be that we
1333 * have files under p->path directory in the index?
1334 * E.g. ce_name == "t-i", and p->path == "t"; we may
1335 * have "t/a" in the index.
1336 */
1337 if (p_len < ce_len && !memcmp(ce_name, p, p_len) &&
1338 ce_name[p_len] < '/')
1339 continue; /* keep looking */
1340 break;
1341 }
1342 return -1;
1343}
1344
1345/*
1346 * Given a sparse directory entry 'ce', compare ce->name to
1347 * info->traverse_path + p->path + '/' if info->traverse_path
1348 * is non-empty.
1349 *
1350 * Compare ce->name to p->path + '/' otherwise. Note that
1351 * ce->name must end in a trailing '/' because it is a sparse
1352 * directory entry.
1353 */
1354static int sparse_dir_matches_path(const struct cache_entry *ce,
1355 struct traverse_info *info,
1356 const struct name_entry *p)
1357{
1358 assert(S_ISSPARSEDIR(ce->ce_mode));
1359 assert(ce->name[ce->ce_namelen - 1] == '/');
1360
1361 if (info->pathlen)
1362 return ce->ce_namelen == info->pathlen + p->pathlen + 1 &&
1363 ce->name[info->pathlen - 1] == '/' &&
1364 !strncmp(ce->name, info->traverse_path, info->pathlen) &&
1365 !strncmp(ce->name + info->pathlen, p->path, p->pathlen);
1366 return ce->ce_namelen == p->pathlen + 1 &&
1367 !strncmp(ce->name, p->path, p->pathlen);
1368}
1369
1370static struct cache_entry *find_cache_entry(struct traverse_info *info,
1371 const struct name_entry *p)
1372{
1373 const char *path;
1374 int pos = find_cache_pos(info, p->path, p->pathlen);
1375 struct unpack_trees_options *o = info->data;
1376
1377 if (0 <= pos)
1378 return o->src_index->cache[pos];
1379
1380 /*
1381 * Check for a sparse-directory entry named "path/".
1382 * Due to the input p->path not having a trailing
1383 * slash, the negative 'pos' value overshoots the
1384 * expected position, hence "-2" instead of "-1".
1385 */
1386 pos = -pos - 2;
1387
1388 if (pos < 0 || pos >= o->src_index->cache_nr)
1389 return NULL;
1390
1391 /*
1392 * Due to lexicographic sorting and sparse directory
1393 * entries ending with a trailing slash, our path as a
1394 * sparse directory (e.g "subdir/") and our path as a
1395 * file (e.g. "subdir") might be separated by other
1396 * paths (e.g. "subdir-").
1397 */
1398 while (pos >= 0) {
1399 struct cache_entry *ce = o->src_index->cache[pos];
1400
1401 if (!skip_prefix(ce->name, info->traverse_path, &path) ||
1402 strncmp(path, p->path, p->pathlen) ||
1403 path[p->pathlen] != '/')
1404 return NULL;
1405
1406 if (S_ISSPARSEDIR(ce->ce_mode) &&
1407 sparse_dir_matches_path(ce, info, p))
1408 return ce;
1409
1410 pos--;
1411 }
1412
1413 return NULL;
1414}
1415
1416static void debug_path(struct traverse_info *info)
1417{
1418 if (info->prev) {
1419 debug_path(info->prev);
1420 if (*info->prev->name)
1421 putchar('/');
1422 }
1423 printf("%s", info->name);
1424}
1425
1426static void debug_name_entry(int i, struct name_entry *n)
1427{
1428 printf("ent#%d %06o %s\n", i,
1429 n->path ? n->mode : 0,
1430 n->path ? n->path : "(missing)");
1431}
1432
1433static void debug_unpack_callback(int n,
1434 unsigned long mask,
1435 unsigned long dirmask,
1436 struct name_entry *names,
1437 struct traverse_info *info)
1438{
1439 int i;
1440 printf("* unpack mask %lu, dirmask %lu, cnt %d ",
1441 mask, dirmask, n);
1442 debug_path(info);
1443 putchar('\n');
1444 for (i = 0; i < n; i++)
1445 debug_name_entry(i, names + i);
1446}
1447
1448/*
1449 * Returns true if and only if the given cache_entry is a
1450 * sparse-directory entry that matches the given name_entry
1451 * from the tree walk at the given traverse_info.
1452 */
1453static int is_sparse_directory_entry(struct cache_entry *ce,
1454 const struct name_entry *name,
1455 struct traverse_info *info)
1456{
1457 if (!ce || !name || !S_ISSPARSEDIR(ce->ce_mode))
1458 return 0;
1459
1460 return sparse_dir_matches_path(ce, info, name);
1461}
1462
1463static int unpack_sparse_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1464{
1465 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1466 struct unpack_trees_options *o = info->data;
1467 int ret, is_new_sparse_dir;
1468
1469 assert(o->merge);
1470
1471 /*
1472 * Unlike in 'unpack_callback', where src[0] is derived from the index when
1473 * merging, src[0] is a transient cache entry derived from the first tree
1474 * provided. Create the temporary entry as if it came from a non-sparse index.
1475 */
1476 if (!is_null_oid(&names[0].oid)) {
1477 src[0] = create_ce_entry(info, &names[0], 0,
1478 &o->internal.result, 1,
1479 dirmask & (1ul << 0));
1480 src[0]->ce_flags |= (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
1481 }
1482
1483 /*
1484 * 'unpack_single_entry' assumes that src[0] is derived directly from
1485 * the index, rather than from an entry in 'names'. This is *not* true when
1486 * merging a sparse directory, in which case names[0] is the "index" source
1487 * entry. To match the expectations of 'unpack_single_entry', shift past the
1488 * "index" tree (i.e., names[0]) and adjust 'names', 'n', 'mask', and
1489 * 'dirmask' accordingly.
1490 */
1491 ret = unpack_single_entry(n - 1, mask >> 1, dirmask >> 1, src, names + 1, info, &is_new_sparse_dir);
1492
1493 if (src[0])
1494 discard_cache_entry(src[0]);
1495
1496 return ret >= 0 ? mask : -1;
1497}
1498
1499/*
1500 * Note that traverse_by_cache_tree() duplicates some logic in this function
1501 * without actually calling it. If you change the logic here you may need to
1502 * check and change there as well.
1503 */
1504static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
1505{
1506 struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
1507 struct unpack_trees_options *o = info->data;
1508 const struct name_entry *p = names;
1509 int is_new_sparse_dir;
1510
1511 /* Find first entry with a real name (we could use "mask" too) */
1512 while (!p->mode)
1513 p++;
1514
1515 if (o->internal.debug_unpack)
1516 debug_unpack_callback(n, mask, dirmask, names, info);
1517
1518 /* Are we supposed to look at the index too? */
1519 if (o->merge) {
1520 while (1) {
1521 int cmp;
1522 struct cache_entry *ce;
1523
1524 if (o->diff_index_cached)
1525 ce = next_cache_entry(o);
1526 else
1527 ce = find_cache_entry(info, p);
1528
1529 if (!ce)
1530 break;
1531 cmp = compare_entry(ce, info, p);
1532 if (cmp < 0) {
1533 if (unpack_index_entry(ce, o) < 0)
1534 return unpack_failed(o, NULL);
1535 continue;
1536 }
1537 if (!cmp) {
1538 if (ce_stage(ce)) {
1539 /*
1540 * If we skip unmerged index
1541 * entries, we'll skip this
1542 * entry *and* the tree
1543 * entries associated with it!
1544 */
1545 if (o->skip_unmerged) {
1546 add_same_unmerged(ce, o);
1547 return mask;
1548 }
1549 }
1550 src[0] = ce;
1551 }
1552 break;
1553 }
1554 }
1555
1556 if (unpack_single_entry(n, mask, dirmask, src, names, info, &is_new_sparse_dir))
1557 return -1;
1558
1559 if (o->merge && src[0]) {
1560 if (ce_stage(src[0]))
1561 mark_ce_used_same_name(src[0], o);
1562 else
1563 mark_ce_used(src[0], o);
1564 }
1565
1566 /* Now handle any directories.. */
1567 if (dirmask) {
1568 /* special case: "diff-index --cached" looking at a tree */
1569 if (o->diff_index_cached &&
1570 n == 1 && dirmask == 1 && S_ISDIR(names->mode)) {
1571 int matches;
1572 matches = cache_tree_matches_traversal(o->src_index->cache_tree,
1573 names, info);
1574 /*
1575 * Everything under the name matches; skip the
1576 * entire hierarchy. diff_index_cached codepath
1577 * special cases D/F conflicts in such a way that
1578 * it does not do any look-ahead, so this is safe.
1579 */
1580 if (matches) {
1581 /*
1582 * Only increment the cache_bottom if the
1583 * directory isn't a sparse directory index
1584 * entry (if it is, it was already incremented)
1585 * in 'mark_ce_used()'
1586 */
1587 if (!src[0] || !S_ISSPARSEDIR(src[0]->ce_mode))
1588 o->internal.cache_bottom += matches;
1589 return mask;
1590 }
1591 }
1592
1593 if (!is_sparse_directory_entry(src[0], p, info) &&
1594 !is_new_sparse_dir &&
1595 traverse_trees_recursive(n, dirmask, mask & ~dirmask,
1596 names, info) < 0) {
1597 return -1;
1598 }
1599
1600 return mask;
1601 }
1602
1603 return mask;
1604}
1605
1606static int clear_ce_flags_1(struct index_state *istate,
1607 struct cache_entry **cache, int nr,
1608 struct strbuf *prefix,
1609 int select_mask, int clear_mask,
1610 struct pattern_list *pl,
1611 enum pattern_match_result default_match,
1612 int progress_nr);
1613
1614/* Whole directory matching */
1615static int clear_ce_flags_dir(struct index_state *istate,
1616 struct cache_entry **cache, int nr,
1617 struct strbuf *prefix,
1618 char *basename,
1619 int select_mask, int clear_mask,
1620 struct pattern_list *pl,
1621 enum pattern_match_result default_match,
1622 int progress_nr)
1623{
1624 struct cache_entry **cache_end;
1625 int dtype = DT_DIR;
1626 int rc;
1627 enum pattern_match_result ret, orig_ret;
1628 orig_ret = path_matches_pattern_list(prefix->buf, prefix->len,
1629 basename, &dtype, pl, istate);
1630
1631 strbuf_addch(prefix, '/');
1632
1633 /* If undecided, use matching result of parent dir in defval */
1634 if (orig_ret == UNDECIDED)
1635 ret = default_match;
1636 else
1637 ret = orig_ret;
1638
1639 for (cache_end = cache; cache_end != cache + nr; cache_end++) {
1640 struct cache_entry *ce = *cache_end;
1641 if (strncmp(ce->name, prefix->buf, prefix->len))
1642 break;
1643 }
1644
1645 if (pl->use_cone_patterns && orig_ret == MATCHED_RECURSIVE) {
1646 struct cache_entry **ce = cache;
1647 rc = cache_end - cache;
1648
1649 while (ce < cache_end) {
1650 (*ce)->ce_flags &= ~clear_mask;
1651 ce++;
1652 }
1653 } else if (pl->use_cone_patterns && orig_ret == NOT_MATCHED) {
1654 rc = cache_end - cache;
1655 } else {
1656 rc = clear_ce_flags_1(istate, cache, cache_end - cache,
1657 prefix,
1658 select_mask, clear_mask,
1659 pl, ret,
1660 progress_nr);
1661 }
1662
1663 strbuf_setlen(prefix, prefix->len - 1);
1664 return rc;
1665}
1666
1667/*
1668 * Traverse the index, find every entry that matches according to
1669 * o->pl. Do "ce_flags &= ~clear_mask" on those entries. Return the
1670 * number of traversed entries.
1671 *
1672 * If select_mask is non-zero, only entries whose ce_flags has on of
1673 * those bits enabled are traversed.
1674 *
1675 * cache : pointer to an index entry
1676 * prefix_len : an offset to its path
1677 *
1678 * The current path ("prefix") including the trailing '/' is
1679 * cache[0]->name[0..(prefix_len-1)]
1680 * Top level path has prefix_len zero.
1681 */
1682static int clear_ce_flags_1(struct index_state *istate,
1683 struct cache_entry **cache, int nr,
1684 struct strbuf *prefix,
1685 int select_mask, int clear_mask,
1686 struct pattern_list *pl,
1687 enum pattern_match_result default_match,
1688 int progress_nr)
1689{
1690 struct cache_entry **cache_end = nr ? cache + nr : cache;
1691
1692 /*
1693 * Process all entries that have the given prefix and meet
1694 * select_mask condition
1695 */
1696 while(cache != cache_end) {
1697 struct cache_entry *ce = *cache;
1698 const char *name, *slash;
1699 int len, dtype;
1700 enum pattern_match_result ret;
1701
1702 display_progress(istate->progress, progress_nr);
1703
1704 if (select_mask && !(ce->ce_flags & select_mask)) {
1705 cache++;
1706 progress_nr++;
1707 continue;
1708 }
1709
1710 if (prefix->len && strncmp(ce->name, prefix->buf, prefix->len))
1711 break;
1712
1713 name = ce->name + prefix->len;
1714 slash = strchr(name, '/');
1715
1716 /* If it's a directory, try whole directory match first */
1717 if (slash) {
1718 int processed;
1719
1720 len = slash - name;
1721 strbuf_add(prefix, name, len);
1722
1723 processed = clear_ce_flags_dir(istate, cache, cache_end - cache,
1724 prefix,
1725 prefix->buf + prefix->len - len,
1726 select_mask, clear_mask,
1727 pl, default_match,
1728 progress_nr);
1729
1730 /* clear_c_f_dir eats a whole dir already? */
1731 if (processed) {
1732 cache += processed;
1733 progress_nr += processed;
1734 strbuf_setlen(prefix, prefix->len - len);
1735 continue;
1736 }
1737
1738 strbuf_addch(prefix, '/');
1739 processed = clear_ce_flags_1(istate, cache, cache_end - cache,
1740 prefix,
1741 select_mask, clear_mask, pl,
1742 default_match, progress_nr);
1743
1744 cache += processed;
1745 progress_nr += processed;
1746
1747 strbuf_setlen(prefix, prefix->len - len - 1);
1748 continue;
1749 }
1750
1751 /* Non-directory */
1752 dtype = ce_to_dtype(ce);
1753 ret = path_matches_pattern_list(ce->name,
1754 ce_namelen(ce),
1755 name, &dtype, pl, istate);
1756 if (ret == UNDECIDED)
1757 ret = default_match;
1758 if (ret == MATCHED || ret == MATCHED_RECURSIVE)
1759 ce->ce_flags &= ~clear_mask;
1760 cache++;
1761 progress_nr++;
1762 }
1763
1764 display_progress(istate->progress, progress_nr);
1765 return nr - (cache_end - cache);
1766}
1767
1768static int clear_ce_flags(struct index_state *istate,
1769 int select_mask, int clear_mask,
1770 struct pattern_list *pl,
1771 int show_progress)
1772{
1773 static struct strbuf prefix = STRBUF_INIT;
1774 char label[100];
1775 int rval;
1776
1777 strbuf_reset(&prefix);
1778 if (show_progress)
1779 istate->progress = start_delayed_progress(
1780 the_repository,
1781 _("Updating index flags"),
1782 istate->cache_nr);
1783
1784 xsnprintf(label, sizeof(label), "clear_ce_flags(0x%08lx,0x%08lx)",
1785 (unsigned long)select_mask, (unsigned long)clear_mask);
1786 trace2_region_enter("unpack_trees", label, istate->repo);
1787 rval = clear_ce_flags_1(istate,
1788 istate->cache,
1789 istate->cache_nr,
1790 &prefix,
1791 select_mask, clear_mask,
1792 pl, 0, 0);
1793 trace2_region_leave("unpack_trees", label, istate->repo);
1794
1795 stop_progress(&istate->progress);
1796 return rval;
1797}
1798
1799/*
1800 * Set/Clear CE_NEW_SKIP_WORKTREE according to $GIT_DIR/info/sparse-checkout
1801 */
1802static void mark_new_skip_worktree(struct pattern_list *pl,
1803 struct index_state *istate,
1804 int select_flag, int skip_wt_flag,
1805 int show_progress)
1806{
1807 int i;
1808
1809 /*
1810 * 1. Pretend the narrowest worktree: only unmerged entries
1811 * are checked out
1812 */
1813 for (i = 0; i < istate->cache_nr; i++) {
1814 struct cache_entry *ce = istate->cache[i];
1815
1816 if (select_flag && !(ce->ce_flags & select_flag))
1817 continue;
1818
1819 if (!ce_stage(ce) && !(ce->ce_flags & CE_CONFLICTED))
1820 ce->ce_flags |= skip_wt_flag;
1821 else
1822 ce->ce_flags &= ~skip_wt_flag;
1823 }
1824
1825 /*
1826 * 2. Widen worktree according to sparse-checkout file.
1827 * Matched entries will have skip_wt_flag cleared (i.e. "in")
1828 */
1829 clear_ce_flags(istate, select_flag, skip_wt_flag, pl, show_progress);
1830}
1831
1832static void populate_from_existing_patterns(struct unpack_trees_options *o,
1833 struct pattern_list *pl)
1834{
1835 if (get_sparse_checkout_patterns(pl) < 0)
1836 o->skip_sparse_checkout = 1;
1837 else
1838 o->internal.pl = pl;
1839}
1840
1841static void update_sparsity_for_prefix(const char *prefix,
1842 struct index_state *istate)
1843{
1844 int prefix_len = strlen(prefix);
1845 struct strbuf ce_prefix = STRBUF_INIT;
1846
1847 if (!istate->sparse_index)
1848 return;
1849
1850 while (prefix_len > 0 && prefix[prefix_len - 1] == '/')
1851 prefix_len--;
1852
1853 if (prefix_len <= 0)
1854 BUG("Invalid prefix passed to update_sparsity_for_prefix");
1855
1856 strbuf_grow(&ce_prefix, prefix_len + 1);
1857 strbuf_add(&ce_prefix, prefix, prefix_len);
1858 strbuf_addch(&ce_prefix, '/');
1859
1860 /*
1861 * If the prefix points to a sparse directory or a path inside a sparse
1862 * directory, the index should be expanded. This is accomplished in one
1863 * of two ways:
1864 * - if the prefix is inside a sparse directory, it will be expanded by
1865 * the 'ensure_full_index(...)' call in 'index_name_pos(...)'.
1866 * - if the prefix matches an existing sparse directory entry,
1867 * 'index_name_pos(...)' will return its index position, triggering
1868 * the 'ensure_full_index(...)' below.
1869 */
1870 if (!path_in_cone_mode_sparse_checkout(ce_prefix.buf, istate) &&
1871 index_name_pos(istate, ce_prefix.buf, ce_prefix.len) >= 0)
1872 ensure_full_index(istate);
1873
1874 strbuf_release(&ce_prefix);
1875}
1876
1877static int verify_absent(const struct cache_entry *,
1878 enum unpack_trees_error_types,
1879 struct unpack_trees_options *);
1880/*
1881 * N-way merge "len" trees. Returns 0 on success, -1 on failure to manipulate the
1882 * resulting index, -2 on failure to reflect the changes to the work tree.
1883 *
1884 * CE_ADDED, CE_UNPACKED and CE_NEW_SKIP_WORKTREE are used internally
1885 */
1886int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
1887{
1888 struct repository *repo = o->src_index->repo;
1889 int i, ret;
1890 static struct cache_entry *dfc;
1891 struct pattern_list pl;
1892 int free_pattern_list = 0;
1893 struct dir_struct dir = DIR_INIT;
1894 struct repo_config_values *cfg = repo_config_values(the_repository);
1895
1896 if (o->reset == UNPACK_RESET_INVALID)
1897 BUG("o->reset had a value of 1; should be UNPACK_TREES_*_UNTRACKED");
1898
1899 if (len > MAX_UNPACK_TREES)
1900 die("unpack_trees takes at most %d trees", MAX_UNPACK_TREES);
1901 if (o->internal.dir)
1902 BUG("o->internal.dir is for internal use only");
1903 if (o->internal.pl)
1904 BUG("o->internal.pl is for internal use only");
1905 if (o->df_conflict_entry)
1906 BUG("o->df_conflict_entry is an output only field");
1907
1908 trace_performance_enter();
1909 trace2_region_enter("unpack_trees", "unpack_trees", repo);
1910
1911 prepare_repo_settings(repo);
1912 if (repo->settings.command_requires_full_index) {
1913 ensure_full_index(o->src_index);
1914 if (o->dst_index)
1915 ensure_full_index(o->dst_index);
1916 }
1917
1918 if (o->reset == UNPACK_RESET_OVERWRITE_UNTRACKED &&
1919 o->preserve_ignored)
1920 BUG("UNPACK_RESET_OVERWRITE_UNTRACKED incompatible with preserved ignored files");
1921
1922 if (!o->preserve_ignored) {
1923 o->internal.dir = &dir;
1924 o->internal.dir->flags |= DIR_SHOW_IGNORED;
1925 setup_standard_excludes(o->internal.dir);
1926 }
1927
1928 if (o->prefix)
1929 update_sparsity_for_prefix(o->prefix, o->src_index);
1930
1931 if (!cfg->apply_sparse_checkout || !o->update)
1932 o->skip_sparse_checkout = 1;
1933 if (!o->skip_sparse_checkout) {
1934 memset(&pl, 0, sizeof(pl));
1935 free_pattern_list = 1;
1936 populate_from_existing_patterns(o, &pl);
1937 }
1938
1939 index_state_init(&o->internal.result, o->src_index->repo);
1940 o->internal.result.initialized = 1;
1941 o->internal.result.timestamp.sec = o->src_index->timestamp.sec;
1942 o->internal.result.timestamp.nsec = o->src_index->timestamp.nsec;
1943 o->internal.result.version = o->src_index->version;
1944 if (!o->src_index->split_index) {
1945 o->internal.result.split_index = NULL;
1946 } else if (o->src_index == o->dst_index) {
1947 /*
1948 * o->dst_index (and thus o->src_index) will be discarded
1949 * and overwritten with o->internal.result at the end of
1950 * this function, so just use src_index's split_index to
1951 * avoid having to create a new one.
1952 */
1953 o->internal.result.split_index = o->src_index->split_index;
1954 if (o->src_index->cache_changed & SPLIT_INDEX_ORDERED)
1955 o->internal.result.cache_changed |= SPLIT_INDEX_ORDERED;
1956 o->internal.result.split_index->refcount++;
1957 } else {
1958 o->internal.result.split_index =
1959 init_split_index(&o->internal.result);
1960 }
1961 oidcpy(&o->internal.result.oid, &o->src_index->oid);
1962 o->internal.result.file_stat = o->src_index->file_stat;
1963 o->internal.merge_size = len;
1964 mark_all_ce_unused(o->src_index);
1965
1966 o->internal.result.fsmonitor_last_update =
1967 xstrdup_or_null(o->src_index->fsmonitor_last_update);
1968 o->internal.result.fsmonitor_has_run_once = o->src_index->fsmonitor_has_run_once;
1969
1970 if (!o->src_index->initialized &&
1971 !repo->settings.command_requires_full_index &&
1972 is_sparse_index_allowed(&o->internal.result, 0))
1973 o->internal.result.sparse_index = 1;
1974
1975 /*
1976 * Sparse checkout loop #1: set NEW_SKIP_WORKTREE on existing entries
1977 */
1978 if (!o->skip_sparse_checkout)
1979 mark_new_skip_worktree(o->internal.pl, o->src_index, 0,
1980 CE_NEW_SKIP_WORKTREE, o->verbose_update);
1981
1982 if (!dfc)
1983 dfc = xcalloc(1, cache_entry_size(0));
1984 o->df_conflict_entry = dfc;
1985
1986 if (len) {
1987 const char *prefix = o->prefix ? o->prefix : "";
1988 struct traverse_info info;
1989
1990 setup_traverse_info(&info, prefix);
1991 info.fn = unpack_callback;
1992 info.data = o;
1993 info.show_all_errors = o->internal.show_all_errors;
1994 info.pathspec = o->pathspec;
1995
1996 if (o->prefix) {
1997 /*
1998 * Unpack existing index entries that sort before the
1999 * prefix the tree is spliced into. Note that o->merge
2000 * is always true in this case.
2001 */
2002 while (1) {
2003 struct cache_entry *ce = next_cache_entry(o);
2004 if (!ce)
2005 break;
2006 if (ce_in_traverse_path(ce, &info))
2007 break;
2008 if (unpack_index_entry(ce, o) < 0)
2009 goto return_failed;
2010 }
2011 }
2012
2013 trace_performance_enter();
2014 trace2_region_enter("unpack_trees", "traverse_trees", repo);
2015 ret = traverse_trees(o->src_index, len, t, &info);
2016 trace2_region_leave("unpack_trees", "traverse_trees", repo);
2017 trace_performance_leave("traverse_trees");
2018 if (ret < 0)
2019 goto return_failed;
2020 }
2021
2022 /* Any left-over entries in the index? */
2023 if (o->merge) {
2024 while (1) {
2025 struct cache_entry *ce = next_cache_entry(o);
2026 if (!ce)
2027 break;
2028 if (unpack_index_entry(ce, o) < 0)
2029 goto return_failed;
2030 }
2031 }
2032 mark_all_ce_unused(o->src_index);
2033
2034 if (o->trivial_merges_only && o->internal.nontrivial_merge) {
2035 ret = unpack_failed(o, "Merge requires file-level merging");
2036 goto done;
2037 }
2038
2039 if (!o->skip_sparse_checkout) {
2040 /*
2041 * Sparse checkout loop #2: set NEW_SKIP_WORKTREE on entries not in loop #1
2042 * If they will have NEW_SKIP_WORKTREE, also set CE_SKIP_WORKTREE
2043 * so apply_sparse_checkout() won't attempt to remove it from worktree
2044 */
2045 mark_new_skip_worktree(o->internal.pl, &o->internal.result,
2046 CE_ADDED, CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE,
2047 o->verbose_update);
2048
2049 ret = 0;
2050 for (i = 0; i < o->internal.result.cache_nr; i++) {
2051 struct cache_entry *ce = o->internal.result.cache[i];
2052
2053 /*
2054 * Entries marked with CE_ADDED in merged_entry() do not have
2055 * verify_absent() check (the check is effectively disabled
2056 * because CE_NEW_SKIP_WORKTREE is set unconditionally).
2057 *
2058 * Do the real check now because we have had
2059 * correct CE_NEW_SKIP_WORKTREE
2060 */
2061 if (ce->ce_flags & CE_ADDED &&
2062 verify_absent(ce, WARNING_SPARSE_ORPHANED_NOT_OVERWRITTEN, o))
2063 ret = 1;
2064
2065 if (apply_sparse_checkout(&o->internal.result, ce, o))
2066 ret = 1;
2067 }
2068 if (ret == 1) {
2069 /*
2070 * Inability to sparsify or de-sparsify individual
2071 * paths is not an error, but just a warning.
2072 */
2073 if (o->internal.show_all_errors)
2074 display_warning_msgs(o);
2075 ret = 0;
2076 }
2077 }
2078
2079 ret = check_updates(o, &o->internal.result) ? (-2) : 0;
2080 if (o->dst_index) {
2081 move_index_extensions(&o->internal.result, o->src_index);
2082 if (!ret) {
2083 if (git_env_bool("GIT_TEST_CHECK_CACHE_TREE", 0) &&
2084 cache_tree_verify(the_repository,
2085 &o->internal.result) < 0) {
2086 ret = -1;
2087 goto done;
2088 }
2089
2090 if (!o->skip_cache_tree_update &&
2091 !cache_tree_fully_valid(&o->internal.result))
2092 cache_tree_update(&o->internal.result,
2093 WRITE_TREE_SILENT |
2094 WRITE_TREE_REPAIR);
2095 }
2096
2097 o->internal.result.updated_workdir = 1;
2098 discard_index(o->dst_index);
2099 *o->dst_index = o->internal.result;
2100 memset(&o->internal.result, 0, sizeof(o->internal.result));
2101 } else {
2102 discard_index(&o->internal.result);
2103 }
2104 o->src_index = NULL;
2105
2106done:
2107 if (free_pattern_list)
2108 clear_pattern_list(&pl);
2109 if (o->internal.dir) {
2110 dir_clear(o->internal.dir);
2111 o->internal.dir = NULL;
2112 }
2113 trace2_region_leave("unpack_trees", "unpack_trees", repo);
2114 trace_performance_leave("unpack_trees");
2115 return ret;
2116
2117return_failed:
2118 if (o->internal.show_all_errors)
2119 display_error_msgs(o);
2120 mark_all_ce_unused(o->src_index);
2121 ret = unpack_failed(o, NULL);
2122 if (o->exiting_early)
2123 ret = 0;
2124 goto done;
2125}
2126
2127/*
2128 * Update SKIP_WORKTREE bits according to sparsity patterns, and update
2129 * working directory to match.
2130 *
2131 * CE_NEW_SKIP_WORKTREE is used internally.
2132 */
2133enum update_sparsity_result update_sparsity(struct unpack_trees_options *o,
2134 struct pattern_list *pl)
2135{
2136 enum update_sparsity_result ret = UPDATE_SPARSITY_SUCCESS;
2137 int i;
2138 unsigned old_show_all_errors;
2139 int free_pattern_list = 0;
2140
2141 old_show_all_errors = o->internal.show_all_errors;
2142 o->internal.show_all_errors = 1;
2143 index_state_init(&o->internal.result, o->src_index->repo);
2144
2145 /* Sanity checks */
2146 if (!o->update || o->index_only || o->skip_sparse_checkout)
2147 BUG("update_sparsity() is for reflecting sparsity patterns in working directory");
2148 if (o->src_index != o->dst_index || o->fn)
2149 BUG("update_sparsity() called wrong");
2150
2151 trace_performance_enter();
2152
2153 /* If we weren't given patterns, use the recorded ones */
2154 if (!pl) {
2155 free_pattern_list = 1;
2156 pl = xcalloc(1, sizeof(*pl));
2157 populate_from_existing_patterns(o, pl);
2158 }
2159 o->internal.pl = pl;
2160
2161 /* Expand sparse directories as needed */
2162 expand_index(o->src_index, o->internal.pl);
2163
2164 /* Set NEW_SKIP_WORKTREE on existing entries. */
2165 mark_all_ce_unused(o->src_index);
2166 mark_new_skip_worktree(o->internal.pl, o->src_index, 0,
2167 CE_NEW_SKIP_WORKTREE, o->verbose_update);
2168
2169 /* Then loop over entries and update/remove as needed */
2170 ret = UPDATE_SPARSITY_SUCCESS;
2171 for (i = 0; i < o->src_index->cache_nr; i++) {
2172 struct cache_entry *ce = o->src_index->cache[i];
2173
2174
2175 if (ce_stage(ce)) {
2176 /* -1 because for loop will increment by 1 */
2177 i += warn_conflicted_path(o->src_index, i, o) - 1;
2178 ret = UPDATE_SPARSITY_WARNINGS;
2179 continue;
2180 }
2181
2182 if (apply_sparse_checkout(o->src_index, ce, o))
2183 ret = UPDATE_SPARSITY_WARNINGS;
2184 }
2185
2186 if (check_updates(o, o->src_index))
2187 ret = UPDATE_SPARSITY_WORKTREE_UPDATE_FAILURES;
2188
2189 display_warning_msgs(o);
2190 o->internal.show_all_errors = old_show_all_errors;
2191 if (free_pattern_list) {
2192 clear_pattern_list(pl);
2193 free(pl);
2194 o->internal.pl = NULL;
2195 }
2196 trace_performance_leave("update_sparsity");
2197 return ret;
2198}
2199
2200/* Here come the merge functions */
2201
2202static int reject_merge(const struct cache_entry *ce,
2203 struct unpack_trees_options *o)
2204{
2205 return add_rejected_path(o, ERROR_WOULD_OVERWRITE, ce->name);
2206}
2207
2208static int same(const struct cache_entry *a, const struct cache_entry *b)
2209{
2210 if (!!a != !!b)
2211 return 0;
2212 if (!a && !b)
2213 return 1;
2214 if ((a->ce_flags | b->ce_flags) & CE_CONFLICTED)
2215 return 0;
2216 return a->ce_mode == b->ce_mode &&
2217 oideq(&a->oid, &b->oid);
2218}
2219
2220
2221/*
2222 * When a CE gets turned into an unmerged entry, we
2223 * want it to be up-to-date
2224 */
2225static int verify_uptodate_1(const struct cache_entry *ce,
2226 struct unpack_trees_options *o,
2227 enum unpack_trees_error_types error_type)
2228{
2229 struct stat st;
2230
2231 if (o->index_only)
2232 return 0;
2233
2234 /*
2235 * CE_VALID and CE_SKIP_WORKTREE cheat, we better check again
2236 * if this entry is truly up-to-date because this file may be
2237 * overwritten.
2238 */
2239 if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2240 ; /* keep checking */
2241 else if (o->reset || ce_uptodate(ce))
2242 return 0;
2243
2244 if (!lstat(ce->name, &st)) {
2245 int flags = CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE;
2246 unsigned changed = ie_match_stat(o->src_index, ce, &st, flags);
2247
2248 if (submodule_from_ce(ce)) {
2249 int r = check_submodule_move_head(ce,
2250 "HEAD", oid_to_hex(&ce->oid), o);
2251 if (r)
2252 return add_rejected_path(o, error_type, ce->name);
2253 return 0;
2254 }
2255
2256 if (!changed)
2257 return 0;
2258 /*
2259 * Historic default policy was to allow submodule to be out
2260 * of sync wrt the superproject index. If the submodule was
2261 * not considered interesting above, we don't care here.
2262 */
2263 if (S_ISGITLINK(ce->ce_mode))
2264 return 0;
2265
2266 errno = 0;
2267 }
2268 if (errno == ENOENT)
2269 return 0;
2270 return add_rejected_path(o, error_type, ce->name);
2271}
2272
2273static int verify_uptodate(const struct cache_entry *ce,
2274 struct unpack_trees_options *o)
2275{
2276 if (!o->skip_sparse_checkout &&
2277 (ce->ce_flags & CE_SKIP_WORKTREE) &&
2278 (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2279 return 0;
2280 return verify_uptodate_1(ce, o, ERROR_NOT_UPTODATE_FILE);
2281}
2282
2283static int verify_uptodate_sparse(const struct cache_entry *ce,
2284 struct unpack_trees_options *o)
2285{
2286 return verify_uptodate_1(ce, o, WARNING_SPARSE_NOT_UPTODATE_FILE);
2287}
2288
2289/*
2290 * TODO: We should actually invalidate o->internal.result, not src_index [1].
2291 * But since cache tree and untracked cache both are not copied to
2292 * o->internal.result until unpacking is complete, we invalidate them on
2293 * src_index instead with the assumption that they will be copied to
2294 * dst_index at the end.
2295 *
2296 * [1] src_index->cache_tree is also used in unpack_callback() so if
2297 * we invalidate o->internal.result, we need to update it to use
2298 * o->internal.result.cache_tree as well.
2299 */
2300static void invalidate_ce_path(const struct cache_entry *ce,
2301 struct unpack_trees_options *o)
2302{
2303 if (!ce)
2304 return;
2305 cache_tree_invalidate_path(o->src_index, ce->name);
2306 untracked_cache_invalidate_path(o->src_index, ce->name, 1);
2307}
2308
2309/*
2310 * Check that checking out ce->sha1 in subdir ce->name is not
2311 * going to overwrite any working files.
2312 */
2313static int verify_clean_submodule(const char *old_sha1,
2314 const struct cache_entry *ce,
2315 struct unpack_trees_options *o)
2316{
2317 if (!submodule_from_ce(ce))
2318 return 0;
2319
2320 return check_submodule_move_head(ce, old_sha1,
2321 oid_to_hex(&ce->oid), o);
2322}
2323
2324static int verify_clean_subdirectory(const struct cache_entry *ce,
2325 struct unpack_trees_options *o)
2326{
2327 /*
2328 * we are about to extract "ce->name"; we would not want to lose
2329 * anything in the existing directory there.
2330 */
2331 int namelen;
2332 int i;
2333 struct dir_struct d;
2334 char *pathbuf;
2335 int cnt = 0;
2336
2337 if (S_ISGITLINK(ce->ce_mode)) {
2338 struct object_id oid;
2339 int sub_head = repo_resolve_gitlink_ref(the_repository, ce->name,
2340 "HEAD", &oid);
2341 /*
2342 * If we are not going to update the submodule, then
2343 * we don't care.
2344 */
2345 if (!sub_head && oideq(&oid, &ce->oid))
2346 return 0;
2347 return verify_clean_submodule(sub_head ? NULL : oid_to_hex(&oid),
2348 ce, o);
2349 }
2350
2351 /*
2352 * First let's make sure we do not have a local modification
2353 * in that directory.
2354 */
2355 namelen = ce_namelen(ce);
2356 for (i = locate_in_src_index(ce, o);
2357 i < o->src_index->cache_nr;
2358 i++) {
2359 struct cache_entry *ce2 = o->src_index->cache[i];
2360 int len = ce_namelen(ce2);
2361 if (len < namelen ||
2362 strncmp(ce->name, ce2->name, namelen) ||
2363 ce2->name[namelen] != '/')
2364 break;
2365 /*
2366 * ce2->name is an entry in the subdirectory to be
2367 * removed.
2368 */
2369 if (!ce_stage(ce2)) {
2370 if (verify_uptodate(ce2, o))
2371 return -1;
2372 add_entry(o, ce2, CE_REMOVE, 0);
2373 invalidate_ce_path(ce, o);
2374 mark_ce_used(ce2, o);
2375 }
2376 cnt++;
2377 }
2378
2379 /* Do not lose a locally present file that is not ignored. */
2380 pathbuf = xstrfmt("%.*s/", namelen, ce->name);
2381
2382 memset(&d, 0, sizeof(d));
2383 if (o->internal.dir)
2384 setup_standard_excludes(&d);
2385 i = read_directory(&d, o->src_index, pathbuf, namelen+1, NULL);
2386 dir_clear(&d);
2387 free(pathbuf);
2388 if (i)
2389 return add_rejected_path(o, ERROR_NOT_UPTODATE_DIR, ce->name);
2390
2391 /* Do not lose startup_info->original_cwd */
2392 if (startup_info->original_cwd &&
2393 !strcmp(startup_info->original_cwd, ce->name))
2394 return add_rejected_path(o, ERROR_CWD_IN_THE_WAY, ce->name);
2395
2396 return cnt;
2397}
2398
2399/*
2400 * This gets called when there was no index entry for the tree entry 'dst',
2401 * but we found a file in the working tree that 'lstat()' said was fine,
2402 * and we're on a case-insensitive filesystem.
2403 *
2404 * See if we can find a case-insensitive match in the index that also
2405 * matches the stat information, and assume it's that other file!
2406 */
2407static int icase_exists(struct unpack_trees_options *o, const char *name, int len, struct stat *st)
2408{
2409 const struct cache_entry *src;
2410
2411 src = index_file_exists(o->src_index, name, len, 1);
2412 return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
2413}
2414
2415enum absent_checking_type {
2416 COMPLETELY_ABSENT,
2417 ABSENT_ANY_DIRECTORY
2418};
2419
2420static int check_ok_to_remove(const char *name, int len, int dtype,
2421 const struct cache_entry *ce, struct stat *st,
2422 enum unpack_trees_error_types error_type,
2423 enum absent_checking_type absent_type,
2424 struct unpack_trees_options *o)
2425{
2426 const struct cache_entry *result;
2427
2428 /*
2429 * It may be that the 'lstat()' succeeded even though
2430 * target 'ce' was absent, because there is an old
2431 * entry that is different only in case..
2432 *
2433 * Ignore that lstat() if it matches.
2434 */
2435 if (repo_ignore_case(the_repository) && icase_exists(o, name, len, st))
2436 return 0;
2437
2438 if (o->internal.dir &&
2439 is_excluded(o->internal.dir, o->src_index, name, &dtype))
2440 /*
2441 * ce->name is explicitly excluded, so it is Ok to
2442 * overwrite it.
2443 */
2444 return 0;
2445 if (S_ISDIR(st->st_mode)) {
2446 /*
2447 * We are checking out path "foo" and
2448 * found "foo/." in the working tree.
2449 * This is tricky -- if we have modified
2450 * files that are in "foo/" we would lose
2451 * them.
2452 */
2453 if (verify_clean_subdirectory(ce, o) < 0)
2454 return -1;
2455 return 0;
2456 }
2457
2458 /* If we only care about directories, then we can remove */
2459 if (absent_type == ABSENT_ANY_DIRECTORY)
2460 return 0;
2461
2462 /*
2463 * The previous round may already have decided to
2464 * delete this path, which is in a subdirectory that
2465 * is being replaced with a blob.
2466 */
2467 result = index_file_exists(&o->internal.result, name, len, 0);
2468 if (result) {
2469 if (result->ce_flags & CE_REMOVE)
2470 return 0;
2471 }
2472
2473 return add_rejected_path(o, error_type, name);
2474}
2475
2476/*
2477 * We do not want to remove or overwrite a working tree file that
2478 * is not tracked, unless it is ignored.
2479 */
2480static int verify_absent_1(const struct cache_entry *ce,
2481 enum unpack_trees_error_types error_type,
2482 enum absent_checking_type absent_type,
2483 struct unpack_trees_options *o)
2484{
2485 int len;
2486 struct stat st;
2487
2488 if (o->index_only || !o->update)
2489 return 0;
2490
2491 if (o->reset == UNPACK_RESET_OVERWRITE_UNTRACKED) {
2492 /* Avoid nuking startup_info->original_cwd... */
2493 if (startup_info->original_cwd &&
2494 !strcmp(startup_info->original_cwd, ce->name))
2495 return add_rejected_path(o, ERROR_CWD_IN_THE_WAY,
2496 ce->name);
2497 /* ...but nuke anything else. */
2498 return 0;
2499 }
2500
2501 len = check_leading_path(ce->name, ce_namelen(ce), 0);
2502 if (!len)
2503 return 0;
2504 else if (len > 0) {
2505 char *path;
2506 int ret;
2507
2508 path = xmemdupz(ce->name, len);
2509 if (lstat(path, &st))
2510 ret = error_errno("cannot stat '%s'", path);
2511 else {
2512 if (submodule_from_ce(ce))
2513 ret = check_submodule_move_head(ce,
2514 oid_to_hex(&ce->oid),
2515 NULL, o);
2516 else
2517 ret = check_ok_to_remove(path, len, DT_UNKNOWN, NULL,
2518 &st, error_type,
2519 absent_type, o);
2520 }
2521 free(path);
2522 return ret;
2523 } else if (lstat(ce->name, &st)) {
2524 if (errno != ENOENT)
2525 return error_errno("cannot stat '%s'", ce->name);
2526 return 0;
2527 } else {
2528 if (submodule_from_ce(ce))
2529 return check_submodule_move_head(ce, oid_to_hex(&ce->oid),
2530 NULL, o);
2531
2532 return check_ok_to_remove(ce->name, ce_namelen(ce),
2533 ce_to_dtype(ce), ce, &st,
2534 error_type, absent_type, o);
2535 }
2536}
2537
2538static int verify_absent(const struct cache_entry *ce,
2539 enum unpack_trees_error_types error_type,
2540 struct unpack_trees_options *o)
2541{
2542 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2543 return 0;
2544 return verify_absent_1(ce, error_type, COMPLETELY_ABSENT, o);
2545}
2546
2547static int verify_absent_if_directory(const struct cache_entry *ce,
2548 enum unpack_trees_error_types error_type,
2549 struct unpack_trees_options *o)
2550{
2551 if (!o->skip_sparse_checkout && (ce->ce_flags & CE_NEW_SKIP_WORKTREE))
2552 return 0;
2553 return verify_absent_1(ce, error_type, ABSENT_ANY_DIRECTORY, o);
2554}
2555
2556static int verify_absent_sparse(const struct cache_entry *ce,
2557 enum unpack_trees_error_types error_type,
2558 struct unpack_trees_options *o)
2559{
2560 return verify_absent_1(ce, error_type, COMPLETELY_ABSENT, o);
2561}
2562
2563static int merged_entry(const struct cache_entry *ce,
2564 const struct cache_entry *old,
2565 struct unpack_trees_options *o)
2566{
2567 int update = CE_UPDATE;
2568 struct cache_entry *merge = dup_cache_entry(ce, &o->internal.result);
2569
2570 if (!old) {
2571 /*
2572 * New index entries. In sparse checkout, the following
2573 * verify_absent() will be delayed until after
2574 * traverse_trees() finishes in unpack_trees(), then:
2575 *
2576 * - CE_NEW_SKIP_WORKTREE will be computed correctly
2577 * - verify_absent() be called again, this time with
2578 * correct CE_NEW_SKIP_WORKTREE
2579 *
2580 * verify_absent() call here does nothing in sparse
2581 * checkout (i.e. o->skip_sparse_checkout == 0)
2582 */
2583 update |= CE_ADDED;
2584 merge->ce_flags |= CE_NEW_SKIP_WORKTREE;
2585
2586 if (verify_absent(merge,
2587 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
2588 discard_cache_entry(merge);
2589 return -1;
2590 }
2591 invalidate_ce_path(merge, o);
2592
2593 if (submodule_from_ce(ce) && file_exists(ce->name)) {
2594 int ret = check_submodule_move_head(ce, NULL,
2595 oid_to_hex(&ce->oid),
2596 o);
2597 if (ret)
2598 return ret;
2599 }
2600
2601 } else if (!(old->ce_flags & CE_CONFLICTED)) {
2602 /*
2603 * See if we can re-use the old CE directly?
2604 * That way we get the uptodate stat info.
2605 *
2606 * This also removes the UPDATE flag on a match; otherwise
2607 * we will end up overwriting local changes in the work tree.
2608 */
2609 if (same(old, merge)) {
2610 copy_cache_entry(merge, old);
2611 update = 0;
2612 } else {
2613 if (verify_uptodate(old, o)) {
2614 discard_cache_entry(merge);
2615 return -1;
2616 }
2617 /* Migrate old flags over */
2618 update |= old->ce_flags & (CE_SKIP_WORKTREE | CE_NEW_SKIP_WORKTREE);
2619 invalidate_ce_path(old, o);
2620 }
2621
2622 if (submodule_from_ce(ce) && file_exists(ce->name)) {
2623 int ret = check_submodule_move_head(ce, oid_to_hex(&old->oid),
2624 oid_to_hex(&ce->oid),
2625 o);
2626 if (ret)
2627 return ret;
2628 }
2629 } else {
2630 /*
2631 * Previously unmerged entry left as an existence
2632 * marker by read_index_unmerged();
2633 */
2634 if (verify_absent_if_directory(merge,
2635 ERROR_WOULD_LOSE_UNTRACKED_OVERWRITTEN, o)) {
2636 discard_cache_entry(merge);
2637 return -1;
2638 }
2639
2640 invalidate_ce_path(old, o);
2641 }
2642
2643 if (do_add_entry(o, merge, update, CE_STAGEMASK) < 0)
2644 return -1;
2645 return 1;
2646}
2647
2648static int merged_sparse_dir(const struct cache_entry * const *src, int n,
2649 struct unpack_trees_options *o)
2650{
2651 struct tree_desc t[MAX_UNPACK_TREES + 1];
2652 void * tree_bufs[MAX_UNPACK_TREES + 1];
2653 struct traverse_info info;
2654 int i, ret;
2655
2656 /*
2657 * Create the tree traversal information for traversing into *only* the
2658 * sparse directory.
2659 */
2660 setup_traverse_info(&info, src[0]->name);
2661 info.fn = unpack_sparse_callback;
2662 info.data = o;
2663 info.show_all_errors = o->internal.show_all_errors;
2664 info.pathspec = o->pathspec;
2665
2666 /* Get the tree descriptors of the sparse directory in each of the merging trees */
2667 for (i = 0; i < n; i++)
2668 tree_bufs[i] = fill_tree_descriptor(o->src_index->repo, &t[i],
2669 src[i] && !is_null_oid(&src[i]->oid) ? &src[i]->oid : NULL);
2670
2671 ret = traverse_trees(o->src_index, n, t, &info);
2672
2673 for (i = 0; i < n; i++)
2674 free(tree_bufs[i]);
2675
2676 return ret;
2677}
2678
2679static int deleted_entry(const struct cache_entry *ce,
2680 const struct cache_entry *old,
2681 struct unpack_trees_options *o)
2682{
2683 /* Did it exist in the index? */
2684 if (!old) {
2685 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2686 return -1;
2687 return 0;
2688 } else if (verify_absent_if_directory(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o)) {
2689 return -1;
2690 }
2691
2692 if (!(old->ce_flags & CE_CONFLICTED) && verify_uptodate(old, o))
2693 return -1;
2694 add_entry(o, ce, CE_REMOVE, 0);
2695 invalidate_ce_path(ce, o);
2696 return 1;
2697}
2698
2699static int keep_entry(const struct cache_entry *ce,
2700 struct unpack_trees_options *o)
2701{
2702 add_entry(o, ce, 0, 0);
2703 if (ce_stage(ce))
2704 invalidate_ce_path(ce, o);
2705 return 1;
2706}
2707
2708#if DBRT_DEBUG
2709static void show_stage_entry(FILE *o,
2710 const char *label, const struct cache_entry *ce)
2711{
2712 if (!ce)
2713 fprintf(o, "%s (missing)\n", label);
2714 else
2715 fprintf(o, "%s%06o %s %d\t%s\n",
2716 label,
2717 ce->ce_mode,
2718 oid_to_hex(&ce->oid),
2719 ce_stage(ce),
2720 ce->name);
2721}
2722#endif
2723
2724int threeway_merge(const struct cache_entry * const *stages,
2725 struct unpack_trees_options *o)
2726{
2727 const struct cache_entry *index;
2728 const struct cache_entry *head;
2729 const struct cache_entry *remote = stages[o->head_idx + 1];
2730 int count;
2731 int head_match = 0;
2732 int remote_match = 0;
2733
2734 int df_conflict_head = 0;
2735 int df_conflict_remote = 0;
2736
2737 int any_anc_missing = 0;
2738 int no_anc_exists = 1;
2739 int i;
2740
2741 for (i = 1; i < o->head_idx; i++) {
2742 if (!stages[i] || stages[i] == o->df_conflict_entry)
2743 any_anc_missing = 1;
2744 else
2745 no_anc_exists = 0;
2746 }
2747
2748 index = stages[0];
2749 head = stages[o->head_idx];
2750
2751 if (head == o->df_conflict_entry) {
2752 df_conflict_head = 1;
2753 head = NULL;
2754 }
2755
2756 if (remote == o->df_conflict_entry) {
2757 df_conflict_remote = 1;
2758 remote = NULL;
2759 }
2760
2761 /*
2762 * First, if there's a #16 situation, note that to prevent #13
2763 * and #14.
2764 */
2765 if (!same(remote, head)) {
2766 for (i = 1; i < o->head_idx; i++) {
2767 if (same(stages[i], head)) {
2768 head_match = i;
2769 }
2770 if (same(stages[i], remote)) {
2771 remote_match = i;
2772 }
2773 }
2774 }
2775
2776 /*
2777 * We start with cases where the index is allowed to match
2778 * something other than the head: #14(ALT) and #2ALT, where it
2779 * is permitted to match the result instead.
2780 */
2781 /* #14, #14ALT, #2ALT */
2782 if (remote && !df_conflict_head && head_match && !remote_match) {
2783 if (index && !same(index, remote) && !same(index, head)) {
2784 if (S_ISSPARSEDIR(index->ce_mode))
2785 return merged_sparse_dir(stages, 4, o);
2786 else
2787 return reject_merge(index, o);
2788 }
2789 return merged_entry(remote, index, o);
2790 }
2791 /*
2792 * If we have an entry in the index cache, then we want to
2793 * make sure that it matches head.
2794 */
2795 if (index && !same(index, head)) {
2796 if (S_ISSPARSEDIR(index->ce_mode))
2797 return merged_sparse_dir(stages, 4, o);
2798 else
2799 return reject_merge(index, o);
2800 }
2801
2802 if (head) {
2803 /* #5ALT, #15 */
2804 if (same(head, remote))
2805 return merged_entry(head, index, o);
2806 /* #13, #3ALT */
2807 if (!df_conflict_remote && remote_match && !head_match)
2808 return merged_entry(head, index, o);
2809 }
2810
2811 /* #1 */
2812 if (!head && !remote && any_anc_missing)
2813 return 0;
2814
2815 /*
2816 * Under the "aggressive" rule, we resolve mostly trivial
2817 * cases that we historically had git-merge-one-file resolve.
2818 */
2819 if (o->aggressive) {
2820 int head_deleted = !head;
2821 int remote_deleted = !remote;
2822 const struct cache_entry *ce = NULL;
2823
2824 if (index)
2825 ce = index;
2826 else if (head)
2827 ce = head;
2828 else if (remote)
2829 ce = remote;
2830 else {
2831 for (i = 1; i < o->head_idx; i++) {
2832 if (stages[i] && stages[i] != o->df_conflict_entry) {
2833 ce = stages[i];
2834 break;
2835 }
2836 }
2837 }
2838
2839 /*
2840 * Deleted in both.
2841 * Deleted in one and unchanged in the other.
2842 */
2843 if ((head_deleted && remote_deleted) ||
2844 (head_deleted && remote && remote_match) ||
2845 (remote_deleted && head && head_match)) {
2846 if (index)
2847 return deleted_entry(index, index, o);
2848 if (ce && !head_deleted) {
2849 if (verify_absent(ce, ERROR_WOULD_LOSE_UNTRACKED_REMOVED, o))
2850 return -1;
2851 }
2852 return 0;
2853 }
2854 /*
2855 * Added in both, identically.
2856 */
2857 if (no_anc_exists && head && remote && same(head, remote))
2858 return merged_entry(head, index, o);
2859
2860 }
2861
2862 /* Handle "no merge" cases (see t/t1000-read-tree-m-3way.sh) */
2863 if (index) {
2864 /*
2865 * If we've reached the "no merge" cases and we're merging
2866 * a sparse directory, we may have an "edit/edit" conflict that
2867 * can be resolved by individually merging directory contents.
2868 */
2869 if (S_ISSPARSEDIR(index->ce_mode))
2870 return merged_sparse_dir(stages, 4, o);
2871
2872 /*
2873 * If we're not merging a sparse directory, ensure the index is
2874 * up-to-date to avoid files getting overwritten with conflict
2875 * resolution files
2876 */
2877 if (verify_uptodate(index, o))
2878 return -1;
2879 }
2880
2881 o->internal.nontrivial_merge = 1;
2882
2883 /* #2, #3, #4, #6, #7, #9, #10, #11. */
2884 count = 0;
2885 if (!head_match || !remote_match) {
2886 for (i = 1; i < o->head_idx; i++) {
2887 if (stages[i] && stages[i] != o->df_conflict_entry) {
2888 keep_entry(stages[i], o);
2889 count++;
2890 break;
2891 }
2892 }
2893 }
2894#if DBRT_DEBUG
2895 else {
2896 fprintf(stderr, "read-tree: warning #16 detected\n");
2897 show_stage_entry(stderr, "head ", stages[head_match]);
2898 show_stage_entry(stderr, "remote ", stages[remote_match]);
2899 }
2900#endif
2901 if (head) { count += keep_entry(head, o); }
2902 if (remote) { count += keep_entry(remote, o); }
2903 return count;
2904}
2905
2906/*
2907 * Two-way merge.
2908 *
2909 * The rule is to "carry forward" what is in the index without losing
2910 * information across a "fast-forward", favoring a successful merge
2911 * over a merge failure when it makes sense. For details of the
2912 * "carry forward" rule, please see <Documentation/git-read-tree.adoc>.
2913 *
2914 */
2915int twoway_merge(const struct cache_entry * const *src,
2916 struct unpack_trees_options *o)
2917{
2918 const struct cache_entry *current = src[0];
2919 const struct cache_entry *oldtree = src[1];
2920 const struct cache_entry *newtree = src[2];
2921
2922 if (o->internal.merge_size != 2)
2923 return error("Cannot do a twoway merge of %d trees",
2924 o->internal.merge_size);
2925
2926 if (oldtree == o->df_conflict_entry)
2927 oldtree = NULL;
2928 if (newtree == o->df_conflict_entry)
2929 newtree = NULL;
2930
2931 if (current) {
2932 if (current->ce_flags & CE_CONFLICTED) {
2933 if (same(oldtree, newtree) || o->reset) {
2934 if (!newtree)
2935 return deleted_entry(current, current, o);
2936 else
2937 return merged_entry(newtree, current, o);
2938 }
2939 return reject_merge(current, o);
2940 } else if ((!oldtree && !newtree) || /* 4 and 5 */
2941 (!oldtree && newtree &&
2942 same(current, newtree)) || /* 6 and 7 */
2943 (oldtree && newtree &&
2944 same(oldtree, newtree)) || /* 14 and 15 */
2945 (oldtree && newtree &&
2946 !same(oldtree, newtree) && /* 18 and 19 */
2947 same(current, newtree))) {
2948 return keep_entry(current, o);
2949 } else if (oldtree && !newtree && same(current, oldtree)) {
2950 /* 10 or 11 */
2951 return deleted_entry(oldtree, current, o);
2952 } else if (oldtree && newtree &&
2953 same(current, oldtree) && !same(current, newtree)) {
2954 /* 20 or 21 */
2955 return merged_entry(newtree, current, o);
2956 } else if (current && !oldtree && newtree &&
2957 S_ISSPARSEDIR(current->ce_mode) != S_ISSPARSEDIR(newtree->ce_mode) &&
2958 ce_stage(current) == 0) {
2959 /*
2960 * This case is a directory/file conflict across the sparse-index
2961 * boundary. When we are changing from one path to another via
2962 * 'git checkout', then we want to replace one entry with another
2963 * via merged_entry(). If there are staged changes, then we should
2964 * reject the merge instead.
2965 */
2966 return merged_entry(newtree, current, o);
2967 } else if (S_ISSPARSEDIR(current->ce_mode)) {
2968 /*
2969 * The sparse directories differ, but we don't know whether that's
2970 * because of two different files in the directory being modified
2971 * (can be trivially merged) or if there is a real file conflict.
2972 * Merge the sparse directory by OID to compare file-by-file.
2973 */
2974 return merged_sparse_dir(src, 3, o);
2975 } else
2976 return reject_merge(current, o);
2977 }
2978 else if (newtree) {
2979 if (oldtree && !o->initial_checkout) {
2980 /*
2981 * deletion of the path was staged;
2982 */
2983 if (same(oldtree, newtree))
2984 return 1;
2985 return reject_merge(oldtree, o);
2986 }
2987 return merged_entry(newtree, current, o);
2988 }
2989 return deleted_entry(oldtree, current, o);
2990}
2991
2992/*
2993 * Bind merge.
2994 *
2995 * Keep the index entries at stage0, collapse stage1 but make sure
2996 * stage0 does not have anything there.
2997 */
2998int bind_merge(const struct cache_entry * const *src,
2999 struct unpack_trees_options *o)
3000{
3001 const struct cache_entry *old = src[0];
3002 const struct cache_entry *a = src[1];
3003
3004 if (o->internal.merge_size != 1)
3005 return error("Cannot do a bind merge of %d trees",
3006 o->internal.merge_size);
3007 if (a && old)
3008 return o->quiet ? -1 :
3009 error(ERRORMSG(o, ERROR_BIND_OVERLAP),
3010 super_prefixed(a->name, o->super_prefix),
3011 super_prefixed(old->name, o->super_prefix));
3012 if (!a)
3013 return keep_entry(old, o);
3014 else
3015 return merged_entry(a, NULL, o);
3016}
3017
3018/*
3019 * One-way merge.
3020 *
3021 * The rule is:
3022 * - take the stat information from stage0, take the data from stage1
3023 */
3024int oneway_merge(const struct cache_entry * const *src,
3025 struct unpack_trees_options *o)
3026{
3027 const struct cache_entry *old = src[0];
3028 const struct cache_entry *a = src[1];
3029
3030 if (o->internal.merge_size != 1)
3031 return error("Cannot do a oneway merge of %d trees",
3032 o->internal.merge_size);
3033
3034 if (!a || a == o->df_conflict_entry)
3035 return deleted_entry(old, old, o);
3036
3037 if (old && same(old, a)) {
3038 int update = 0;
3039 if (o->reset && o->update && !ce_uptodate(old) && !ce_skip_worktree(old) &&
3040 !(old->ce_flags & CE_FSMONITOR_VALID)) {
3041 struct stat st;
3042 if (lstat(old->name, &st) ||
3043 ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE))
3044 update |= CE_UPDATE;
3045 }
3046 if (o->update && S_ISGITLINK(old->ce_mode) &&
3047 should_update_submodules() && !verify_uptodate(old, o))
3048 update |= CE_UPDATE;
3049 add_entry(o, old, update, CE_STAGEMASK);
3050 return 0;
3051 }
3052 return merged_entry(a, old, o);
3053}
3054
3055/*
3056 * Merge worktree and untracked entries in a stash entry.
3057 *
3058 * Ignore all index entries. Collapse remaining trees but make sure that they
3059 * don't have any conflicting files.
3060 */
3061int stash_worktree_untracked_merge(const struct cache_entry * const *src,
3062 struct unpack_trees_options *o)
3063{
3064 const struct cache_entry *worktree = src[1];
3065 const struct cache_entry *untracked = src[2];
3066
3067 if (o->internal.merge_size != 2)
3068 BUG("invalid merge_size: %d", o->internal.merge_size);
3069
3070 if (worktree && untracked)
3071 return error(_("worktree and untracked commit have duplicate entries: %s"),
3072 super_prefixed(worktree->name, o->super_prefix));
3073
3074 return merged_entry(worktree ? worktree : untracked, NULL, o);
3075}