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