Coverage Report

Created: 2026-01-09 07:10

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