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