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