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