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