Coverage Report

Created: 2026-12-01 06:58

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