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