Coverage Report

Created: 2026-09-28 06:15

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