builtin-read-tree.con commit Merge branch 'jc/lt-tree-n-cache-tree' into next (52bc0e2)
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 */
   6#define DBRT_DEBUG 1
   7
   8#include "cache.h"
   9
  10#include "object.h"
  11#include "tree.h"
  12#include "cache-tree.h"
  13#include "tree-walk.h"
  14#include <sys/time.h>
  15#include <signal.h>
  16#include "builtin.h"
  17
  18static int reset = 0;
  19static int merge = 0;
  20static int update = 0;
  21static int index_only = 0;
  22static int nontrivial_merge = 0;
  23static int trivial_merges_only = 0;
  24static int aggressive = 0;
  25static int verbose_update = 0;
  26static volatile int progress_update = 0;
  27static const char *prefix = NULL;
  28
  29static int head_idx = -1;
  30static int merge_size = 0;
  31
  32static struct object_list *trees = NULL;
  33
  34static struct cache_entry df_conflict_entry = { 
  35};
  36
  37static struct tree_entry_list df_conflict_list = {
  38        .name = NULL,
  39        .next = &df_conflict_list
  40};
  41
  42typedef int (*merge_fn_t)(struct cache_entry **src);
  43
  44static int entcmp(const char *name1, int dir1, const char *name2, int dir2)
  45{
  46        int len1 = strlen(name1);
  47        int len2 = strlen(name2);
  48        int len = len1 < len2 ? len1 : len2;
  49        int ret = memcmp(name1, name2, len);
  50        unsigned char c1, c2;
  51        if (ret)
  52                return ret;
  53        c1 = name1[len];
  54        c2 = name2[len];
  55        if (!c1 && dir1)
  56                c1 = '/';
  57        if (!c2 && dir2)
  58                c2 = '/';
  59        ret = (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
  60        if (c1 && c2 && !ret)
  61                ret = len1 - len2;
  62        return ret;
  63}
  64
  65static int unpack_trees_rec(struct tree_entry_list **posns, int len,
  66                            const char *base, merge_fn_t fn, int *indpos)
  67{
  68        int baselen = strlen(base);
  69        int src_size = len + 1;
  70        do {
  71                int i;
  72                const char *first;
  73                int firstdir = 0;
  74                int pathlen;
  75                unsigned ce_size;
  76                struct tree_entry_list **subposns;
  77                struct cache_entry **src;
  78                int any_files = 0;
  79                int any_dirs = 0;
  80                char *cache_name;
  81                int ce_stage;
  82
  83                /* Find the first name in the input. */
  84
  85                first = NULL;
  86                cache_name = NULL;
  87
  88                /* Check the cache */
  89                if (merge && *indpos < active_nr) {
  90                        /* This is a bit tricky: */
  91                        /* If the index has a subdirectory (with
  92                         * contents) as the first name, it'll get a
  93                         * filename like "foo/bar". But that's after
  94                         * "foo", so the entry in trees will get
  95                         * handled first, at which point we'll go into
  96                         * "foo", and deal with "bar" from the index,
  97                         * because the base will be "foo/". The only
  98                         * way we can actually have "foo/bar" first of
  99                         * all the things is if the trees don't
 100                         * contain "foo" at all, in which case we'll
 101                         * handle "foo/bar" without going into the
 102                         * directory, but that's fine (and will return
 103                         * an error anyway, with the added unknown
 104                         * file case.
 105                         */
 106
 107                        cache_name = active_cache[*indpos]->name;
 108                        if (strlen(cache_name) > baselen &&
 109                            !memcmp(cache_name, base, baselen)) {
 110                                cache_name += baselen;
 111                                first = cache_name;
 112                        } else {
 113                                cache_name = NULL;
 114                        }
 115                }
 116
 117#if DBRT_DEBUG > 1
 118                if (first)
 119                        printf("index %s\n", first);
 120#endif
 121                for (i = 0; i < len; i++) {
 122                        if (!posns[i] || posns[i] == &df_conflict_list)
 123                                continue;
 124#if DBRT_DEBUG > 1
 125                        printf("%d %s\n", i + 1, posns[i]->name);
 126#endif
 127                        if (!first || entcmp(first, firstdir,
 128                                             posns[i]->name, 
 129                                             posns[i]->directory) > 0) {
 130                                first = posns[i]->name;
 131                                firstdir = posns[i]->directory;
 132                        }
 133                }
 134                /* No name means we're done */
 135                if (!first)
 136                        return 0;
 137
 138                pathlen = strlen(first);
 139                ce_size = cache_entry_size(baselen + pathlen);
 140
 141                src = xcalloc(src_size, sizeof(struct cache_entry *));
 142
 143                subposns = xcalloc(len, sizeof(struct tree_list_entry *));
 144
 145                if (cache_name && !strcmp(cache_name, first)) {
 146                        any_files = 1;
 147                        src[0] = active_cache[*indpos];
 148                        remove_cache_entry_at(*indpos);
 149                }
 150
 151                for (i = 0; i < len; i++) {
 152                        struct cache_entry *ce;
 153
 154                        if (!posns[i] ||
 155                            (posns[i] != &df_conflict_list &&
 156                             strcmp(first, posns[i]->name))) {
 157                                continue;
 158                        }
 159
 160                        if (posns[i] == &df_conflict_list) {
 161                                src[i + merge] = &df_conflict_entry;
 162                                continue;
 163                        }
 164
 165                        if (posns[i]->directory) {
 166                                struct tree *tree = lookup_tree(posns[i]->sha1);
 167                                any_dirs = 1;
 168                                parse_tree(tree);
 169                                subposns[i] = create_tree_entry_list(tree);
 170                                posns[i] = posns[i]->next;
 171                                src[i + merge] = &df_conflict_entry;
 172                                continue;
 173                        }
 174
 175                        if (!merge)
 176                                ce_stage = 0;
 177                        else if (i + 1 < head_idx)
 178                                ce_stage = 1;
 179                        else if (i + 1 > head_idx)
 180                                ce_stage = 3;
 181                        else
 182                                ce_stage = 2;
 183
 184                        ce = xcalloc(1, ce_size);
 185                        ce->ce_mode = create_ce_mode(posns[i]->mode);
 186                        ce->ce_flags = create_ce_flags(baselen + pathlen,
 187                                                       ce_stage);
 188                        memcpy(ce->name, base, baselen);
 189                        memcpy(ce->name + baselen, first, pathlen + 1);
 190
 191                        any_files = 1;
 192
 193                        memcpy(ce->sha1, posns[i]->sha1, 20);
 194                        src[i + merge] = ce;
 195                        subposns[i] = &df_conflict_list;
 196                        posns[i] = posns[i]->next;
 197                }
 198                if (any_files) {
 199                        if (merge) {
 200                                int ret;
 201
 202#if DBRT_DEBUG > 1
 203                                printf("%s:\n", first);
 204                                for (i = 0; i < src_size; i++) {
 205                                        printf(" %d ", i);
 206                                        if (src[i])
 207                                                printf("%s\n", sha1_to_hex(src[i]->sha1));
 208                                        else
 209                                                printf("\n");
 210                                }
 211#endif
 212                                ret = fn(src);
 213                                
 214#if DBRT_DEBUG > 1
 215                                printf("Added %d entries\n", ret);
 216#endif
 217                                *indpos += ret;
 218                        } else {
 219                                for (i = 0; i < src_size; i++) {
 220                                        if (src[i]) {
 221                                                add_cache_entry(src[i], ADD_CACHE_OK_TO_ADD|ADD_CACHE_SKIP_DFCHECK);
 222                                        }
 223                                }
 224                        }
 225                }
 226                if (any_dirs) {
 227                        char *newbase = xmalloc(baselen + 2 + pathlen);
 228                        memcpy(newbase, base, baselen);
 229                        memcpy(newbase + baselen, first, pathlen);
 230                        newbase[baselen + pathlen] = '/';
 231                        newbase[baselen + pathlen + 1] = '\0';
 232                        if (unpack_trees_rec(subposns, len, newbase, fn,
 233                                             indpos))
 234                                return -1;
 235                        free(newbase);
 236                }
 237                free(subposns);
 238                free(src);
 239        } while (1);
 240}
 241
 242static void reject_merge(struct cache_entry *ce)
 243{
 244        die("Entry '%s' would be overwritten by merge. Cannot merge.", 
 245            ce->name);
 246}
 247
 248/* Unlink the last component and attempt to remove leading
 249 * directories, in case this unlink is the removal of the
 250 * last entry in the directory -- empty directories are removed.
 251 */
 252static void unlink_entry(char *name)
 253{
 254        char *cp, *prev;
 255
 256        if (unlink(name))
 257                return;
 258        prev = NULL;
 259        while (1) {
 260                int status;
 261                cp = strrchr(name, '/');
 262                if (prev)
 263                        *prev = '/';
 264                if (!cp)
 265                        break;
 266
 267                *cp = 0;
 268                status = rmdir(name);
 269                if (status) {
 270                        *cp = '/';
 271                        break;
 272                }
 273                prev = cp;
 274        }
 275}
 276
 277static void progress_interval(int signum)
 278{
 279        progress_update = 1;
 280}
 281
 282static void setup_progress_signal(void)
 283{
 284        struct sigaction sa;
 285        struct itimerval v;
 286
 287        memset(&sa, 0, sizeof(sa));
 288        sa.sa_handler = progress_interval;
 289        sigemptyset(&sa.sa_mask);
 290        sa.sa_flags = SA_RESTART;
 291        sigaction(SIGALRM, &sa, NULL);
 292
 293        v.it_interval.tv_sec = 1;
 294        v.it_interval.tv_usec = 0;
 295        v.it_value = v.it_interval;
 296        setitimer(ITIMER_REAL, &v, NULL);
 297}
 298
 299static void check_updates(struct cache_entry **src, int nr)
 300{
 301        static struct checkout state = {
 302                .base_dir = "",
 303                .force = 1,
 304                .quiet = 1,
 305                .refresh_cache = 1,
 306        };
 307        unsigned short mask = htons(CE_UPDATE);
 308        unsigned last_percent = 200, cnt = 0, total = 0;
 309
 310        if (update && verbose_update) {
 311                for (total = cnt = 0; cnt < nr; cnt++) {
 312                        struct cache_entry *ce = src[cnt];
 313                        if (!ce->ce_mode || ce->ce_flags & mask)
 314                                total++;
 315                }
 316
 317                /* Don't bother doing this for very small updates */
 318                if (total < 250)
 319                        total = 0;
 320
 321                if (total) {
 322                        fprintf(stderr, "Checking files out...\n");
 323                        setup_progress_signal();
 324                        progress_update = 1;
 325                }
 326                cnt = 0;
 327        }
 328
 329        while (nr--) {
 330                struct cache_entry *ce = *src++;
 331
 332                if (total) {
 333                        if (!ce->ce_mode || ce->ce_flags & mask) {
 334                                unsigned percent;
 335                                cnt++;
 336                                percent = (cnt * 100) / total;
 337                                if (percent != last_percent ||
 338                                    progress_update) {
 339                                        fprintf(stderr, "%4u%% (%u/%u) done\r",
 340                                                percent, cnt, total);
 341                                        last_percent = percent;
 342                                }
 343                        }
 344                }
 345                if (!ce->ce_mode) {
 346                        if (update)
 347                                unlink_entry(ce->name);
 348                        continue;
 349                }
 350                if (ce->ce_flags & mask) {
 351                        ce->ce_flags &= ~mask;
 352                        if (update)
 353                                checkout_entry(ce, &state, NULL);
 354                }
 355        }
 356        if (total) {
 357                signal(SIGALRM, SIG_IGN);
 358                fputc('\n', stderr);
 359        }
 360}
 361
 362static int unpack_trees(merge_fn_t fn)
 363{
 364        int indpos = 0;
 365        unsigned len = object_list_length(trees);
 366        struct tree_entry_list **posns;
 367        int i;
 368        struct object_list *posn = trees;
 369        merge_size = len;
 370
 371        if (len) {
 372                posns = xmalloc(len * sizeof(struct tree_entry_list *));
 373                for (i = 0; i < len; i++) {
 374                        posns[i] = create_tree_entry_list((struct tree *) posn->item);
 375                        posn = posn->next;
 376                }
 377                if (unpack_trees_rec(posns, len, prefix ? prefix : "",
 378                                     fn, &indpos))
 379                        return -1;
 380        }
 381
 382        if (trivial_merges_only && nontrivial_merge)
 383                die("Merge requires file-level merging");
 384
 385        check_updates(active_cache, active_nr);
 386        return 0;
 387}
 388
 389static int list_tree(unsigned char *sha1)
 390{
 391        struct tree *tree = parse_tree_indirect(sha1);
 392        if (!tree)
 393                return -1;
 394        object_list_append(&tree->object, &trees);
 395        return 0;
 396}
 397
 398static int same(struct cache_entry *a, struct cache_entry *b)
 399{
 400        if (!!a != !!b)
 401                return 0;
 402        if (!a && !b)
 403                return 1;
 404        return a->ce_mode == b->ce_mode && 
 405                !memcmp(a->sha1, b->sha1, 20);
 406}
 407
 408
 409/*
 410 * When a CE gets turned into an unmerged entry, we
 411 * want it to be up-to-date
 412 */
 413static void verify_uptodate(struct cache_entry *ce)
 414{
 415        struct stat st;
 416
 417        if (index_only || reset)
 418                return;
 419
 420        if (!lstat(ce->name, &st)) {
 421                unsigned changed = ce_match_stat(ce, &st, 1);
 422                if (!changed)
 423                        return;
 424                errno = 0;
 425        }
 426        if (reset) {
 427                ce->ce_flags |= htons(CE_UPDATE);
 428                return;
 429        }
 430        if (errno == ENOENT)
 431                return;
 432        die("Entry '%s' not uptodate. Cannot merge.", ce->name);
 433}
 434
 435static void invalidate_ce_path(struct cache_entry *ce)
 436{
 437        if (ce)
 438                cache_tree_invalidate_path(active_cache_tree, ce->name);
 439}
 440
 441/*
 442 * We do not want to remove or overwrite a working tree file that
 443 * is not tracked.
 444 */
 445static void verify_absent(const char *path, const char *action)
 446{
 447        struct stat st;
 448
 449        if (index_only || reset || !update)
 450                return;
 451        if (!lstat(path, &st))
 452                die("Untracked working tree file '%s' "
 453                    "would be %s by merge.", path, action);
 454}
 455
 456static int merged_entry(struct cache_entry *merge, struct cache_entry *old)
 457{
 458        merge->ce_flags |= htons(CE_UPDATE);
 459        if (old) {
 460                /*
 461                 * See if we can re-use the old CE directly?
 462                 * That way we get the uptodate stat info.
 463                 *
 464                 * This also removes the UPDATE flag on
 465                 * a match.
 466                 */
 467                if (same(old, merge)) {
 468                        *merge = *old;
 469                } else {
 470                        verify_uptodate(old);
 471                        invalidate_ce_path(old);
 472                }
 473        }
 474        else {
 475                verify_absent(merge->name, "overwritten");
 476                invalidate_ce_path(merge);
 477        }
 478
 479        merge->ce_flags &= ~htons(CE_STAGEMASK);
 480        add_cache_entry(merge, ADD_CACHE_OK_TO_ADD);
 481        return 1;
 482}
 483
 484static int deleted_entry(struct cache_entry *ce, struct cache_entry *old)
 485{
 486        if (old)
 487                verify_uptodate(old);
 488        else
 489                verify_absent(ce->name, "removed");
 490        ce->ce_mode = 0;
 491        add_cache_entry(ce, ADD_CACHE_OK_TO_ADD);
 492        invalidate_ce_path(ce);
 493        return 1;
 494}
 495
 496static int keep_entry(struct cache_entry *ce)
 497{
 498        add_cache_entry(ce, ADD_CACHE_OK_TO_ADD);
 499        return 1;
 500}
 501
 502#if DBRT_DEBUG
 503static void show_stage_entry(FILE *o,
 504                             const char *label, const struct cache_entry *ce)
 505{
 506        if (!ce)
 507                fprintf(o, "%s (missing)\n", label);
 508        else
 509                fprintf(o, "%s%06o %s %d\t%s\n",
 510                        label,
 511                        ntohl(ce->ce_mode),
 512                        sha1_to_hex(ce->sha1),
 513                        ce_stage(ce),
 514                        ce->name);
 515}
 516#endif
 517
 518static int threeway_merge(struct cache_entry **stages)
 519{
 520        struct cache_entry *index;
 521        struct cache_entry *head; 
 522        struct cache_entry *remote = stages[head_idx + 1];
 523        int count;
 524        int head_match = 0;
 525        int remote_match = 0;
 526        const char *path = NULL;
 527
 528        int df_conflict_head = 0;
 529        int df_conflict_remote = 0;
 530
 531        int any_anc_missing = 0;
 532        int no_anc_exists = 1;
 533        int i;
 534
 535        for (i = 1; i < head_idx; i++) {
 536                if (!stages[i])
 537                        any_anc_missing = 1;
 538                else {
 539                        if (!path)
 540                                path = stages[i]->name;
 541                        no_anc_exists = 0;
 542                }
 543        }
 544
 545        index = stages[0];
 546        head = stages[head_idx];
 547
 548        if (head == &df_conflict_entry) {
 549                df_conflict_head = 1;
 550                head = NULL;
 551        }
 552
 553        if (remote == &df_conflict_entry) {
 554                df_conflict_remote = 1;
 555                remote = NULL;
 556        }
 557
 558        if (!path && index)
 559                path = index->name;
 560        if (!path && head)
 561                path = head->name;
 562        if (!path && remote)
 563                path = remote->name;
 564
 565        /* First, if there's a #16 situation, note that to prevent #13
 566         * and #14.
 567         */
 568        if (!same(remote, head)) {
 569                for (i = 1; i < head_idx; i++) {
 570                        if (same(stages[i], head)) {
 571                                head_match = i;
 572                        }
 573                        if (same(stages[i], remote)) {
 574                                remote_match = i;
 575                        }
 576                }
 577        }
 578
 579        /* We start with cases where the index is allowed to match
 580         * something other than the head: #14(ALT) and #2ALT, where it
 581         * is permitted to match the result instead.
 582         */
 583        /* #14, #14ALT, #2ALT */
 584        if (remote && !df_conflict_head && head_match && !remote_match) {
 585                if (index && !same(index, remote) && !same(index, head))
 586                        reject_merge(index);
 587                return merged_entry(remote, index);
 588        }
 589        /*
 590         * If we have an entry in the index cache, then we want to
 591         * make sure that it matches head.
 592         */
 593        if (index && !same(index, head)) {
 594                reject_merge(index);
 595        }
 596
 597        if (head) {
 598                /* #5ALT, #15 */
 599                if (same(head, remote))
 600                        return merged_entry(head, index);
 601                /* #13, #3ALT */
 602                if (!df_conflict_remote && remote_match && !head_match)
 603                        return merged_entry(head, index);
 604        }
 605
 606        /* #1 */
 607        if (!head && !remote && any_anc_missing)
 608                return 0;
 609
 610        /* Under the new "aggressive" rule, we resolve mostly trivial
 611         * cases that we historically had git-merge-one-file resolve.
 612         */
 613        if (aggressive) {
 614                int head_deleted = !head && !df_conflict_head;
 615                int remote_deleted = !remote && !df_conflict_remote;
 616                /*
 617                 * Deleted in both.
 618                 * Deleted in one and unchanged in the other.
 619                 */
 620                if ((head_deleted && remote_deleted) ||
 621                    (head_deleted && remote && remote_match) ||
 622                    (remote_deleted && head && head_match)) {
 623                        if (index)
 624                                return deleted_entry(index, index);
 625                        else if (path)
 626                                verify_absent(path, "removed");
 627                        return 0;
 628                }
 629                /*
 630                 * Added in both, identically.
 631                 */
 632                if (no_anc_exists && head && remote && same(head, remote))
 633                        return merged_entry(head, index);
 634
 635        }
 636
 637        /* Below are "no merge" cases, which require that the index be
 638         * up-to-date to avoid the files getting overwritten with
 639         * conflict resolution files. 
 640         */
 641        if (index) {
 642                verify_uptodate(index);
 643        }
 644        else if (path)
 645                verify_absent(path, "overwritten");
 646
 647        nontrivial_merge = 1;
 648
 649        /* #2, #3, #4, #6, #7, #9, #11. */
 650        count = 0;
 651        if (!head_match || !remote_match) {
 652                for (i = 1; i < head_idx; i++) {
 653                        if (stages[i]) {
 654                                keep_entry(stages[i]);
 655                                count++;
 656                                break;
 657                        }
 658                }
 659        }
 660#if DBRT_DEBUG
 661        else {
 662                fprintf(stderr, "read-tree: warning #16 detected\n");
 663                show_stage_entry(stderr, "head   ", stages[head_match]);
 664                show_stage_entry(stderr, "remote ", stages[remote_match]);
 665        }
 666#endif
 667        if (head) { count += keep_entry(head); }
 668        if (remote) { count += keep_entry(remote); }
 669        return count;
 670}
 671
 672/*
 673 * Two-way merge.
 674 *
 675 * The rule is to "carry forward" what is in the index without losing
 676 * information across a "fast forward", favoring a successful merge
 677 * over a merge failure when it makes sense.  For details of the
 678 * "carry forward" rule, please see <Documentation/git-read-tree.txt>.
 679 *
 680 */
 681static int twoway_merge(struct cache_entry **src)
 682{
 683        struct cache_entry *current = src[0];
 684        struct cache_entry *oldtree = src[1], *newtree = src[2];
 685
 686        if (merge_size != 2)
 687                return error("Cannot do a twoway merge of %d trees",
 688                             merge_size);
 689
 690        if (current) {
 691                if ((!oldtree && !newtree) || /* 4 and 5 */
 692                    (!oldtree && newtree &&
 693                     same(current, newtree)) || /* 6 and 7 */
 694                    (oldtree && newtree &&
 695                     same(oldtree, newtree)) || /* 14 and 15 */
 696                    (oldtree && newtree &&
 697                     !same(oldtree, newtree) && /* 18 and 19*/
 698                     same(current, newtree))) {
 699                        return keep_entry(current);
 700                }
 701                else if (oldtree && !newtree && same(current, oldtree)) {
 702                        /* 10 or 11 */
 703                        return deleted_entry(oldtree, current);
 704                }
 705                else if (oldtree && newtree &&
 706                         same(current, oldtree) && !same(current, newtree)) {
 707                        /* 20 or 21 */
 708                        return merged_entry(newtree, current);
 709                }
 710                else {
 711                        /* all other failures */
 712                        if (oldtree)
 713                                reject_merge(oldtree);
 714                        if (current)
 715                                reject_merge(current);
 716                        if (newtree)
 717                                reject_merge(newtree);
 718                        return -1;
 719                }
 720        }
 721        else if (newtree)
 722                return merged_entry(newtree, current);
 723        else
 724                return deleted_entry(oldtree, current);
 725}
 726
 727/*
 728 * Bind merge.
 729 *
 730 * Keep the index entries at stage0, collapse stage1 but make sure
 731 * stage0 does not have anything there.
 732 */
 733static int bind_merge(struct cache_entry **src)
 734{
 735        struct cache_entry *old = src[0];
 736        struct cache_entry *a = src[1];
 737
 738        if (merge_size != 1)
 739                return error("Cannot do a bind merge of %d trees\n",
 740                             merge_size);
 741        if (a && old)
 742                die("Entry '%s' overlaps.  Cannot bind.", a->name);
 743        if (!a)
 744                return keep_entry(old);
 745        else
 746                return merged_entry(a, NULL);
 747}
 748
 749/*
 750 * One-way merge.
 751 *
 752 * The rule is:
 753 * - take the stat information from stage0, take the data from stage1
 754 */
 755static int oneway_merge(struct cache_entry **src)
 756{
 757        struct cache_entry *old = src[0];
 758        struct cache_entry *a = src[1];
 759
 760        if (merge_size != 1)
 761                return error("Cannot do a oneway merge of %d trees",
 762                             merge_size);
 763
 764        if (!a) {
 765                invalidate_ce_path(old);
 766                return deleted_entry(old, old);
 767        }
 768        if (old && same(old, a)) {
 769                if (reset) {
 770                        struct stat st;
 771                        if (lstat(old->name, &st) ||
 772                            ce_match_stat(old, &st, 1))
 773                                old->ce_flags |= htons(CE_UPDATE);
 774                }
 775                return keep_entry(old);
 776        }
 777        return merged_entry(a, old);
 778}
 779
 780static int read_cache_unmerged(void)
 781{
 782        int i, deleted;
 783        struct cache_entry **dst;
 784
 785        read_cache();
 786        dst = active_cache;
 787        deleted = 0;
 788        for (i = 0; i < active_nr; i++) {
 789                struct cache_entry *ce = active_cache[i];
 790                if (ce_stage(ce)) {
 791                        deleted++;
 792                        invalidate_ce_path(ce);
 793                        continue;
 794                }
 795                if (deleted)
 796                        *dst = ce;
 797                dst++;
 798        }
 799        active_nr -= deleted;
 800        return deleted;
 801}
 802
 803static void prime_cache_tree_rec(struct cache_tree *it, struct tree *tree)
 804{
 805        struct tree_desc desc;
 806        int cnt = 0;
 807
 808        memcpy(it->sha1, tree->object.sha1, 20);
 809        desc.buf = tree->buffer;
 810        desc.size = tree->size;
 811
 812        while (desc.size) {
 813                unsigned mode;
 814                const char *name;
 815                const unsigned char *sha1;
 816
 817                sha1 = tree_entry_extract(&desc, &name, &mode);
 818                update_tree_entry(&desc);
 819
 820                if (!S_ISDIR(mode))
 821                        cnt++;
 822                else {
 823                        struct cache_tree_sub *sub;
 824                        struct tree *subtree;
 825
 826                        subtree = lookup_tree(sha1);
 827                        if (!subtree->object.parsed)
 828                                parse_tree(subtree);
 829                        sub = cache_tree_sub(it, name);
 830                        sub->cache_tree = cache_tree();
 831                        prime_cache_tree_rec(sub->cache_tree, subtree);
 832                        cnt += sub->cache_tree->entry_count;
 833                }
 834        }
 835        it->entry_count = cnt;
 836}
 837
 838static void prime_cache_tree(void)
 839{
 840        struct tree *tree = (struct tree *)trees->item;
 841        if (!tree)
 842                return;
 843        active_cache_tree = cache_tree();
 844        prime_cache_tree_rec(active_cache_tree, tree);
 845
 846}
 847
 848static const char read_tree_usage[] = "git-read-tree (<sha> | [[-m [--aggressive] | --reset | --prefix=<prefix>] [-u | -i]] <sha1> [<sha2> [<sha3>]])";
 849
 850static struct cache_file cache_file;
 851
 852int cmd_read_tree(int argc, const char **argv, char **envp)
 853{
 854        int i, newfd, stage = 0;
 855        unsigned char sha1[20];
 856        merge_fn_t fn = NULL;
 857
 858        setup_git_directory();
 859        git_config(git_default_config);
 860
 861        newfd = hold_index_file_for_update(&cache_file, get_index_file());
 862        if (newfd < 0)
 863                die("unable to create new cachefile");
 864
 865        git_config(git_default_config);
 866
 867        merge = 0;
 868        reset = 0;
 869        for (i = 1; i < argc; i++) {
 870                const char *arg = argv[i];
 871
 872                /* "-u" means "update", meaning that a merge will update
 873                 * the working tree.
 874                 */
 875                if (!strcmp(arg, "-u")) {
 876                        update = 1;
 877                        continue;
 878                }
 879
 880                if (!strcmp(arg, "-v")) {
 881                        verbose_update = 1;
 882                        continue;
 883                }
 884
 885                /* "-i" means "index only", meaning that a merge will
 886                 * not even look at the working tree.
 887                 */
 888                if (!strcmp(arg, "-i")) {
 889                        index_only = 1;
 890                        continue;
 891                }
 892
 893                /* "--prefix=<subdirectory>/" means keep the current index
 894                 *  entries and put the entries from the tree under the
 895                 * given subdirectory.
 896                 */
 897                if (!strncmp(arg, "--prefix=", 9)) {
 898                        if (stage || merge || prefix)
 899                                usage(read_tree_usage);
 900                        prefix = arg + 9;
 901                        merge = 1;
 902                        stage = 1;
 903                        if (read_cache_unmerged())
 904                                die("you need to resolve your current index first");
 905                        continue;
 906                }
 907
 908                /* This differs from "-m" in that we'll silently ignore unmerged entries */
 909                if (!strcmp(arg, "--reset")) {
 910                        if (stage || merge || prefix)
 911                                usage(read_tree_usage);
 912                        reset = 1;
 913                        merge = 1;
 914                        stage = 1;
 915                        read_cache_unmerged();
 916                        continue;
 917                }
 918
 919                if (!strcmp(arg, "--trivial")) {
 920                        trivial_merges_only = 1;
 921                        continue;
 922                }
 923
 924                if (!strcmp(arg, "--aggressive")) {
 925                        aggressive = 1;
 926                        continue;
 927                }
 928
 929                /* "-m" stands for "merge", meaning we start in stage 1 */
 930                if (!strcmp(arg, "-m")) {
 931                        if (stage || merge || prefix)
 932                                usage(read_tree_usage);
 933                        if (read_cache_unmerged())
 934                                die("you need to resolve your current index first");
 935                        stage = 1;
 936                        merge = 1;
 937                        continue;
 938                }
 939
 940                /* using -u and -i at the same time makes no sense */
 941                if (1 < index_only + update)
 942                        usage(read_tree_usage);
 943
 944                if (get_sha1(arg, sha1))
 945                        die("Not a valid object name %s", arg);
 946                if (list_tree(sha1) < 0)
 947                        die("failed to unpack tree object %s", arg);
 948                stage++;
 949        }
 950        if ((update||index_only) && !merge)
 951                usage(read_tree_usage);
 952
 953        if (prefix) {
 954                int pfxlen = strlen(prefix);
 955                int pos;
 956                if (prefix[pfxlen-1] != '/')
 957                        die("prefix must end with /");
 958                if (stage != 2)
 959                        die("binding merge takes only one tree");
 960                pos = cache_name_pos(prefix, pfxlen);
 961                if (0 <= pos)
 962                        die("corrupt index file");
 963                pos = -pos-1;
 964                if (pos < active_nr &&
 965                    !strncmp(active_cache[pos]->name, prefix, pfxlen))
 966                        die("subdirectory '%s' already exists.", prefix);
 967                pos = cache_name_pos(prefix, pfxlen-1);
 968                if (0 <= pos)
 969                        die("file '%.*s' already exists.", pfxlen-1, prefix);
 970        }
 971
 972        if (merge) {
 973                if (stage < 2)
 974                        die("just how do you expect me to merge %d trees?", stage-1);
 975                switch (stage - 1) {
 976                case 1:
 977                        fn = prefix ? bind_merge : oneway_merge;
 978                        break;
 979                case 2:
 980                        fn = twoway_merge;
 981                        break;
 982                case 3:
 983                default:
 984                        fn = threeway_merge;
 985                        cache_tree_free(&active_cache_tree);
 986                        break;
 987                }
 988
 989                if (stage - 1 >= 3)
 990                        head_idx = stage - 2;
 991                else
 992                        head_idx = 1;
 993        }
 994
 995        unpack_trees(fn);
 996
 997        /*
 998         * When reading only one tree (either the most basic form,
 999         * "-m ent" or "--reset ent" form), we can obtain a fully
1000         * valid cache-tree because the index must match exactly
1001         * what came from the tree.
1002         */
1003        if (trees && trees->item && (!merge || (stage == 2))) {
1004                cache_tree_free(&active_cache_tree);
1005                prime_cache_tree();
1006        }
1007
1008        if (write_cache(newfd, active_cache, active_nr) ||
1009            commit_index_file(&cache_file))
1010                die("unable to write new index file");
1011        return 0;
1012}