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