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