8eb4b7095c5aab494228eb8b538b3c0b94e8b1ae
   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_1(struct cache_entry *ce,
 456                                   struct unpack_trees_options *o,
 457                                   const char *error_msg)
 458{
 459        struct stat st;
 460
 461        if (o->index_only || (!ce_skip_worktree(ce) && (o->reset || ce_uptodate(ce))))
 462                return 0;
 463
 464        if (!lstat(ce->name, &st)) {
 465                unsigned changed = ie_match_stat(o->src_index, ce, &st, CE_MATCH_IGNORE_VALID);
 466                if (!changed)
 467                        return 0;
 468                /*
 469                 * NEEDSWORK: the current default policy is to allow
 470                 * submodule to be out of sync wrt the supermodule
 471                 * index.  This needs to be tightened later for
 472                 * submodules that are marked to be automatically
 473                 * checked out.
 474                 */
 475                if (S_ISGITLINK(ce->ce_mode))
 476                        return 0;
 477                errno = 0;
 478        }
 479        if (errno == ENOENT)
 480                return 0;
 481        return o->gently ? -1 :
 482                error(error_msg, ce->name);
 483}
 484
 485static int verify_uptodate(struct cache_entry *ce,
 486                           struct unpack_trees_options *o)
 487{
 488        return verify_uptodate_1(ce, o, ERRORMSG(o, not_uptodate_file));
 489}
 490
 491static void invalidate_ce_path(struct cache_entry *ce, struct unpack_trees_options *o)
 492{
 493        if (ce)
 494                cache_tree_invalidate_path(o->src_index->cache_tree, ce->name);
 495}
 496
 497/*
 498 * Check that checking out ce->sha1 in subdir ce->name is not
 499 * going to overwrite any working files.
 500 *
 501 * Currently, git does not checkout subprojects during a superproject
 502 * checkout, so it is not going to overwrite anything.
 503 */
 504static int verify_clean_submodule(struct cache_entry *ce, const char *action,
 505                                      struct unpack_trees_options *o)
 506{
 507        return 0;
 508}
 509
 510static int verify_clean_subdirectory(struct cache_entry *ce, const char *action,
 511                                      struct unpack_trees_options *o)
 512{
 513        /*
 514         * we are about to extract "ce->name"; we would not want to lose
 515         * anything in the existing directory there.
 516         */
 517        int namelen;
 518        int i;
 519        struct dir_struct d;
 520        char *pathbuf;
 521        int cnt = 0;
 522        unsigned char sha1[20];
 523
 524        if (S_ISGITLINK(ce->ce_mode) &&
 525            resolve_gitlink_ref(ce->name, "HEAD", sha1) == 0) {
 526                /* If we are not going to update the submodule, then
 527                 * we don't care.
 528                 */
 529                if (!hashcmp(sha1, ce->sha1))
 530                        return 0;
 531                return verify_clean_submodule(ce, action, o);
 532        }
 533
 534        /*
 535         * First let's make sure we do not have a local modification
 536         * in that directory.
 537         */
 538        namelen = strlen(ce->name);
 539        for (i = o->pos; i < o->src_index->cache_nr; i++) {
 540                struct cache_entry *ce2 = o->src_index->cache[i];
 541                int len = ce_namelen(ce2);
 542                if (len < namelen ||
 543                    strncmp(ce->name, ce2->name, namelen) ||
 544                    ce2->name[namelen] != '/')
 545                        break;
 546                /*
 547                 * ce2->name is an entry in the subdirectory.
 548                 */
 549                if (!ce_stage(ce2)) {
 550                        if (verify_uptodate(ce2, o))
 551                                return -1;
 552                        add_entry(o, ce2, CE_REMOVE, 0);
 553                }
 554                cnt++;
 555        }
 556
 557        /*
 558         * Then we need to make sure that we do not lose a locally
 559         * present file that is not ignored.
 560         */
 561        pathbuf = xmalloc(namelen + 2);
 562        memcpy(pathbuf, ce->name, namelen);
 563        strcpy(pathbuf+namelen, "/");
 564
 565        memset(&d, 0, sizeof(d));
 566        if (o->dir)
 567                d.exclude_per_dir = o->dir->exclude_per_dir;
 568        i = read_directory(&d, pathbuf, namelen+1, NULL);
 569        if (i)
 570                return o->gently ? -1 :
 571                        error(ERRORMSG(o, not_uptodate_dir), ce->name);
 572        free(pathbuf);
 573        return cnt;
 574}
 575
 576/*
 577 * This gets called when there was no index entry for the tree entry 'dst',
 578 * but we found a file in the working tree that 'lstat()' said was fine,
 579 * and we're on a case-insensitive filesystem.
 580 *
 581 * See if we can find a case-insensitive match in the index that also
 582 * matches the stat information, and assume it's that other file!
 583 */
 584static int icase_exists(struct unpack_trees_options *o, struct cache_entry *dst, struct stat *st)
 585{
 586        struct cache_entry *src;
 587
 588        src = index_name_exists(o->src_index, dst->name, ce_namelen(dst), 1);
 589        return src && !ie_match_stat(o->src_index, src, st, CE_MATCH_IGNORE_VALID);
 590}
 591
 592/*
 593 * We do not want to remove or overwrite a working tree file that
 594 * is not tracked, unless it is ignored.
 595 */
 596static int verify_absent_1(struct cache_entry *ce, const char *action,
 597                                 struct unpack_trees_options *o,
 598                                 const char *error_msg)
 599{
 600        struct stat st;
 601
 602        if (o->index_only || o->reset || !o->update)
 603                return 0;
 604
 605        if (has_symlink_or_noent_leading_path(ce->name, ce_namelen(ce)))
 606                return 0;
 607
 608        if (!lstat(ce->name, &st)) {
 609                int ret;
 610                int dtype = ce_to_dtype(ce);
 611                struct cache_entry *result;
 612
 613                /*
 614                 * It may be that the 'lstat()' succeeded even though
 615                 * target 'ce' was absent, because there is an old
 616                 * entry that is different only in case..
 617                 *
 618                 * Ignore that lstat() if it matches.
 619                 */
 620                if (ignore_case && icase_exists(o, ce, &st))
 621                        return 0;
 622
 623                if (o->dir && excluded(o->dir, ce->name, &dtype))
 624                        /*
 625                         * ce->name is explicitly excluded, so it is Ok to
 626                         * overwrite it.
 627                         */
 628                        return 0;
 629                if (S_ISDIR(st.st_mode)) {
 630                        /*
 631                         * We are checking out path "foo" and
 632                         * found "foo/." in the working tree.
 633                         * This is tricky -- if we have modified
 634                         * files that are in "foo/" we would lose
 635                         * it.
 636                         */
 637                        ret = verify_clean_subdirectory(ce, action, o);
 638                        if (ret < 0)
 639                                return ret;
 640
 641                        /*
 642                         * If this removed entries from the index,
 643                         * what that means is:
 644                         *
 645                         * (1) the caller unpack_callback() saw path/foo
 646                         * in the index, and it has not removed it because
 647                         * it thinks it is handling 'path' as blob with
 648                         * D/F conflict;
 649                         * (2) we will return "ok, we placed a merged entry
 650                         * in the index" which would cause o->pos to be
 651                         * incremented by one;
 652                         * (3) however, original o->pos now has 'path/foo'
 653                         * marked with "to be removed".
 654                         *
 655                         * We need to increment it by the number of
 656                         * deleted entries here.
 657                         */
 658                        o->pos += ret;
 659                        return 0;
 660                }
 661
 662                /*
 663                 * The previous round may already have decided to
 664                 * delete this path, which is in a subdirectory that
 665                 * is being replaced with a blob.
 666                 */
 667                result = index_name_exists(&o->result, ce->name, ce_namelen(ce), 0);
 668                if (result) {
 669                        if (result->ce_flags & CE_REMOVE)
 670                                return 0;
 671                }
 672
 673                return o->gently ? -1 :
 674                        error(ERRORMSG(o, would_lose_untracked), ce->name, action);
 675        }
 676        return 0;
 677}
 678static int verify_absent(struct cache_entry *ce, const char *action,
 679                         struct unpack_trees_options *o)
 680{
 681        return verify_absent_1(ce, action, o, ERRORMSG(o, would_lose_untracked));
 682}
 683
 684static int merged_entry(struct cache_entry *merge, struct cache_entry *old,
 685                struct unpack_trees_options *o)
 686{
 687        int update = CE_UPDATE;
 688
 689        if (old) {
 690                /*
 691                 * See if we can re-use the old CE directly?
 692                 * That way we get the uptodate stat info.
 693                 *
 694                 * This also removes the UPDATE flag on a match; otherwise
 695                 * we will end up overwriting local changes in the work tree.
 696                 */
 697                if (same(old, merge)) {
 698                        copy_cache_entry(merge, old);
 699                        update = 0;
 700                } else {
 701                        if (verify_uptodate(old, o))
 702                                return -1;
 703                        if (ce_skip_worktree(old))
 704                                update |= CE_SKIP_WORKTREE;
 705                        invalidate_ce_path(old, o);
 706                }
 707        }
 708        else {
 709                if (verify_absent(merge, "overwritten", o))
 710                        return -1;
 711                invalidate_ce_path(merge, o);
 712        }
 713
 714        add_entry(o, merge, update, CE_STAGEMASK);
 715        return 1;
 716}
 717
 718static int deleted_entry(struct cache_entry *ce, struct cache_entry *old,
 719                struct unpack_trees_options *o)
 720{
 721        /* Did it exist in the index? */
 722        if (!old) {
 723                if (verify_absent(ce, "removed", o))
 724                        return -1;
 725                return 0;
 726        }
 727        if (verify_uptodate(old, o))
 728                return -1;
 729        add_entry(o, ce, CE_REMOVE, 0);
 730        invalidate_ce_path(ce, o);
 731        return 1;
 732}
 733
 734static int keep_entry(struct cache_entry *ce, struct unpack_trees_options *o)
 735{
 736        add_entry(o, ce, 0, 0);
 737        return 1;
 738}
 739
 740#if DBRT_DEBUG
 741static void show_stage_entry(FILE *o,
 742                             const char *label, const struct cache_entry *ce)
 743{
 744        if (!ce)
 745                fprintf(o, "%s (missing)\n", label);
 746        else
 747                fprintf(o, "%s%06o %s %d\t%s\n",
 748                        label,
 749                        ce->ce_mode,
 750                        sha1_to_hex(ce->sha1),
 751                        ce_stage(ce),
 752                        ce->name);
 753}
 754#endif
 755
 756int threeway_merge(struct cache_entry **stages, struct unpack_trees_options *o)
 757{
 758        struct cache_entry *index;
 759        struct cache_entry *head;
 760        struct cache_entry *remote = stages[o->head_idx + 1];
 761        int count;
 762        int head_match = 0;
 763        int remote_match = 0;
 764
 765        int df_conflict_head = 0;
 766        int df_conflict_remote = 0;
 767
 768        int any_anc_missing = 0;
 769        int no_anc_exists = 1;
 770        int i;
 771
 772        for (i = 1; i < o->head_idx; i++) {
 773                if (!stages[i] || stages[i] == o->df_conflict_entry)
 774                        any_anc_missing = 1;
 775                else
 776                        no_anc_exists = 0;
 777        }
 778
 779        index = stages[0];
 780        head = stages[o->head_idx];
 781
 782        if (head == o->df_conflict_entry) {
 783                df_conflict_head = 1;
 784                head = NULL;
 785        }
 786
 787        if (remote == o->df_conflict_entry) {
 788                df_conflict_remote = 1;
 789                remote = NULL;
 790        }
 791
 792        /* First, if there's a #16 situation, note that to prevent #13
 793         * and #14.
 794         */
 795        if (!same(remote, head)) {
 796                for (i = 1; i < o->head_idx; i++) {
 797                        if (same(stages[i], head)) {
 798                                head_match = i;
 799                        }
 800                        if (same(stages[i], remote)) {
 801                                remote_match = i;
 802                        }
 803                }
 804        }
 805
 806        /* We start with cases where the index is allowed to match
 807         * something other than the head: #14(ALT) and #2ALT, where it
 808         * is permitted to match the result instead.
 809         */
 810        /* #14, #14ALT, #2ALT */
 811        if (remote && !df_conflict_head && head_match && !remote_match) {
 812                if (index && !same(index, remote) && !same(index, head))
 813                        return o->gently ? -1 : reject_merge(index, o);
 814                return merged_entry(remote, index, o);
 815        }
 816        /*
 817         * If we have an entry in the index cache, then we want to
 818         * make sure that it matches head.
 819         */
 820        if (index && !same(index, head))
 821                return o->gently ? -1 : reject_merge(index, o);
 822
 823        if (head) {
 824                /* #5ALT, #15 */
 825                if (same(head, remote))
 826                        return merged_entry(head, index, o);
 827                /* #13, #3ALT */
 828                if (!df_conflict_remote && remote_match && !head_match)
 829                        return merged_entry(head, index, o);
 830        }
 831
 832        /* #1 */
 833        if (!head && !remote && any_anc_missing)
 834                return 0;
 835
 836        /* Under the new "aggressive" rule, we resolve mostly trivial
 837         * cases that we historically had git-merge-one-file resolve.
 838         */
 839        if (o->aggressive) {
 840                int head_deleted = !head && !df_conflict_head;
 841                int remote_deleted = !remote && !df_conflict_remote;
 842                struct cache_entry *ce = NULL;
 843
 844                if (index)
 845                        ce = index;
 846                else if (head)
 847                        ce = head;
 848                else if (remote)
 849                        ce = remote;
 850                else {
 851                        for (i = 1; i < o->head_idx; i++) {
 852                                if (stages[i] && stages[i] != o->df_conflict_entry) {
 853                                        ce = stages[i];
 854                                        break;
 855                                }
 856                        }
 857                }
 858
 859                /*
 860                 * Deleted in both.
 861                 * Deleted in one and unchanged in the other.
 862                 */
 863                if ((head_deleted && remote_deleted) ||
 864                    (head_deleted && remote && remote_match) ||
 865                    (remote_deleted && head && head_match)) {
 866                        if (index)
 867                                return deleted_entry(index, index, o);
 868                        if (ce && !head_deleted) {
 869                                if (verify_absent(ce, "removed", o))
 870                                        return -1;
 871                        }
 872                        return 0;
 873                }
 874                /*
 875                 * Added in both, identically.
 876                 */
 877                if (no_anc_exists && head && remote && same(head, remote))
 878                        return merged_entry(head, index, o);
 879
 880        }
 881
 882        /* Below are "no merge" cases, which require that the index be
 883         * up-to-date to avoid the files getting overwritten with
 884         * conflict resolution files.
 885         */
 886        if (index) {
 887                if (verify_uptodate(index, o))
 888                        return -1;
 889        }
 890
 891        o->nontrivial_merge = 1;
 892
 893        /* #2, #3, #4, #6, #7, #9, #10, #11. */
 894        count = 0;
 895        if (!head_match || !remote_match) {
 896                for (i = 1; i < o->head_idx; i++) {
 897                        if (stages[i] && stages[i] != o->df_conflict_entry) {
 898                                keep_entry(stages[i], o);
 899                                count++;
 900                                break;
 901                        }
 902                }
 903        }
 904#if DBRT_DEBUG
 905        else {
 906                fprintf(stderr, "read-tree: warning #16 detected\n");
 907                show_stage_entry(stderr, "head   ", stages[head_match]);
 908                show_stage_entry(stderr, "remote ", stages[remote_match]);
 909        }
 910#endif
 911        if (head) { count += keep_entry(head, o); }
 912        if (remote) { count += keep_entry(remote, o); }
 913        return count;
 914}
 915
 916/*
 917 * Two-way merge.
 918 *
 919 * The rule is to "carry forward" what is in the index without losing
 920 * information across a "fast forward", favoring a successful merge
 921 * over a merge failure when it makes sense.  For details of the
 922 * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
 923 *
 924 */
 925int twoway_merge(struct cache_entry **src, struct unpack_trees_options *o)
 926{
 927        struct cache_entry *current = src[0];
 928        struct cache_entry *oldtree = src[1];
 929        struct cache_entry *newtree = src[2];
 930
 931        if (o->merge_size != 2)
 932                return error("Cannot do a twoway merge of %d trees",
 933                             o->merge_size);
 934
 935        if (oldtree == o->df_conflict_entry)
 936                oldtree = NULL;
 937        if (newtree == o->df_conflict_entry)
 938                newtree = NULL;
 939
 940        if (current) {
 941                if ((!oldtree && !newtree) || /* 4 and 5 */
 942                    (!oldtree && newtree &&
 943                     same(current, newtree)) || /* 6 and 7 */
 944                    (oldtree && newtree &&
 945                     same(oldtree, newtree)) || /* 14 and 15 */
 946                    (oldtree && newtree &&
 947                     !same(oldtree, newtree) && /* 18 and 19 */
 948                     same(current, newtree))) {
 949                        return keep_entry(current, o);
 950                }
 951                else if (oldtree && !newtree && same(current, oldtree)) {
 952                        /* 10 or 11 */
 953                        return deleted_entry(oldtree, current, o);
 954                }
 955                else if (oldtree && newtree &&
 956                         same(current, oldtree) && !same(current, newtree)) {
 957                        /* 20 or 21 */
 958                        return merged_entry(newtree, current, o);
 959                }
 960                else {
 961                        /* all other failures */
 962                        if (oldtree)
 963                                return o->gently ? -1 : reject_merge(oldtree, o);
 964                        if (current)
 965                                return o->gently ? -1 : reject_merge(current, o);
 966                        if (newtree)
 967                                return o->gently ? -1 : reject_merge(newtree, o);
 968                        return -1;
 969                }
 970        }
 971        else if (newtree) {
 972                if (oldtree && !o->initial_checkout) {
 973                        /*
 974                         * deletion of the path was staged;
 975                         */
 976                        if (same(oldtree, newtree))
 977                                return 1;
 978                        return reject_merge(oldtree, o);
 979                }
 980                return merged_entry(newtree, current, o);
 981        }
 982        return deleted_entry(oldtree, current, o);
 983}
 984
 985/*
 986 * Bind merge.
 987 *
 988 * Keep the index entries at stage0, collapse stage1 but make sure
 989 * stage0 does not have anything there.
 990 */
 991int bind_merge(struct cache_entry **src,
 992                struct unpack_trees_options *o)
 993{
 994        struct cache_entry *old = src[0];
 995        struct cache_entry *a = src[1];
 996
 997        if (o->merge_size != 1)
 998                return error("Cannot do a bind merge of %d trees\n",
 999                             o->merge_size);
1000        if (a && old)
1001                return o->gently ? -1 :
1002                        error(ERRORMSG(o, bind_overlap), a->name, old->name);
1003        if (!a)
1004                return keep_entry(old, o);
1005        else
1006                return merged_entry(a, NULL, o);
1007}
1008
1009/*
1010 * One-way merge.
1011 *
1012 * The rule is:
1013 * - take the stat information from stage0, take the data from stage1
1014 */
1015int oneway_merge(struct cache_entry **src, struct unpack_trees_options *o)
1016{
1017        struct cache_entry *old = src[0];
1018        struct cache_entry *a = src[1];
1019
1020        if (o->merge_size != 1)
1021                return error("Cannot do a oneway merge of %d trees",
1022                             o->merge_size);
1023
1024        if (!a || a == o->df_conflict_entry)
1025                return deleted_entry(old, old, o);
1026
1027        if (old && same(old, a)) {
1028                int update = 0;
1029                if (o->reset && !ce_uptodate(old) && !ce_skip_worktree(old)) {
1030                        struct stat st;
1031                        if (lstat(old->name, &st) ||
1032                            ie_match_stat(o->src_index, old, &st, CE_MATCH_IGNORE_VALID))
1033                                update |= CE_UPDATE;
1034                }
1035                add_entry(o, old, update, 0);
1036                return 0;
1037        }
1038        return merged_entry(a, old, o);
1039}