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