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