at commit a0189536

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