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