pack-objects.con commit git-verify-pack: get rid of while loop (fc5fc50)
   1#include "cache.h"
   2#include "object.h"
   3#include "blob.h"
   4#include "commit.h"
   5#include "tag.h"
   6#include "tree.h"
   7#include "delta.h"
   8#include "pack.h"
   9#include "csum-file.h"
  10#include "tree-walk.h"
  11#include <sys/time.h>
  12#include <signal.h>
  13
  14static const char pack_usage[] = "git-pack-objects [-q] [--no-reuse-delta] [--non-empty] [--local] [--incremental] [--window=N] [--depth=N] {--stdout | base-name} < object-list";
  15
  16struct object_entry {
  17        unsigned char sha1[20];
  18        unsigned long size;     /* uncompressed size */
  19        unsigned long offset;   /* offset into the final pack file;
  20                                 * nonzero if already written.
  21                                 */
  22        unsigned int depth;     /* delta depth */
  23        unsigned int delta_limit;       /* base adjustment for in-pack delta */
  24        unsigned int hash;      /* name hint hash */
  25        enum object_type type;
  26        enum object_type in_pack_type;  /* could be delta */
  27        unsigned long delta_size;       /* delta data size (uncompressed) */
  28        struct object_entry *delta;     /* delta base object */
  29        struct packed_git *in_pack;     /* already in pack */
  30        unsigned int in_pack_offset;
  31        struct object_entry *delta_child; /* deltified objects who bases me */
  32        struct object_entry *delta_sibling; /* other deltified objects who
  33                                             * uses the same base as me
  34                                             */
  35        int preferred_base;     /* we do not pack this, but is encouraged to
  36                                 * be used as the base objectto delta huge
  37                                 * objects against.
  38                                 */
  39};
  40
  41/*
  42 * Objects we are going to pack are collected in objects array (dynamically
  43 * expanded).  nr_objects & nr_alloc controls this array.  They are stored
  44 * in the order we see -- typically rev-list --objects order that gives us
  45 * nice "minimum seek" order.
  46 *
  47 * sorted-by-sha ans sorted-by-type are arrays of pointers that point at
  48 * elements in the objects array.  The former is used to build the pack
  49 * index (lists object names in the ascending order to help offset lookup),
  50 * and the latter is used to group similar things together by try_delta()
  51 * heuristics.
  52 */
  53
  54static unsigned char object_list_sha1[20];
  55static int non_empty = 0;
  56static int no_reuse_delta = 0;
  57static int local = 0;
  58static int incremental = 0;
  59static struct object_entry **sorted_by_sha, **sorted_by_type;
  60static struct object_entry *objects = NULL;
  61static int nr_objects = 0, nr_alloc = 0, nr_result = 0;
  62static const char *base_name;
  63static unsigned char pack_file_sha1[20];
  64static int progress = 1;
  65static volatile sig_atomic_t progress_update = 0;
  66static int window = 10;
  67
  68/*
  69 * The object names in objects array are hashed with this hashtable,
  70 * to help looking up the entry by object name.  Binary search from
  71 * sorted_by_sha is also possible but this was easier to code and faster.
  72 * This hashtable is built after all the objects are seen.
  73 */
  74static int *object_ix = NULL;
  75static int object_ix_hashsz = 0;
  76
  77/*
  78 * Pack index for existing packs give us easy access to the offsets into
  79 * corresponding pack file where each object's data starts, but the entries
  80 * do not store the size of the compressed representation (uncompressed
  81 * size is easily available by examining the pack entry header).  We build
  82 * a hashtable of existing packs (pack_revindex), and keep reverse index
  83 * here -- pack index file is sorted by object name mapping to offset; this
  84 * pack_revindex[].revindex array is an ordered list of offsets, so if you
  85 * know the offset of an object, next offset is where its packed
  86 * representation ends.
  87 */
  88struct pack_revindex {
  89        struct packed_git *p;
  90        unsigned long *revindex;
  91} *pack_revindex = NULL;
  92static int pack_revindex_hashsz = 0;
  93
  94/*
  95 * stats
  96 */
  97static int written = 0;
  98static int written_delta = 0;
  99static int reused = 0;
 100static int reused_delta = 0;
 101
 102static int pack_revindex_ix(struct packed_git *p)
 103{
 104        unsigned long ui = (unsigned long)p;
 105        int i;
 106
 107        ui = ui ^ (ui >> 16); /* defeat structure alignment */
 108        i = (int)(ui % pack_revindex_hashsz);
 109        while (pack_revindex[i].p) {
 110                if (pack_revindex[i].p == p)
 111                        return i;
 112                if (++i == pack_revindex_hashsz)
 113                        i = 0;
 114        }
 115        return -1 - i;
 116}
 117
 118static void prepare_pack_ix(void)
 119{
 120        int num;
 121        struct packed_git *p;
 122        for (num = 0, p = packed_git; p; p = p->next)
 123                num++;
 124        if (!num)
 125                return;
 126        pack_revindex_hashsz = num * 11;
 127        pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
 128        for (p = packed_git; p; p = p->next) {
 129                num = pack_revindex_ix(p);
 130                num = - 1 - num;
 131                pack_revindex[num].p = p;
 132        }
 133        /* revindex elements are lazily initialized */
 134}
 135
 136static int cmp_offset(const void *a_, const void *b_)
 137{
 138        unsigned long a = *(unsigned long *) a_;
 139        unsigned long b = *(unsigned long *) b_;
 140        if (a < b)
 141                return -1;
 142        else if (a == b)
 143                return 0;
 144        else
 145                return 1;
 146}
 147
 148/*
 149 * Ordered list of offsets of objects in the pack.
 150 */
 151static void prepare_pack_revindex(struct pack_revindex *rix)
 152{
 153        struct packed_git *p = rix->p;
 154        int num_ent = num_packed_objects(p);
 155        int i;
 156        void *index = p->index_base + 256;
 157
 158        rix->revindex = xmalloc(sizeof(unsigned long) * (num_ent + 1));
 159        for (i = 0; i < num_ent; i++) {
 160                unsigned int hl = *((unsigned int *)((char *) index + 24*i));
 161                rix->revindex[i] = ntohl(hl);
 162        }
 163        /* This knows the pack format -- the 20-byte trailer
 164         * follows immediately after the last object data.
 165         */
 166        rix->revindex[num_ent] = p->pack_size - 20;
 167        qsort(rix->revindex, num_ent, sizeof(unsigned long), cmp_offset);
 168}
 169
 170static unsigned long find_packed_object_size(struct packed_git *p,
 171                                             unsigned long ofs)
 172{
 173        int num;
 174        int lo, hi;
 175        struct pack_revindex *rix;
 176        unsigned long *revindex;
 177        num = pack_revindex_ix(p);
 178        if (num < 0)
 179                die("internal error: pack revindex uninitialized");
 180        rix = &pack_revindex[num];
 181        if (!rix->revindex)
 182                prepare_pack_revindex(rix);
 183        revindex = rix->revindex;
 184        lo = 0;
 185        hi = num_packed_objects(p) + 1;
 186        do {
 187                int mi = (lo + hi) / 2;
 188                if (revindex[mi] == ofs) {
 189                        return revindex[mi+1] - ofs;
 190                }
 191                else if (ofs < revindex[mi])
 192                        hi = mi;
 193                else
 194                        lo = mi + 1;
 195        } while (lo < hi);
 196        die("internal error: pack revindex corrupt");
 197}
 198
 199static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
 200{
 201        unsigned long othersize, delta_size;
 202        char type[10];
 203        void *otherbuf = read_sha1_file(entry->delta->sha1, type, &othersize);
 204        void *delta_buf;
 205
 206        if (!otherbuf)
 207                die("unable to read %s", sha1_to_hex(entry->delta->sha1));
 208        delta_buf = diff_delta(otherbuf, othersize,
 209                               buf, size, &delta_size, 0);
 210        if (!delta_buf || delta_size != entry->delta_size)
 211                die("delta size changed");
 212        free(buf);
 213        free(otherbuf);
 214        return delta_buf;
 215}
 216
 217/*
 218 * The per-object header is a pretty dense thing, which is
 219 *  - first byte: low four bits are "size", then three bits of "type",
 220 *    and the high bit is "size continues".
 221 *  - each byte afterwards: low seven bits are size continuation,
 222 *    with the high bit being "size continues"
 223 */
 224static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
 225{
 226        int n = 1;
 227        unsigned char c;
 228
 229        if (type < OBJ_COMMIT || type > OBJ_DELTA)
 230                die("bad type %d", type);
 231
 232        c = (type << 4) | (size & 15);
 233        size >>= 4;
 234        while (size) {
 235                *hdr++ = c | 0x80;
 236                c = size & 0x7f;
 237                size >>= 7;
 238                n++;
 239        }
 240        *hdr = c;
 241        return n;
 242}
 243
 244static unsigned long write_object(struct sha1file *f,
 245                                  struct object_entry *entry)
 246{
 247        unsigned long size;
 248        char type[10];
 249        void *buf;
 250        unsigned char header[10];
 251        unsigned hdrlen, datalen;
 252        enum object_type obj_type;
 253        int to_reuse = 0;
 254
 255        if (entry->preferred_base)
 256                return 0;
 257
 258        obj_type = entry->type;
 259        if (! entry->in_pack)
 260                to_reuse = 0;   /* can't reuse what we don't have */
 261        else if (obj_type == OBJ_DELTA)
 262                to_reuse = 1;   /* check_object() decided it for us */
 263        else if (obj_type != entry->in_pack_type)
 264                to_reuse = 0;   /* pack has delta which is unusable */
 265        else if (entry->delta)
 266                to_reuse = 0;   /* we want to pack afresh */
 267        else
 268                to_reuse = 1;   /* we have it in-pack undeltified,
 269                                 * and we do not need to deltify it.
 270                                 */
 271
 272        if (! to_reuse) {
 273                buf = read_sha1_file(entry->sha1, type, &size);
 274                if (!buf)
 275                        die("unable to read %s", sha1_to_hex(entry->sha1));
 276                if (size != entry->size)
 277                        die("object %s size inconsistency (%lu vs %lu)",
 278                            sha1_to_hex(entry->sha1), size, entry->size);
 279                if (entry->delta) {
 280                        buf = delta_against(buf, size, entry);
 281                        size = entry->delta_size;
 282                        obj_type = OBJ_DELTA;
 283                }
 284                /*
 285                 * The object header is a byte of 'type' followed by zero or
 286                 * more bytes of length.  For deltas, the 20 bytes of delta
 287                 * sha1 follows that.
 288                 */
 289                hdrlen = encode_header(obj_type, size, header);
 290                sha1write(f, header, hdrlen);
 291
 292                if (entry->delta) {
 293                        sha1write(f, entry->delta, 20);
 294                        hdrlen += 20;
 295                }
 296                datalen = sha1write_compressed(f, buf, size);
 297                free(buf);
 298        }
 299        else {
 300                struct packed_git *p = entry->in_pack;
 301                use_packed_git(p);
 302
 303                datalen = find_packed_object_size(p, entry->in_pack_offset);
 304                buf = (char *) p->pack_base + entry->in_pack_offset;
 305                sha1write(f, buf, datalen);
 306                unuse_packed_git(p);
 307                hdrlen = 0; /* not really */
 308                if (obj_type == OBJ_DELTA)
 309                        reused_delta++;
 310                reused++;
 311        }
 312        if (obj_type == OBJ_DELTA)
 313                written_delta++;
 314        written++;
 315        return hdrlen + datalen;
 316}
 317
 318static unsigned long write_one(struct sha1file *f,
 319                               struct object_entry *e,
 320                               unsigned long offset)
 321{
 322        if (e->offset)
 323                /* offset starts from header size and cannot be zero
 324                 * if it is written already.
 325                 */
 326                return offset;
 327        e->offset = offset;
 328        offset += write_object(f, e);
 329        /* if we are deltified, write out its base object. */
 330        if (e->delta)
 331                offset = write_one(f, e->delta, offset);
 332        return offset;
 333}
 334
 335static void write_pack_file(void)
 336{
 337        int i;
 338        struct sha1file *f;
 339        unsigned long offset;
 340        struct pack_header hdr;
 341        unsigned last_percent = 999;
 342        int do_progress = 0;
 343
 344        if (!base_name)
 345                f = sha1fd(1, "<stdout>");
 346        else {
 347                f = sha1create("%s-%s.%s", base_name,
 348                               sha1_to_hex(object_list_sha1), "pack");
 349                do_progress = progress;
 350        }
 351        if (do_progress)
 352                fprintf(stderr, "Writing %d objects.\n", nr_result);
 353
 354        hdr.hdr_signature = htonl(PACK_SIGNATURE);
 355        hdr.hdr_version = htonl(PACK_VERSION);
 356        hdr.hdr_entries = htonl(nr_result);
 357        sha1write(f, &hdr, sizeof(hdr));
 358        offset = sizeof(hdr);
 359        if (!nr_result)
 360                goto done;
 361        for (i = 0; i < nr_objects; i++) {
 362                offset = write_one(f, objects + i, offset);
 363                if (do_progress) {
 364                        unsigned percent = written * 100 / nr_result;
 365                        if (progress_update || percent != last_percent) {
 366                                fprintf(stderr, "%4u%% (%u/%u) done\r",
 367                                        percent, written, nr_result);
 368                                progress_update = 0;
 369                                last_percent = percent;
 370                        }
 371                }
 372        }
 373        if (do_progress)
 374                fputc('\n', stderr);
 375 done:
 376        sha1close(f, pack_file_sha1, 1);
 377}
 378
 379static void write_index_file(void)
 380{
 381        int i;
 382        struct sha1file *f = sha1create("%s-%s.%s", base_name,
 383                                        sha1_to_hex(object_list_sha1), "idx");
 384        struct object_entry **list = sorted_by_sha;
 385        struct object_entry **last = list + nr_result;
 386        unsigned int array[256];
 387
 388        /*
 389         * Write the first-level table (the list is sorted,
 390         * but we use a 256-entry lookup to be able to avoid
 391         * having to do eight extra binary search iterations).
 392         */
 393        for (i = 0; i < 256; i++) {
 394                struct object_entry **next = list;
 395                while (next < last) {
 396                        struct object_entry *entry = *next;
 397                        if (entry->sha1[0] != i)
 398                                break;
 399                        next++;
 400                }
 401                array[i] = htonl(next - sorted_by_sha);
 402                list = next;
 403        }
 404        sha1write(f, array, 256 * sizeof(int));
 405
 406        /*
 407         * Write the actual SHA1 entries..
 408         */
 409        list = sorted_by_sha;
 410        for (i = 0; i < nr_result; i++) {
 411                struct object_entry *entry = *list++;
 412                unsigned int offset = htonl(entry->offset);
 413                sha1write(f, &offset, 4);
 414                sha1write(f, entry->sha1, 20);
 415        }
 416        sha1write(f, pack_file_sha1, 20);
 417        sha1close(f, NULL, 1);
 418}
 419
 420static int locate_object_entry_hash(const unsigned char *sha1)
 421{
 422        int i;
 423        unsigned int ui;
 424        memcpy(&ui, sha1, sizeof(unsigned int));
 425        i = ui % object_ix_hashsz;
 426        while (0 < object_ix[i]) {
 427                if (!memcmp(sha1, objects[object_ix[i]-1].sha1, 20))
 428                        return i;
 429                if (++i == object_ix_hashsz)
 430                        i = 0;
 431        }
 432        return -1 - i;
 433}
 434
 435static struct object_entry *locate_object_entry(const unsigned char *sha1)
 436{
 437        int i;
 438
 439        if (!object_ix_hashsz)
 440                return NULL;
 441
 442        i = locate_object_entry_hash(sha1);
 443        if (0 <= i)
 444                return &objects[object_ix[i]-1];
 445        return NULL;
 446}
 447
 448static void rehash_objects(void)
 449{
 450        int i;
 451        struct object_entry *oe;
 452
 453        object_ix_hashsz = nr_objects * 3;
 454        if (object_ix_hashsz < 1024)
 455                object_ix_hashsz = 1024;
 456        object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
 457        memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
 458        for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
 459                int ix = locate_object_entry_hash(oe->sha1);
 460                if (0 <= ix)
 461                        continue;
 462                ix = -1 - ix;
 463                object_ix[ix] = i + 1;
 464        }
 465}
 466
 467static unsigned name_hash(const char *name)
 468{
 469        unsigned char c;
 470        unsigned hash = 0;
 471
 472        /*
 473         * This effectively just creates a sortable number from the
 474         * last sixteen non-whitespace characters. Last characters
 475         * count "most", so things that end in ".c" sort together.
 476         */
 477        while ((c = *name++) != 0) {
 478                if (isspace(c))
 479                        continue;
 480                hash = (hash >> 2) + (c << 24);
 481        }
 482        return hash;
 483}
 484
 485static int add_object_entry(const unsigned char *sha1, unsigned hash, int exclude)
 486{
 487        unsigned int idx = nr_objects;
 488        struct object_entry *entry;
 489        struct packed_git *p;
 490        unsigned int found_offset = 0;
 491        struct packed_git *found_pack = NULL;
 492        int ix, status = 0;
 493
 494        if (!exclude) {
 495                for (p = packed_git; p; p = p->next) {
 496                        struct pack_entry e;
 497                        if (find_pack_entry_one(sha1, &e, p)) {
 498                                if (incremental)
 499                                        return 0;
 500                                if (local && !p->pack_local)
 501                                        return 0;
 502                                if (!found_pack) {
 503                                        found_offset = e.offset;
 504                                        found_pack = e.p;
 505                                }
 506                        }
 507                }
 508        }
 509        if ((entry = locate_object_entry(sha1)) != NULL)
 510                goto already_added;
 511
 512        if (idx >= nr_alloc) {
 513                unsigned int needed = (idx + 1024) * 3 / 2;
 514                objects = xrealloc(objects, needed * sizeof(*entry));
 515                nr_alloc = needed;
 516        }
 517        entry = objects + idx;
 518        nr_objects = idx + 1;
 519        memset(entry, 0, sizeof(*entry));
 520        memcpy(entry->sha1, sha1, 20);
 521        entry->hash = hash;
 522
 523        if (object_ix_hashsz * 3 <= nr_objects * 4)
 524                rehash_objects();
 525        else {
 526                ix = locate_object_entry_hash(entry->sha1);
 527                if (0 <= ix)
 528                        die("internal error in object hashing.");
 529                object_ix[-1 - ix] = idx + 1;
 530        }
 531        status = 1;
 532
 533 already_added:
 534        if (progress_update) {
 535                fprintf(stderr, "Counting objects...%d\r", nr_objects);
 536                progress_update = 0;
 537        }
 538        if (exclude)
 539                entry->preferred_base = 1;
 540        else {
 541                if (found_pack) {
 542                        entry->in_pack = found_pack;
 543                        entry->in_pack_offset = found_offset;
 544                }
 545        }
 546        return status;
 547}
 548
 549struct pbase_tree_cache {
 550        unsigned char sha1[20];
 551        int ref;
 552        int temporary;
 553        void *tree_data;
 554        unsigned long tree_size;
 555};
 556
 557static struct pbase_tree_cache *(pbase_tree_cache[256]);
 558static int pbase_tree_cache_ix(const unsigned char *sha1)
 559{
 560        return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
 561}
 562static int pbase_tree_cache_ix_incr(int ix)
 563{
 564        return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
 565}
 566
 567static struct pbase_tree {
 568        struct pbase_tree *next;
 569        /* This is a phony "cache" entry; we are not
 570         * going to evict it nor find it through _get()
 571         * mechanism -- this is for the toplevel node that
 572         * would almost always change with any commit.
 573         */
 574        struct pbase_tree_cache pcache;
 575} *pbase_tree;
 576
 577static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
 578{
 579        struct pbase_tree_cache *ent, *nent;
 580        void *data;
 581        unsigned long size;
 582        char type[20];
 583        int neigh;
 584        int my_ix = pbase_tree_cache_ix(sha1);
 585        int available_ix = -1;
 586
 587        /* pbase-tree-cache acts as a limited hashtable.
 588         * your object will be found at your index or within a few
 589         * slots after that slot if it is cached.
 590         */
 591        for (neigh = 0; neigh < 8; neigh++) {
 592                ent = pbase_tree_cache[my_ix];
 593                if (ent && !memcmp(ent->sha1, sha1, 20)) {
 594                        ent->ref++;
 595                        return ent;
 596                }
 597                else if (((available_ix < 0) && (!ent || !ent->ref)) ||
 598                         ((0 <= available_ix) &&
 599                          (!ent && pbase_tree_cache[available_ix])))
 600                        available_ix = my_ix;
 601                if (!ent)
 602                        break;
 603                my_ix = pbase_tree_cache_ix_incr(my_ix);
 604        }
 605
 606        /* Did not find one.  Either we got a bogus request or
 607         * we need to read and perhaps cache.
 608         */
 609        data = read_sha1_file(sha1, type, &size);
 610        if (!data)
 611                return NULL;
 612        if (strcmp(type, tree_type)) {
 613                free(data);
 614                return NULL;
 615        }
 616
 617        /* We need to either cache or return a throwaway copy */
 618
 619        if (available_ix < 0)
 620                ent = NULL;
 621        else {
 622                ent = pbase_tree_cache[available_ix];
 623                my_ix = available_ix;
 624        }
 625
 626        if (!ent) {
 627                nent = xmalloc(sizeof(*nent));
 628                nent->temporary = (available_ix < 0);
 629        }
 630        else {
 631                /* evict and reuse */
 632                free(ent->tree_data);
 633                nent = ent;
 634        }
 635        memcpy(nent->sha1, sha1, 20);
 636        nent->tree_data = data;
 637        nent->tree_size = size;
 638        nent->ref = 1;
 639        if (!nent->temporary)
 640                pbase_tree_cache[my_ix] = nent;
 641        return nent;
 642}
 643
 644static void pbase_tree_put(struct pbase_tree_cache *cache)
 645{
 646        if (!cache->temporary) {
 647                cache->ref--;
 648                return;
 649        }
 650        free(cache->tree_data);
 651        free(cache);
 652}
 653
 654static int name_cmp_len(const char *name)
 655{
 656        int i;
 657        for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
 658                ;
 659        return i;
 660}
 661
 662static void add_pbase_object(struct tree_desc *tree,
 663                             const char *name,
 664                             int cmplen,
 665                             const char *fullname)
 666{
 667        struct name_entry entry;
 668
 669        while (tree_entry(tree,&entry)) {
 670                unsigned long size;
 671                char type[20];
 672
 673                if (entry.pathlen != cmplen ||
 674                    memcmp(entry.path, name, cmplen) ||
 675                    !has_sha1_file(entry.sha1) ||
 676                    sha1_object_info(entry.sha1, type, &size))
 677                        continue;
 678                if (name[cmplen] != '/') {
 679                        unsigned hash = name_hash(fullname);
 680                        add_object_entry(entry.sha1, hash, 1);
 681                        return;
 682                }
 683                if (!strcmp(type, tree_type)) {
 684                        struct tree_desc sub;
 685                        struct pbase_tree_cache *tree;
 686                        const char *down = name+cmplen+1;
 687                        int downlen = name_cmp_len(down);
 688
 689                        tree = pbase_tree_get(entry.sha1);
 690                        if (!tree)
 691                                return;
 692                        sub.buf = tree->tree_data;
 693                        sub.size = tree->tree_size;
 694
 695                        add_pbase_object(&sub, down, downlen, fullname);
 696                        pbase_tree_put(tree);
 697                }
 698        }
 699}
 700
 701static unsigned *done_pbase_paths;
 702static int done_pbase_paths_num;
 703static int done_pbase_paths_alloc;
 704static int done_pbase_path_pos(unsigned hash)
 705{
 706        int lo = 0;
 707        int hi = done_pbase_paths_num;
 708        while (lo < hi) {
 709                int mi = (hi + lo) / 2;
 710                if (done_pbase_paths[mi] == hash)
 711                        return mi;
 712                if (done_pbase_paths[mi] < hash)
 713                        hi = mi;
 714                else
 715                        lo = mi + 1;
 716        }
 717        return -lo-1;
 718}
 719
 720static int check_pbase_path(unsigned hash)
 721{
 722        int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
 723        if (0 <= pos)
 724                return 1;
 725        pos = -pos - 1;
 726        if (done_pbase_paths_alloc <= done_pbase_paths_num) {
 727                done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
 728                done_pbase_paths = xrealloc(done_pbase_paths,
 729                                            done_pbase_paths_alloc *
 730                                            sizeof(unsigned));
 731        }
 732        done_pbase_paths_num++;
 733        if (pos < done_pbase_paths_num)
 734                memmove(done_pbase_paths + pos + 1,
 735                        done_pbase_paths + pos,
 736                        (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
 737        done_pbase_paths[pos] = hash;
 738        return 0;
 739}
 740
 741static void add_preferred_base_object(char *name, unsigned hash)
 742{
 743        struct pbase_tree *it;
 744        int cmplen = name_cmp_len(name);
 745
 746        if (check_pbase_path(hash))
 747                return;
 748
 749        for (it = pbase_tree; it; it = it->next) {
 750                if (cmplen == 0) {
 751                        hash = name_hash("");
 752                        add_object_entry(it->pcache.sha1, hash, 1);
 753                }
 754                else {
 755                        struct tree_desc tree;
 756                        tree.buf = it->pcache.tree_data;
 757                        tree.size = it->pcache.tree_size;
 758                        add_pbase_object(&tree, name, cmplen, name);
 759                }
 760        }
 761}
 762
 763static void add_preferred_base(unsigned char *sha1)
 764{
 765        struct pbase_tree *it;
 766        void *data;
 767        unsigned long size;
 768        unsigned char tree_sha1[20];
 769
 770        data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
 771        if (!data)
 772                return;
 773
 774        for (it = pbase_tree; it; it = it->next) {
 775                if (!memcmp(it->pcache.sha1, tree_sha1, 20)) {
 776                        free(data);
 777                        return;
 778                }
 779        }
 780
 781        it = xcalloc(1, sizeof(*it));
 782        it->next = pbase_tree;
 783        pbase_tree = it;
 784
 785        memcpy(it->pcache.sha1, tree_sha1, 20);
 786        it->pcache.tree_data = data;
 787        it->pcache.tree_size = size;
 788}
 789
 790static void check_object(struct object_entry *entry)
 791{
 792        char type[20];
 793
 794        if (entry->in_pack && !entry->preferred_base) {
 795                unsigned char base[20];
 796                unsigned long size;
 797                struct object_entry *base_entry;
 798
 799                /* We want in_pack_type even if we do not reuse delta.
 800                 * There is no point not reusing non-delta representations.
 801                 */
 802                check_reuse_pack_delta(entry->in_pack,
 803                                       entry->in_pack_offset,
 804                                       base, &size,
 805                                       &entry->in_pack_type);
 806
 807                /* Check if it is delta, and the base is also an object
 808                 * we are going to pack.  If so we will reuse the existing
 809                 * delta.
 810                 */
 811                if (!no_reuse_delta &&
 812                    entry->in_pack_type == OBJ_DELTA &&
 813                    (base_entry = locate_object_entry(base)) &&
 814                    (!base_entry->preferred_base)) {
 815
 816                        /* Depth value does not matter - find_deltas()
 817                         * will never consider reused delta as the
 818                         * base object to deltify other objects
 819                         * against, in order to avoid circular deltas.
 820                         */
 821
 822                        /* uncompressed size of the delta data */
 823                        entry->size = entry->delta_size = size;
 824                        entry->delta = base_entry;
 825                        entry->type = OBJ_DELTA;
 826
 827                        entry->delta_sibling = base_entry->delta_child;
 828                        base_entry->delta_child = entry;
 829
 830                        return;
 831                }
 832                /* Otherwise we would do the usual */
 833        }
 834
 835        if (sha1_object_info(entry->sha1, type, &entry->size))
 836                die("unable to get type of object %s",
 837                    sha1_to_hex(entry->sha1));
 838
 839        if (!strcmp(type, commit_type)) {
 840                entry->type = OBJ_COMMIT;
 841        } else if (!strcmp(type, tree_type)) {
 842                entry->type = OBJ_TREE;
 843        } else if (!strcmp(type, blob_type)) {
 844                entry->type = OBJ_BLOB;
 845        } else if (!strcmp(type, tag_type)) {
 846                entry->type = OBJ_TAG;
 847        } else
 848                die("unable to pack object %s of type %s",
 849                    sha1_to_hex(entry->sha1), type);
 850}
 851
 852static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
 853{
 854        struct object_entry *child = me->delta_child;
 855        unsigned int m = n;
 856        while (child) {
 857                unsigned int c = check_delta_limit(child, n + 1);
 858                if (m < c)
 859                        m = c;
 860                child = child->delta_sibling;
 861        }
 862        return m;
 863}
 864
 865static void get_object_details(void)
 866{
 867        int i;
 868        struct object_entry *entry;
 869
 870        prepare_pack_ix();
 871        for (i = 0, entry = objects; i < nr_objects; i++, entry++)
 872                check_object(entry);
 873
 874        if (nr_objects == nr_result) {
 875                /*
 876                 * Depth of objects that depend on the entry -- this
 877                 * is subtracted from depth-max to break too deep
 878                 * delta chain because of delta data reusing.
 879                 * However, we loosen this restriction when we know we
 880                 * are creating a thin pack -- it will have to be
 881                 * expanded on the other end anyway, so do not
 882                 * artificially cut the delta chain and let it go as
 883                 * deep as it wants.
 884                 */
 885                for (i = 0, entry = objects; i < nr_objects; i++, entry++)
 886                        if (!entry->delta && entry->delta_child)
 887                                entry->delta_limit =
 888                                        check_delta_limit(entry, 1);
 889        }
 890}
 891
 892typedef int (*entry_sort_t)(const struct object_entry *, const struct object_entry *);
 893
 894static entry_sort_t current_sort;
 895
 896static int sort_comparator(const void *_a, const void *_b)
 897{
 898        struct object_entry *a = *(struct object_entry **)_a;
 899        struct object_entry *b = *(struct object_entry **)_b;
 900        return current_sort(a,b);
 901}
 902
 903static struct object_entry **create_sorted_list(entry_sort_t sort)
 904{
 905        struct object_entry **list = xmalloc(nr_objects * sizeof(struct object_entry *));
 906        int i;
 907
 908        for (i = 0; i < nr_objects; i++)
 909                list[i] = objects + i;
 910        current_sort = sort;
 911        qsort(list, nr_objects, sizeof(struct object_entry *), sort_comparator);
 912        return list;
 913}
 914
 915static int sha1_sort(const struct object_entry *a, const struct object_entry *b)
 916{
 917        return memcmp(a->sha1, b->sha1, 20);
 918}
 919
 920static struct object_entry **create_final_object_list(void)
 921{
 922        struct object_entry **list;
 923        int i, j;
 924
 925        for (i = nr_result = 0; i < nr_objects; i++)
 926                if (!objects[i].preferred_base)
 927                        nr_result++;
 928        list = xmalloc(nr_result * sizeof(struct object_entry *));
 929        for (i = j = 0; i < nr_objects; i++) {
 930                if (!objects[i].preferred_base)
 931                        list[j++] = objects + i;
 932        }
 933        current_sort = sha1_sort;
 934        qsort(list, nr_result, sizeof(struct object_entry *), sort_comparator);
 935        return list;
 936}
 937
 938static int type_size_sort(const struct object_entry *a, const struct object_entry *b)
 939{
 940        if (a->type < b->type)
 941                return -1;
 942        if (a->type > b->type)
 943                return 1;
 944        if (a->hash < b->hash)
 945                return -1;
 946        if (a->hash > b->hash)
 947                return 1;
 948        if (a->preferred_base < b->preferred_base)
 949                return -1;
 950        if (a->preferred_base > b->preferred_base)
 951                return 1;
 952        if (a->size < b->size)
 953                return -1;
 954        if (a->size > b->size)
 955                return 1;
 956        return a < b ? -1 : (a > b);
 957}
 958
 959struct unpacked {
 960        struct object_entry *entry;
 961        void *data;
 962        struct delta_index *index;
 963};
 964
 965/*
 966 * We search for deltas _backwards_ in a list sorted by type and
 967 * by size, so that we see progressively smaller and smaller files.
 968 * That's because we prefer deltas to be from the bigger file
 969 * to the smaller - deletes are potentially cheaper, but perhaps
 970 * more importantly, the bigger file is likely the more recent
 971 * one.
 972 */
 973static int try_delta(struct unpacked *trg, struct unpacked *src,
 974                     unsigned max_depth)
 975{
 976        struct object_entry *trg_entry = trg->entry;
 977        struct object_entry *src_entry = src->entry;
 978        unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
 979        char type[10];
 980        void *delta_buf;
 981
 982        /* Don't bother doing diffs between different types */
 983        if (trg_entry->type != src_entry->type)
 984                return -1;
 985
 986        /* We do not compute delta to *create* objects we are not
 987         * going to pack.
 988         */
 989        if (trg_entry->preferred_base)
 990                return -1;
 991
 992        /*
 993         * We do not bother to try a delta that we discarded
 994         * on an earlier try, but only when reusing delta data.
 995         */
 996        if (!no_reuse_delta && trg_entry->in_pack &&
 997            trg_entry->in_pack == src_entry->in_pack)
 998                return 0;
 999
1000        /*
1001         * If the current object is at pack edge, take the depth the
1002         * objects that depend on the current object into account --
1003         * otherwise they would become too deep.
1004         */
1005        if (trg_entry->delta_child) {
1006                if (max_depth <= trg_entry->delta_limit)
1007                        return 0;
1008                max_depth -= trg_entry->delta_limit;
1009        }
1010        if (src_entry->depth >= max_depth)
1011                return 0;
1012
1013        /* Now some size filtering heuristics. */
1014        trg_size = trg_entry->size;
1015        max_size = trg_size/2 - 20;
1016        max_size = max_size * (max_depth - src_entry->depth) / max_depth;
1017        if (max_size == 0)
1018                return 0;
1019        if (trg_entry->delta && trg_entry->delta_size <= max_size)
1020                max_size = trg_entry->delta_size-1;
1021        src_size = src_entry->size;
1022        sizediff = src_size < trg_size ? trg_size - src_size : 0;
1023        if (sizediff >= max_size)
1024                return 0;
1025
1026        /* Load data if not already done */
1027        if (!trg->data) {
1028                trg->data = read_sha1_file(trg_entry->sha1, type, &sz);
1029                if (sz != trg_size)
1030                        die("object %s inconsistent object length (%lu vs %lu)",
1031                            sha1_to_hex(trg_entry->sha1), sz, trg_size);
1032        }
1033        if (!src->data) {
1034                src->data = read_sha1_file(src_entry->sha1, type, &sz);
1035                if (sz != src_size)
1036                        die("object %s inconsistent object length (%lu vs %lu)",
1037                            sha1_to_hex(src_entry->sha1), sz, src_size);
1038        }
1039        if (!src->index) {
1040                src->index = create_delta_index(src->data, src_size);
1041                if (!src->index)
1042                        die("out of memory");
1043        }
1044
1045        delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1046        if (!delta_buf)
1047                return 0;
1048
1049        trg_entry->delta = src_entry;
1050        trg_entry->delta_size = delta_size;
1051        trg_entry->depth = src_entry->depth + 1;
1052        free(delta_buf);
1053        return 1;
1054}
1055
1056static void progress_interval(int signum)
1057{
1058        progress_update = 1;
1059}
1060
1061static void find_deltas(struct object_entry **list, int window, int depth)
1062{
1063        int i, idx;
1064        unsigned int array_size = window * sizeof(struct unpacked);
1065        struct unpacked *array = xmalloc(array_size);
1066        unsigned processed = 0;
1067        unsigned last_percent = 999;
1068
1069        memset(array, 0, array_size);
1070        i = nr_objects;
1071        idx = 0;
1072        if (progress)
1073                fprintf(stderr, "Deltifying %d objects.\n", nr_result);
1074
1075        while (--i >= 0) {
1076                struct object_entry *entry = list[i];
1077                struct unpacked *n = array + idx;
1078                int j;
1079
1080                if (!entry->preferred_base)
1081                        processed++;
1082
1083                if (progress) {
1084                        unsigned percent = processed * 100 / nr_result;
1085                        if (percent != last_percent || progress_update) {
1086                                fprintf(stderr, "%4u%% (%u/%u) done\r",
1087                                        percent, processed, nr_result);
1088                                progress_update = 0;
1089                                last_percent = percent;
1090                        }
1091                }
1092
1093                if (entry->delta)
1094                        /* This happens if we decided to reuse existing
1095                         * delta from a pack.  "!no_reuse_delta &&" is implied.
1096                         */
1097                        continue;
1098
1099                if (entry->size < 50)
1100                        continue;
1101                free_delta_index(n->index);
1102                n->index = NULL;
1103                free(n->data);
1104                n->data = NULL;
1105                n->entry = entry;
1106
1107                j = window;
1108                while (--j > 0) {
1109                        unsigned int other_idx = idx + j;
1110                        struct unpacked *m;
1111                        if (other_idx >= window)
1112                                other_idx -= window;
1113                        m = array + other_idx;
1114                        if (!m->entry)
1115                                break;
1116                        if (try_delta(n, m, depth) < 0)
1117                                break;
1118                }
1119                /* if we made n a delta, and if n is already at max
1120                 * depth, leaving it in the window is pointless.  we
1121                 * should evict it first.
1122                 */
1123                if (entry->delta && depth <= entry->depth)
1124                        continue;
1125
1126                idx++;
1127                if (idx >= window)
1128                        idx = 0;
1129        }
1130
1131        if (progress)
1132                fputc('\n', stderr);
1133
1134        for (i = 0; i < window; ++i) {
1135                free_delta_index(array[i].index);
1136                free(array[i].data);
1137        }
1138        free(array);
1139}
1140
1141static void prepare_pack(int window, int depth)
1142{
1143        get_object_details();
1144        sorted_by_type = create_sorted_list(type_size_sort);
1145        if (window && depth)
1146                find_deltas(sorted_by_type, window+1, depth);
1147}
1148
1149static int reuse_cached_pack(unsigned char *sha1, int pack_to_stdout)
1150{
1151        static const char cache[] = "pack-cache/pack-%s.%s";
1152        char *cached_pack, *cached_idx;
1153        int ifd, ofd, ifd_ix = -1;
1154
1155        cached_pack = git_path(cache, sha1_to_hex(sha1), "pack");
1156        ifd = open(cached_pack, O_RDONLY);
1157        if (ifd < 0)
1158                return 0;
1159
1160        if (!pack_to_stdout) {
1161                cached_idx = git_path(cache, sha1_to_hex(sha1), "idx");
1162                ifd_ix = open(cached_idx, O_RDONLY);
1163                if (ifd_ix < 0) {
1164                        close(ifd);
1165                        return 0;
1166                }
1167        }
1168
1169        if (progress)
1170                fprintf(stderr, "Reusing %d objects pack %s\n", nr_objects,
1171                        sha1_to_hex(sha1));
1172
1173        if (pack_to_stdout) {
1174                if (copy_fd(ifd, 1))
1175                        exit(1);
1176                close(ifd);
1177        }
1178        else {
1179                char name[PATH_MAX];
1180                snprintf(name, sizeof(name),
1181                         "%s-%s.%s", base_name, sha1_to_hex(sha1), "pack");
1182                ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1183                if (ofd < 0)
1184                        die("unable to open %s (%s)", name, strerror(errno));
1185                if (copy_fd(ifd, ofd))
1186                        exit(1);
1187                close(ifd);
1188
1189                snprintf(name, sizeof(name),
1190                         "%s-%s.%s", base_name, sha1_to_hex(sha1), "idx");
1191                ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1192                if (ofd < 0)
1193                        die("unable to open %s (%s)", name, strerror(errno));
1194                if (copy_fd(ifd_ix, ofd))
1195                        exit(1);
1196                close(ifd_ix);
1197                puts(sha1_to_hex(sha1));
1198        }
1199
1200        return 1;
1201}
1202
1203static void setup_progress_signal(void)
1204{
1205        struct sigaction sa;
1206        struct itimerval v;
1207
1208        memset(&sa, 0, sizeof(sa));
1209        sa.sa_handler = progress_interval;
1210        sigemptyset(&sa.sa_mask);
1211        sa.sa_flags = SA_RESTART;
1212        sigaction(SIGALRM, &sa, NULL);
1213
1214        v.it_interval.tv_sec = 1;
1215        v.it_interval.tv_usec = 0;
1216        v.it_value = v.it_interval;
1217        setitimer(ITIMER_REAL, &v, NULL);
1218}
1219
1220static int git_pack_config(const char *k, const char *v)
1221{
1222        if(!strcmp(k, "pack.window")) {
1223                window = git_config_int(k, v);
1224                return 0;
1225        }
1226        return git_default_config(k, v);
1227}
1228
1229int main(int argc, char **argv)
1230{
1231        SHA_CTX ctx;
1232        char line[40 + 1 + PATH_MAX + 2];
1233        int depth = 10, pack_to_stdout = 0;
1234        struct object_entry **list;
1235        int num_preferred_base = 0;
1236        int i;
1237
1238        setup_git_directory();
1239        git_config(git_pack_config);
1240
1241        progress = isatty(2);
1242        for (i = 1; i < argc; i++) {
1243                const char *arg = argv[i];
1244
1245                if (*arg == '-') {
1246                        if (!strcmp("--non-empty", arg)) {
1247                                non_empty = 1;
1248                                continue;
1249                        }
1250                        if (!strcmp("--local", arg)) {
1251                                local = 1;
1252                                continue;
1253                        }
1254                        if (!strcmp("--progress", arg)) {
1255                                progress = 1;
1256                                continue;
1257                        }
1258                        if (!strcmp("--incremental", arg)) {
1259                                incremental = 1;
1260                                continue;
1261                        }
1262                        if (!strncmp("--window=", arg, 9)) {
1263                                char *end;
1264                                window = strtoul(arg+9, &end, 0);
1265                                if (!arg[9] || *end)
1266                                        usage(pack_usage);
1267                                continue;
1268                        }
1269                        if (!strncmp("--depth=", arg, 8)) {
1270                                char *end;
1271                                depth = strtoul(arg+8, &end, 0);
1272                                if (!arg[8] || *end)
1273                                        usage(pack_usage);
1274                                continue;
1275                        }
1276                        if (!strcmp("--progress", arg)) {
1277                                progress = 1;
1278                                continue;
1279                        }
1280                        if (!strcmp("-q", arg)) {
1281                                progress = 0;
1282                                continue;
1283                        }
1284                        if (!strcmp("--no-reuse-delta", arg)) {
1285                                no_reuse_delta = 1;
1286                                continue;
1287                        }
1288                        if (!strcmp("--stdout", arg)) {
1289                                pack_to_stdout = 1;
1290                                continue;
1291                        }
1292                        usage(pack_usage);
1293                }
1294                if (base_name)
1295                        usage(pack_usage);
1296                base_name = arg;
1297        }
1298
1299        if (pack_to_stdout != !base_name)
1300                usage(pack_usage);
1301
1302        prepare_packed_git();
1303
1304        if (progress) {
1305                fprintf(stderr, "Generating pack...\n");
1306                setup_progress_signal();
1307        }
1308
1309        for (;;) {
1310                unsigned char sha1[20];
1311                unsigned hash;
1312
1313                if (!fgets(line, sizeof(line), stdin)) {
1314                        if (feof(stdin))
1315                                break;
1316                        if (!ferror(stdin))
1317                                die("fgets returned NULL, not EOF, not error!");
1318                        if (errno != EINTR)
1319                                die("fgets: %s", strerror(errno));
1320                        clearerr(stdin);
1321                        continue;
1322                }
1323
1324                if (line[0] == '-') {
1325                        if (get_sha1_hex(line+1, sha1))
1326                                die("expected edge sha1, got garbage:\n %s",
1327                                    line+1);
1328                        if (num_preferred_base++ < window)
1329                                add_preferred_base(sha1);
1330                        continue;
1331                }
1332                if (get_sha1_hex(line, sha1))
1333                        die("expected sha1, got garbage:\n %s", line);
1334                hash = name_hash(line+41);
1335                add_preferred_base_object(line+41, hash);
1336                add_object_entry(sha1, hash, 0);
1337        }
1338        if (progress)
1339                fprintf(stderr, "Done counting %d objects.\n", nr_objects);
1340        sorted_by_sha = create_final_object_list();
1341        if (non_empty && !nr_result)
1342                return 0;
1343
1344        SHA1_Init(&ctx);
1345        list = sorted_by_sha;
1346        for (i = 0; i < nr_result; i++) {
1347                struct object_entry *entry = *list++;
1348                SHA1_Update(&ctx, entry->sha1, 20);
1349        }
1350        SHA1_Final(object_list_sha1, &ctx);
1351        if (progress && (nr_objects != nr_result))
1352                fprintf(stderr, "Result has %d objects.\n", nr_result);
1353
1354        if (reuse_cached_pack(object_list_sha1, pack_to_stdout))
1355                ;
1356        else {
1357                if (nr_result)
1358                        prepare_pack(window, depth);
1359                if (progress && pack_to_stdout) {
1360                        /* the other end usually displays progress itself */
1361                        struct itimerval v = {{0,},};
1362                        setitimer(ITIMER_REAL, &v, NULL);
1363                        signal(SIGALRM, SIG_IGN );
1364                        progress_update = 0;
1365                }
1366                write_pack_file();
1367                if (!pack_to_stdout) {
1368                        write_index_file();
1369                        puts(sha1_to_hex(object_list_sha1));
1370                }
1371        }
1372        if (progress)
1373                fprintf(stderr, "Total %d, written %d (delta %d), reused %d (delta %d)\n",
1374                        nr_result, written, written_delta, reused, reused_delta);
1375        return 0;
1376}