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