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