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