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