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