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