unpack-trees.con commit sparse checkout: inhibit empty worktree (9e1afb1)
   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
  12/*
  13 * Error messages expected by scripts out of plumbing commands such as
  14 * read-tree.  Non-scripted Porcelain is not required to use these messages
  15 * and in fact are encouraged to reword them to better suit their particular
  16 * situation better.  See how "git checkout" replaces not_uptodate_file to
  17 * explain why it does not allow switching between branches when you have
  18 * local changes, for example.
  19 */
  20static struct unpack_trees_error_msgs unpack_plumbing_errors = {
  21        /* would_overwrite */
  22        "Entry '%s' would be overwritten by merge. Cannot merge.",
  23
  24        /* not_uptodate_file */
  25        "Entry '%s' not uptodate. Cannot merge.",
  26
  27        /* not_uptodate_dir */
  28        "Updating '%s' would lose untracked files in it",
  29
  30        /* would_lose_untracked */
  31        "Untracked working tree file '%s' would be %s by merge.",
  32
  33        /* bind_overlap */
  34        "Entry '%s' overlaps with '%s'.  Cannot bind.",
  35
  36        /* sparse_not_uptodate_file */
  37        "Entry '%s' not uptodate. Cannot update sparse checkout.",
  38
  39        /* would_lose_orphaned */
  40        "Working tree file '%s' would be %s by sparse checkout update.",
  41};
  42
  43#define ERRORMSG(o,fld) \
  44        ( ((o) && (o)->msgs.fld) \
  45        ? ((o)->msgs.fld) \
  46        : (unpack_plumbing_errors.fld) )
  47
  48static void add_entry(struct unpack_trees_options *o, struct cache_entry *ce,
  49        unsigned int set, unsigned int clear)
  50{
  51        unsigned int size = ce_size(ce);
  52        struct cache_entry *new = xmalloc(size);
  53
  54        clear |= CE_HASHED | CE_UNHASHED;
  55
  56        memcpy(new, ce, size);
  57        new->next = NULL;
  58        new->ce_flags = (new->ce_flags & ~clear) | set;
  59        add_index_entry(&o->result, new, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
  60}
  61
  62/*
  63 * Unlink the last component and schedule the leading directories for
  64 * removal, such that empty directories get removed.
  65 */
  66static void unlink_entry(struct cache_entry *ce)
  67{
  68        if (has_symlink_or_noent_leading_path(ce->name, ce_namelen(ce)))
  69                return;
  70        if (unlink_or_warn(ce->name))
  71                return;
  72        schedule_dir_for_removal(ce->name, ce_namelen(ce));
  73}
  74
  75static struct checkout state;
  76static int check_updates(struct unpack_trees_options *o)
  77{
  78        unsigned cnt = 0, total = 0;
  79        struct progress *progress = NULL;
  80        struct index_state *index = &o->result;
  81        int i;
  82        int errs = 0;
  83
  84        if (o->update && o->verbose_update) {
  85                for (total = cnt = 0; cnt < index->cache_nr; cnt++) {
  86                        struct cache_entry *ce = index->cache[cnt];
  87                        if (ce->ce_flags & (CE_UPDATE | CE_REMOVE | CE_WT_REMOVE))
  88                                total++;
  89                }
  90
  91                progress = start_progress_delay("Checking out files",
  92                                                total, 50, 1);
  93                cnt = 0;
  94        }
  95
  96        if (o->update)
  97                git_attr_set_direction(GIT_ATTR_CHECKOUT, &o->result);
  98        for (i = 0; i < index->cache_nr; i++) {
  99                struct cache_entry *ce = index->cache[i];
 100
 101                if (ce->ce_flags & CE_WT_REMOVE) {
 102                        display_progress(progress, ++cnt);
 103                        if (o->update)
 104                                unlink_entry(ce);
 105                        continue;
 106                }
 107
 108                if (ce->ce_flags & CE_REMOVE) {
 109                        display_progress(progress, ++cnt);
 110                        if (o->update)
 111                                unlink_entry(ce);
 112                }
 113        }
 114        remove_marked_cache_entries(&o->result);
 115        remove_scheduled_dirs();
 116
 117        for (i = 0; i < index->cache_nr; i++) {
 118                struct cache_entry *ce = index->cache[i];
 119
 120                if (ce->ce_flags & CE_UPDATE) {
 121                        display_progress(progress, ++cnt);
 122                        ce->ce_flags &= ~CE_UPDATE;
 123                        if (o->update) {
 124                                errs |= checkout_entry(ce, &state, NULL);
 125                        }
 126                }
 127        }
 128        stop_progress(&progress);
 129        if (o->update)
 130                git_attr_set_direction(GIT_ATTR_CHECKIN, NULL);
 131        return errs != 0;
 132}
 133
 134static int verify_uptodate_sparse(struct cache_entry *ce, struct unpack_trees_options *o);
 135static int verify_absent_sparse(struct cache_entry *ce, const char *action, struct unpack_trees_options *o);
 136
 137static int will_have_skip_worktree(const struct cache_entry *ce, struct unpack_trees_options *o)
 138{
 139        const char *basename;
 140
 141        if (ce_stage(ce))
 142                return 0;
 143
 144        basename = strrchr(ce->name, '/');
 145        basename = basename ? basename+1 : ce->name;
 146        return excluded_from_list(ce->name, ce_namelen(ce), basename, NULL, o->el) <= 0;
 147}
 148
 149static int apply_sparse_checkout(struct cache_entry *ce, struct unpack_trees_options *o)
 150{
 151        int was_skip_worktree = ce_skip_worktree(ce);
 152
 153        if (will_have_skip_worktree(ce, o))
 154                ce->ce_flags |= CE_SKIP_WORKTREE;
 155        else
 156                ce->ce_flags &= ~CE_SKIP_WORKTREE;
 157
 158        /*
 159         * We only care about files getting into the checkout area
 160         * If merge strategies want to remove some, go ahead, this
 161         * flag will be removed eventually in unpack_trees() if it's
 162         * outside checkout area.
 163         */
 164        if (ce->ce_flags & CE_REMOVE)
 165                return 0;
 166
 167        if (!was_skip_worktree && ce_skip_worktree(ce)) {
 168                /*
 169                 * If CE_UPDATE is set, verify_uptodate() must be called already
 170                 * also stat info may have lost after merged_entry() so calling
 171                 * verify_uptodate() again may fail
 172                 */
 173                if (!(ce->ce_flags & CE_UPDATE) && verify_uptodate_sparse(ce, o))
 174                        return -1;
 175                ce->ce_flags |= CE_WT_REMOVE;
 176        }
 177        if (was_skip_worktree && !ce_skip_worktree(ce)) {
 178                if (verify_absent_sparse(ce, "overwritten", o))
 179                        return -1;
 180                ce->ce_flags |= CE_UPDATE;
 181        }
 182        return 0;
 183}
 184
 185static inline int call_unpack_fn(struct cache_entry **src, struct unpack_trees_options *o)
 186{
 187        int ret = o->fn(src, o);
 188        if (ret > 0)
 189                ret = 0;
 190        return ret;
 191}
 192
 193static int unpack_index_entry(struct cache_entry *ce, struct unpack_trees_options *o)
 194{
 195        struct cache_entry *src[5] = { ce, NULL, };
 196
 197        o->pos++;
 198        if (ce_stage(ce)) {
 199                if (o->skip_unmerged) {
 200                        add_entry(o, ce, 0, 0);
 201                        return 0;
 202                }
 203        }
 204        return call_unpack_fn(src, o);
 205}
 206
 207static int traverse_trees_recursive(int n, unsigned long dirmask, unsigned long df_conflicts, struct name_entry *names, struct traverse_info *info)
 208{
 209        int i;
 210        struct tree_desc t[MAX_UNPACK_TREES];
 211        struct traverse_info newinfo;
 212        struct name_entry *p;
 213
 214        p = names;
 215        while (!p->mode)
 216                p++;
 217
 218        newinfo = *info;
 219        newinfo.prev = info;
 220        newinfo.name = *p;
 221        newinfo.pathlen += tree_entry_len(p->path, p->sha1) + 1;
 222        newinfo.conflicts |= df_conflicts;
 223
 224        for (i = 0; i < n; i++, dirmask >>= 1) {
 225                const unsigned char *sha1 = NULL;
 226                if (dirmask & 1)
 227                        sha1 = names[i].sha1;
 228                fill_tree_descriptor(t+i, sha1);
 229        }
 230        return traverse_trees(n, t, &newinfo);
 231}
 232
 233/*
 234 * Compare the traverse-path to the cache entry without actually
 235 * having to generate the textual representation of the traverse
 236 * path.
 237 *
 238 * NOTE! This *only* compares up to the size of the traverse path
 239 * itself - the caller needs to do the final check for the cache
 240 * entry having more data at the end!
 241 */
 242static int do_compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
 243{
 244        int len, pathlen, ce_len;
 245        const char *ce_name;
 246
 247        if (info->prev) {
 248                int cmp = do_compare_entry(ce, info->prev, &info->name);
 249                if (cmp)
 250                        return cmp;
 251        }
 252        pathlen = info->pathlen;
 253        ce_len = ce_namelen(ce);
 254
 255        /* If ce_len < pathlen then we must have previously hit "name == directory" entry */
 256        if (ce_len < pathlen)
 257                return -1;
 258
 259        ce_len -= pathlen;
 260        ce_name = ce->name + pathlen;
 261
 262        len = tree_entry_len(n->path, n->sha1);
 263        return df_name_compare(ce_name, ce_len, S_IFREG, n->path, len, n->mode);
 264}
 265
 266static int compare_entry(const struct cache_entry *ce, const struct traverse_info *info, const struct name_entry *n)
 267{
 268        int cmp = do_compare_entry(ce, info, n);
 269        if (cmp)
 270                return cmp;
 271
 272        /*
 273         * Even if the beginning compared identically, the ce should
 274         * compare as bigger than a directory leading up to it!
 275         */
 276        return ce_namelen(ce) > traverse_path_len(info, n);
 277}
 278
 279static struct cache_entry *create_ce_entry(const struct traverse_info *info, const struct name_entry *n, int stage)
 280{
 281        int len = traverse_path_len(info, n);
 282        struct cache_entry *ce = xcalloc(1, cache_entry_size(len));
 283
 284        ce->ce_mode = create_ce_mode(n->mode);
 285        ce->ce_flags = create_ce_flags(len, stage);
 286        hashcpy(ce->sha1, n->sha1);
 287        make_traverse_path(ce->name, info, n);
 288
 289        return ce;
 290}
 291
 292static int unpack_nondirectories(int n, unsigned long mask,
 293                                 unsigned long dirmask,
 294                                 struct cache_entry **src,
 295                                 const struct name_entry *names,
 296                                 const struct traverse_info *info)
 297{
 298        int i;
 299        struct unpack_trees_options *o = info->data;
 300        unsigned long conflicts;
 301
 302        /* Do we have *only* directories? Nothing to do */
 303        if (mask == dirmask && !src[0])
 304                return 0;
 305
 306        conflicts = info->conflicts;
 307        if (o->merge)
 308                conflicts >>= 1;
 309        conflicts |= dirmask;
 310
 311        /*
 312         * Ok, we've filled in up to any potential index entry in src[0],
 313         * now do the rest.
 314         */
 315        for (i = 0; i < n; i++) {
 316                int stage;
 317                unsigned int bit = 1ul << i;
 318                if (conflicts & bit) {
 319                        src[i + o->merge] = o->df_conflict_entry;
 320                        continue;
 321                }
 322                if (!(mask & bit))
 323                        continue;
 324                if (!o->merge)
 325                        stage = 0;
 326                else if (i + 1 < o->head_idx)
 327                        stage = 1;
 328                else if (i + 1 > o->head_idx)
 329                        stage = 3;
 330                else
 331                        stage = 2;
 332                src[i + o->merge] = create_ce_entry(info, names + i, stage);
 333        }
 334
 335        if (o->merge)
 336                return call_unpack_fn(src, o);
 337
 338        for (i = 0; i < n; i++)
 339                if (src[i] && src[i] != o->df_conflict_entry)
 340                        add_entry(o, src[i], 0, 0);
 341        return 0;
 342}
 343
 344static int unpack_callback(int n, unsigned long mask, unsigned long dirmask, struct name_entry *names, struct traverse_info *info)
 345{
 346        struct cache_entry *src[MAX_UNPACK_TREES + 1] = { NULL, };
 347        struct unpack_trees_options *o = info->data;
 348        const struct name_entry *p = names;
 349
 350        /* Find first entry with a real name (we could use "mask" too) */
 351        while (!p->mode)
 352                p++;
 353
 354        /* Are we supposed to look at the index too? */
 355        if (o->merge) {
 356                while (o->pos < o->src_index->cache_nr) {
 357                        struct cache_entry *ce = o->src_index->cache[o->pos];
 358                        int cmp = compare_entry(ce, info, p);
 359                        if (cmp < 0) {
 360                                if (unpack_index_entry(ce, o) < 0)
 361                                        return -1;
 362                                continue;
 363                        }
 364                        if (!cmp) {
 365                                o->pos++;
 366                                if (ce_stage(ce)) {
 367                                        /*
 368                                         * If we skip unmerged index entries, we'll skip this
 369                                         * entry *and* the tree entries associated with it!
 370                                         */
 371                                        if (o->skip_unmerged) {
 372                                                add_entry(o, ce, 0, 0);
 373                                                return mask;
 374                                        }
 375                                }
 376                                src[0] = ce;
 377                        }
 378                        break;
 379                }
 380        }
 381
 382        if (unpack_nondirectories(n, mask, dirmask, src, names, info) < 0)
 383                return -1;
 384
 385        /* Now handle any directories.. */
 386        if (dirmask) {
 387                unsigned long conflicts = mask & ~dirmask;
 388                if (o->merge) {
 389                        conflicts <<= 1;
 390                        if (src[0])
 391                                conflicts |= 1;
 392                }
 393
 394                /* special case: "diff-index --cached" looking at a tree */
 395                if (o->diff_index_cached &&
 396                    n == 1 && dirmask == 1 && S_ISDIR(names->mode)) {
 397                        int matches;
 398                        matches = cache_tree_matches_traversal(o->src_index->cache_tree,
 399                                                               names, info);
 400                        /*
 401                         * Everything under the name matches.  Adjust o->pos to
 402                         * skip the entire hierarchy.
 403                         */
 404                        if (matches) {
 405                                o->pos += matches;
 406                                return mask;
 407                        }
 408                }
 409
 410                if (traverse_trees_recursive(n, dirmask, conflicts,
 411                                             names, info) < 0)
 412                        return -1;
 413                return mask;
 414        }
 415
 416        return mask;
 417}
 418
 419static int unpack_failed(struct unpack_trees_options *o, const char *message)
 420{
 421        discard_index(&o->result);
 422        if (!o->gently) {
 423                if (message)
 424                        return error("%s", message);
 425                return -1;
 426        }
 427        return -1;
 428}
 429
 430/*
 431 * N-way merge "len" trees.  Returns 0 on success, -1 on failure to manipulate the
 432 * resulting index, -2 on failure to reflect the changes to the work tree.
 433 */
 434int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options *o)
 435{
 436        int i, ret;
 437        static struct cache_entry *dfc;
 438        struct exclude_list el;
 439
 440        if (len > MAX_UNPACK_TREES)
 441                die("unpack_trees takes at most %d trees", MAX_UNPACK_TREES);
 442        memset(&state, 0, sizeof(state));
 443        state.base_dir = "";
 444        state.force = 1;
 445        state.quiet = 1;
 446        state.refresh_cache = 1;
 447
 448        memset(&el, 0, sizeof(el));
 449        if (!core_apply_sparse_checkout || !o->update)
 450                o->skip_sparse_checkout = 1;
 451        if (!o->skip_sparse_checkout) {
 452                if (add_excludes_from_file_to_list(git_path("info/sparse-checkout"), "", 0, NULL, &el, 0) < 0)
 453                        o->skip_sparse_checkout = 1;
 454                else
 455                        o->el = &el;
 456        }
 457
 458        memset(&o->result, 0, sizeof(o->result));
 459        o->result.initialized = 1;
 460        if (o->src_index) {
 461                o->result.timestamp.sec = o->src_index->timestamp.sec;
 462                o->result.timestamp.nsec = o->src_index->timestamp.nsec;
 463        }
 464        o->merge_size = len;
 465
 466        if (!dfc)
 467                dfc = xcalloc(1, cache_entry_size(0));
 468        o->df_conflict_entry = dfc;
 469
 470        if (len) {
 471                const char *prefix = o->prefix ? o->prefix : "";
 472                struct traverse_info info;
 473
 474                setup_traverse_info(&info, prefix);
 475                info.fn = unpack_callback;
 476                info.data = o;
 477
 478                if (traverse_trees(len, t, &info) < 0) {
 479                        ret = unpack_failed(o, NULL);
 480                        goto done;
 481                }
 482        }
 483
 484        /* Any left-over entries in the index? */
 485        if (o->merge) {
 486                while (o->pos < o->src_index->cache_nr) {
 487                        struct cache_entry *ce = o->src_index->cache[o->pos];
 488                        if (unpack_index_entry(ce, o) < 0) {
 489                                ret = unpack_failed(o, NULL);
 490                                goto done;
 491                        }
 492                }
 493        }
 494
 495        if (o->trivial_merges_only && o->nontrivial_merge) {
 496                ret = unpack_failed(o, "Merge requires file-level merging");
 497                goto done;
 498        }
 499
 500        if (!o->skip_sparse_checkout) {
 501                int empty_worktree = 1;
 502                for (i = 0;i < o->result.cache_nr;i++) {
 503                        struct cache_entry *ce = o->result.cache[i];
 504
 505                        if (apply_sparse_checkout(ce, o)) {
 506                                ret = -1;
 507                                goto done;
 508                        }
 509                        /*
 510                         * Merge strategies may set CE_UPDATE|CE_REMOVE outside checkout
 511                         * area as a result of ce_skip_worktree() shortcuts in
 512                         * verify_absent() and verify_uptodate(). Clear them.
 513                         */
 514                        if (ce_skip_worktree(ce))
 515                                ce->ce_flags &= ~(CE_UPDATE | CE_REMOVE);
 516                        else
 517                                empty_worktree = 0;
 518
 519                }
 520                if (o->result.cache_nr && empty_worktree) {
 521                        ret = unpack_failed(o, "Sparse checkout leaves no entry on working directory");
 522                        goto done;
 523                }
 524        }
 525
 526        o->src_index = NULL;
 527        ret = check_updates(o) ? (-2) : 0;
 528        if (o->dst_index)
 529                *o->dst_index = o->result;
 530
 531done:
 532        for (i = 0;i < el.nr;i++)
 533                free(el.excludes[i]);
 534        if (el.excludes)
 535                free(el.excludes);
 536
 537        return ret;
 538}
 539
 540/* Here come the merge functions */
 541
 542static int reject_merge(struct cache_entry *ce, struct unpack_trees_options *o)
 543{
 544        return error(ERRORMSG(o, would_overwrite), ce->name);
 545}
 546
 547static int same(struct cache_entry *a, struct cache_entry *b)
 548{
 549        if (!!a != !!b)
 550                return 0;
 551        if (!a && !b)
 552                return 1;
 553        return a->ce_mode == b->ce_mode &&
 554               !hashcmp(a->sha1, b->sha1);
 555}
 556
 557
 558/*
 559 * When a CE gets turned into an unmerged entry, we
 560 * want it to be up-to-date
 561 */
 562static int verify_uptodate_1(struct cache_entry *ce,
 563                                   struct unpack_trees_options *o,
 564                                   const char *error_msg)
 565{
 566        struct stat st;
 567
 568        if (o->index_only || (!ce_skip_worktree(ce) && (o->reset || ce_uptodate(ce))))
 569                return 0;
 570
 571        if (!lstat(ce->name, &st)) {
 572                unsigned changed = ie_match_stat(o->src_index, ce, &st, CE_MATCH_IGNORE_VALID);
 573                if (!changed)
 574                        return 0;
 575                /*
 576                 * NEEDSWORK: the current default policy is to allow
 577                 * submodule to be out of sync wrt the supermodule
 578                 * index.  This needs to be tightened later for
 579                 * submodules that are marked to be automatically
 580                 * checked out.
 581                 */
 582                if (S_ISGITLINK(ce->ce_mode))
 583                        return 0;
 584                errno = 0;
 585        }
 586        if (errno == ENOENT)
 587                return 0;
 588        return o->gently ? -1 :
 589                error(error_msg, ce->name);
 590}
 591
 592static int verify_uptodate(struct cache_entry *ce,
 593                           struct unpack_trees_options *o)
 594{
 595        if (!o->skip_sparse_checkout && will_have_skip_worktree(ce, o))
 596                return 0;
 597        return verify_uptodate_1(ce, o, ERRORMSG(o, not_uptodate_file));
 598}
 599
 600static int verify_uptodate_sparse(struct cache_entry *ce,
 601                                  struct unpack_trees_options *o)
 602{
 603        return verify_uptodate_1(ce, o, ERRORMSG(o, sparse_not_uptodate_file));
 604}
 605
 606static void invalidate_ce_path(struct cache_entry *ce, struct unpack_trees_options *o)
 607{
 608        if (ce)
 609                cache_tree_invalidate_path(o->src_index->cache_tree, ce->name);
 610}
 611
 612/*
 613 * Check that checking out ce->sha1 in subdir ce->name is not
 614 * going to overwrite any working files.
 615 *
 616 * Currently, git does not checkout subprojects during a superproject
 617 * checkout, so it is not going to overwrite anything.
 618 */
 619static int verify_clean_submodule(struct cache_entry *ce, const char *action,
 620                                      struct unpack_trees_options *o)
 621{
 622        return 0;
 623}
 624
 625static int verify_clean_subdirectory(struct cache_entry *ce, const char *action,
 626                                      struct unpack_trees_options *o)
 627{
 628        /*
 629         * we are about to extract "ce->name"; we would not want to lose
 630         * anything in the existing directory there.
 631         */
 632        int namelen;
 633        int i;
 634        struct dir_struct d;
 635        char *pathbuf;
 636        int cnt = 0;
 637        unsigned char sha1[20];
 638
 639        if (S_ISGITLINK(ce->ce_mode) &&
 640            resolve_gitlink_ref(ce->name, "HEAD", sha1) == 0) {
 641                /* If we are not going to update the submodule, then
 642                 * we don't care.
 643                 */
 644                if (!hashcmp(sha1, ce->sha1))
 645                        return 0;
 646                return verify_clean_submodule(ce, action, o);
 647        }
 648
 649        /*
 650         * First let's make sure we do not have a local modification
 651         * in that directory.
 652         */
 653        namelen = strlen(ce->name);
 654        for (i = o->pos; i < o->src_index->cache_nr; i++) {
 655                struct cache_entry *ce2 = o->src_index->cache[i];
 656                int len = ce_namelen(ce2);
 657                if (len < namelen ||
 658                    strncmp(ce->name, ce2->name, namelen) ||
 659                    ce2->name[namelen] != '/')
 660                        break;
 661                /*
 662                 * ce2->name is an entry in the subdirectory.
 663                 */
 664                if (!ce_stage(ce2)) {
 665                        if (verify_uptodate(ce2, o))
 666                                return -1;
 667                        add_entry(o, ce2, CE_REMOVE, 0);
 668                }
 669                cnt++;
 670        }
 671
 672        /*
 673         * Then we need to make sure that we do not lose a locally
 674         * present file that is not ignored.
 675         */
 676        pathbuf = xmalloc(namelen + 2);
 677        memcpy(pathbuf, ce->name, namelen);
 678        strcpy(pathbuf+namelen, "/");
 679
 680        memset(&d, 0, sizeof(d));
 681        if (o->dir)
 682                d.exclude_per_dir = o->dir->exclude_per_dir;
 683        i = read_directory(&d, pathbuf, namelen+1, NULL);
 684        if (i)
 685                return o->gently ? -1 :
 686                        error(ERRORMSG(o, not_uptodate_dir), ce->name);
 687        free(pathbuf);
 688        return cnt;
 689}
 690
 691/*
 692 * This gets called when there was no index entry for the tree entry 'dst',
 693 * but we found a file in the working tree that 'lstat()' said was fine,
 694 * and we're on a case-insensitive filesystem.
 695 *
 696 * See if we can find a case-insensitive match in the index that also
 697 * matches the stat information, and assume it's that other file!
 698 */
 699static int icase_exists(struct unpack_trees_options *o, struct cache_entry *dst, struct stat *st)
 700{
 701        struct cache_entry *src;
 702
 703        src = index_name_exists(o->src_index, dst->name, ce_namelen(dst), 1);
 704        return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID);
 705}
 706
 707/*
 708 * We do not want to remove or overwrite a working tree file that
 709 * is not tracked, unless it is ignored.
 710 */
 711static int verify_absent_1(struct cache_entry *ce, const char *action,
 712                                 struct unpack_trees_options *o,
 713                                 const char *error_msg)
 714{
 715        struct stat st;
 716
 717        if (o->index_only || o->reset || !o->update)
 718                return 0;
 719
 720        if (has_symlink_or_noent_leading_path(ce->name, ce_namelen(ce)))
 721                return 0;
 722
 723        if (!lstat(ce->name, &st)) {
 724                int ret;
 725                int dtype = ce_to_dtype(ce);
 726                struct cache_entry *result;
 727
 728                /*
 729                 * It may be that the 'lstat()' succeeded even though
 730                 * target 'ce' was absent, because there is an old
 731                 * entry that is different only in case..
 732                 *
 733                 * Ignore that lstat() if it matches.
 734                 */
 735                if (ignore_case && icase_exists(o, ce, &st))
 736                        return 0;
 737
 738                if (o->dir && excluded(o->dir, ce->name, &dtype))
 739                        /*
 740                         * ce->name is explicitly excluded, so it is Ok to
 741                         * overwrite it.
 742                         */
 743                        return 0;
 744                if (S_ISDIR(st.st_mode)) {
 745                        /*
 746                         * We are checking out path "foo" and
 747                         * found "foo/." in the working tree.
 748                         * This is tricky -- if we have modified
 749                         * files that are in "foo/" we would lose
 750                         * it.
 751                         */
 752                        ret = verify_clean_subdirectory(ce, action, o);
 753                        if (ret < 0)
 754                                return ret;
 755
 756                        /*
 757                         * If this removed entries from the index,
 758                         * what that means is:
 759                         *
 760                         * (1) the caller unpack_callback() saw path/foo
 761                         * in the index, and it has not removed it because
 762                         * it thinks it is handling 'path' as blob with
 763                         * D/F conflict;
 764                         * (2) we will return "ok, we placed a merged entry
 765                         * in the index" which would cause o->pos to be
 766                         * incremented by one;
 767                         * (3) however, original o->pos now has 'path/foo'
 768                         * marked with "to be removed".
 769                         *
 770                         * We need to increment it by the number of
 771                         * deleted entries here.
 772                         */
 773                        o->pos += ret;
 774                        return 0;
 775                }
 776
 777                /*
 778                 * The previous round may already have decided to
 779                 * delete this path, which is in a subdirectory that
 780                 * is being replaced with a blob.
 781                 */
 782                result = index_name_exists(&o->result, ce->name, ce_namelen(ce), 0);
 783                if (result) {
 784                        if (result->ce_flags & CE_REMOVE)
 785                                return 0;
 786                }
 787
 788                return o->gently ? -1 :
 789                        error(ERRORMSG(o, would_lose_untracked), ce->name, action);
 790        }
 791        return 0;
 792}
 793static int verify_absent(struct cache_entry *ce, const char *action,
 794                         struct unpack_trees_options *o)
 795{
 796        if (!o->skip_sparse_checkout && will_have_skip_worktree(ce, o))
 797                return 0;
 798        return verify_absent_1(ce, action, o, ERRORMSG(o, would_lose_untracked));
 799}
 800
 801static int verify_absent_sparse(struct cache_entry *ce, const char *action,
 802                         struct unpack_trees_options *o)
 803{
 804        return verify_absent_1(ce, action, o, ERRORMSG(o, would_lose_orphaned));
 805}
 806
 807static int merged_entry(struct cache_entry *merge, struct cache_entry *old,
 808                struct unpack_trees_options *o)
 809{
 810        int update = CE_UPDATE;
 811
 812        if (old) {
 813                /*
 814                 * See if we can re-use the old CE directly?
 815                 * That way we get the uptodate stat info.
 816                 *
 817                 * This also removes the UPDATE flag on a match; otherwise
 818                 * we will end up overwriting local changes in the work tree.
 819                 */
 820                if (same(old, merge)) {
 821                        copy_cache_entry(merge, old);
 822                        update = 0;
 823                } else {
 824                        if (verify_uptodate(old, o))
 825                                return -1;
 826                        if (ce_skip_worktree(old))
 827                                update |= CE_SKIP_WORKTREE;
 828                        invalidate_ce_path(old, o);
 829                }
 830        }
 831        else {
 832                if (verify_absent(merge, "overwritten", o))
 833                        return -1;
 834                invalidate_ce_path(merge, o);
 835        }
 836
 837        add_entry(o, merge, update, CE_STAGEMASK);
 838        return 1;
 839}
 840
 841static int deleted_entry(struct cache_entry *ce, struct cache_entry *old,
 842                struct unpack_trees_options *o)
 843{
 844        /* Did it exist in the index? */
 845        if (!old) {
 846                if (verify_absent(ce, "removed", o))
 847                        return -1;
 848                return 0;
 849        }
 850        if (verify_uptodate(old, o))
 851                return -1;
 852        add_entry(o, ce, CE_REMOVE, 0);
 853        invalidate_ce_path(ce, o);
 854        return 1;
 855}
 856
 857static int keep_entry(struct cache_entry *ce, struct unpack_trees_options *o)
 858{
 859        add_entry(o, ce, 0, 0);
 860        return 1;
 861}
 862
 863#if DBRT_DEBUG
 864static void show_stage_entry(FILE *o,
 865                             const char *label, const struct cache_entry *ce)
 866{
 867        if (!ce)
 868                fprintf(o, "%s (missing)\n", label);
 869        else
 870                fprintf(o, "%s%06o %s %d\t%s\n",
 871                        label,
 872                        ce->ce_mode,
 873                        sha1_to_hex(ce->sha1),
 874                        ce_stage(ce),
 875                        ce->name);
 876}
 877#endif
 878
 879int threeway_merge(struct cache_entry **stages, struct unpack_trees_options *o)
 880{
 881        struct cache_entry *index;
 882        struct cache_entry *head;
 883        struct cache_entry *remote = stages[o->head_idx + 1];
 884        int count;
 885        int head_match = 0;
 886        int remote_match = 0;
 887
 888        int df_conflict_head = 0;
 889        int df_conflict_remote = 0;
 890
 891        int any_anc_missing = 0;
 892        int no_anc_exists = 1;
 893        int i;
 894
 895        for (i = 1; i < o->head_idx; i++) {
 896                if (!stages[i] || stages[i] == o->df_conflict_entry)
 897                        any_anc_missing = 1;
 898                else
 899                        no_anc_exists = 0;
 900        }
 901
 902        index = stages[0];
 903        head = stages[o->head_idx];
 904
 905        if (head == o->df_conflict_entry) {
 906                df_conflict_head = 1;
 907                head = NULL;
 908        }
 909
 910        if (remote == o->df_conflict_entry) {
 911                df_conflict_remote = 1;
 912                remote = NULL;
 913        }
 914
 915        /* First, if there's a #16 situation, note that to prevent #13
 916         * and #14.
 917         */
 918        if (!same(remote, head)) {
 919                for (i = 1; i < o->head_idx; i++) {
 920                        if (same(stages[i], head)) {
 921                                head_match = i;
 922                        }
 923                        if (same(stages[i], remote)) {
 924                                remote_match = i;
 925                        }
 926                }
 927        }
 928
 929        /* We start with cases where the index is allowed to match
 930         * something other than the head: #14(ALT) and #2ALT, where it
 931         * is permitted to match the result instead.
 932         */
 933        /* #14, #14ALT, #2ALT */
 934        if (remote && !df_conflict_head && head_match && !remote_match) {
 935                if (index && !same(index, remote) && !same(index, head))
 936                        return o->gently ? -1 : reject_merge(index, o);
 937                return merged_entry(remote, index, o);
 938        }
 939        /*
 940         * If we have an entry in the index cache, then we want to
 941         * make sure that it matches head.
 942         */
 943        if (index && !same(index, head))
 944                return o->gently ? -1 : reject_merge(index, o);
 945
 946        if (head) {
 947                /* #5ALT, #15 */
 948                if (same(head, remote))
 949                        return merged_entry(head, index, o);
 950                /* #13, #3ALT */
 951                if (!df_conflict_remote && remote_match && !head_match)
 952                        return merged_entry(head, index, o);
 953        }
 954
 955        /* #1 */
 956        if (!head && !remote && any_anc_missing)
 957                return 0;
 958
 959        /* Under the new "aggressive" rule, we resolve mostly trivial
 960         * cases that we historically had git-merge-one-file resolve.
 961         */
 962        if (o->aggressive) {
 963                int head_deleted = !head && !df_conflict_head;
 964                int remote_deleted = !remote && !df_conflict_remote;
 965                struct cache_entry *ce = NULL;
 966
 967                if (index)
 968                        ce = index;
 969                else if (head)
 970                        ce = head;
 971                else if (remote)
 972                        ce = remote;
 973                else {
 974                        for (i = 1; i < o->head_idx; i++) {
 975                                if (stages[i] && stages[i] != o->df_conflict_entry) {
 976                                        ce = stages[i];
 977                                        break;
 978                                }
 979                        }
 980                }
 981
 982                /*
 983                 * Deleted in both.
 984                 * Deleted in one and unchanged in the other.
 985                 */
 986                if ((head_deleted && remote_deleted) ||
 987                    (head_deleted && remote && remote_match) ||
 988                    (remote_deleted && head && head_match)) {
 989                        if (index)
 990                                return deleted_entry(index, index, o);
 991                        if (ce && !head_deleted) {
 992                                if (verify_absent(ce, "removed", o))
 993                                        return -1;
 994                        }
 995                        return 0;
 996                }
 997                /*
 998                 * Added in both, identically.
 999                 */
1000                if (no_anc_exists && head && remote && same(head, remote))
1001                        return merged_entry(head, index, o);
1002
1003        }
1004
1005        /* Below are "no merge" cases, which require that the index be
1006         * up-to-date to avoid the files getting overwritten with
1007         * conflict resolution files.
1008         */
1009        if (index) {
1010                if (verify_uptodate(index, o))
1011                        return -1;
1012        }
1013
1014        o->nontrivial_merge = 1;
1015
1016        /* #2, #3, #4, #6, #7, #9, #10, #11. */
1017        count = 0;
1018        if (!head_match || !remote_match) {
1019                for (i = 1; i < o->head_idx; i++) {
1020                        if (stages[i] && stages[i] != o->df_conflict_entry) {
1021                                keep_entry(stages[i], o);
1022                                count++;
1023                                break;
1024                        }
1025                }
1026        }
1027#if DBRT_DEBUG
1028        else {
1029                fprintf(stderr, "read-tree: warning #16 detected\n");
1030                show_stage_entry(stderr, "head   ", stages[head_match]);
1031                show_stage_entry(stderr, "remote ", stages[remote_match]);
1032        }
1033#endif
1034        if (head) { count += keep_entry(head, o); }
1035        if (remote) { count += keep_entry(remote, o); }
1036        return count;
1037}
1038
1039/*
1040 * Two-way merge.
1041 *
1042 * The rule is to "carry forward" what is in the index without losing
1043 * information across a "fast forward", favoring a successful merge
1044 * over a merge failure when it makes sense.  For details of the
1045 * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
1046 *
1047 */
1048int twoway_merge(struct cache_entry **src, struct unpack_trees_options *o)
1049{
1050        struct cache_entry *current = src[0];
1051        struct cache_entry *oldtree = src[1];
1052        struct cache_entry *newtree = src[2];
1053
1054        if (o->merge_size != 2)
1055                return error("Cannot do a twoway merge of %d trees",
1056                             o->merge_size);
1057
1058        if (oldtree == o->df_conflict_entry)
1059                oldtree = NULL;
1060        if (newtree == o->df_conflict_entry)
1061                newtree = NULL;
1062
1063        if (current) {
1064                if ((!oldtree && !newtree) || /* 4 and 5 */
1065                    (!oldtree && newtree &&
1066                     same(current, newtree)) || /* 6 and 7 */
1067                    (oldtree && newtree &&
1068                     same(oldtree, newtree)) || /* 14 and 15 */
1069                    (oldtree && newtree &&
1070                     !same(oldtree, newtree) && /* 18 and 19 */
1071                     same(current, newtree))) {
1072                        return keep_entry(current, o);
1073                }
1074                else if (oldtree && !newtree && same(current, oldtree)) {
1075                        /* 10 or 11 */
1076                        return deleted_entry(oldtree, current, o);
1077                }
1078                else if (oldtree && newtree &&
1079                         same(current, oldtree) && !same(current, newtree)) {
1080                        /* 20 or 21 */
1081                        return merged_entry(newtree, current, o);
1082                }
1083                else {
1084                        /* all other failures */
1085                        if (oldtree)
1086                                return o->gently ? -1 : reject_merge(oldtree, o);
1087                        if (current)
1088                                return o->gently ? -1 : reject_merge(current, o);
1089                        if (newtree)
1090                                return o->gently ? -1 : reject_merge(newtree, o);
1091                        return -1;
1092                }
1093        }
1094        else if (newtree) {
1095                if (oldtree && !o->initial_checkout) {
1096                        /*
1097                         * deletion of the path was staged;
1098                         */
1099                        if (same(oldtree, newtree))
1100                                return 1;
1101                        return reject_merge(oldtree, o);
1102                }
1103                return merged_entry(newtree, current, o);
1104        }
1105        return deleted_entry(oldtree, current, o);
1106}
1107
1108/*
1109 * Bind merge.
1110 *
1111 * Keep the index entries at stage0, collapse stage1 but make sure
1112 * stage0 does not have anything there.
1113 */
1114int bind_merge(struct cache_entry **src,
1115                struct unpack_trees_options *o)
1116{
1117        struct cache_entry *old = src[0];
1118        struct cache_entry *a = src[1];
1119
1120        if (o->merge_size != 1)
1121                return error("Cannot do a bind merge of %d trees\n",
1122                             o->merge_size);
1123        if (a && old)
1124                return o->gently ? -1 :
1125                        error(ERRORMSG(o, bind_overlap), a->name, old->name);
1126        if (!a)
1127                return keep_entry(old, o);
1128        else
1129                return merged_entry(a, NULL, o);
1130}
1131
1132/*
1133 * One-way merge.
1134 *
1135 * The rule is:
1136 * - take the stat information from stage0, take the data from stage1
1137 */
1138int oneway_merge(struct cache_entry **src, struct unpack_trees_options *o)
1139{
1140        struct cache_entry *old = src[0];
1141        struct cache_entry *a = src[1];
1142
1143        if (o->merge_size != 1)
1144                return error("Cannot do a oneway merge of %d trees",
1145                             o->merge_size);
1146
1147        if (!a || a == o->df_conflict_entry)
1148                return deleted_entry(old, old, o);
1149
1150        if (old && same(old, a)) {
1151                int update = 0;
1152                if (o->reset && !ce_uptodate(old) && !ce_skip_worktree(old)) {
1153                        struct stat st;
1154                        if (lstat(old->name, &st) ||
1155                            ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID))
1156                                update |= CE_UPDATE;
1157                }
1158                add_entry(o, old, update, 0);
1159                return 0;
1160        }
1161        return merged_entry(a, old, o);
1162}