pack-objects.con commit pack-objects: allow "thin" packs to exceed depth limits (b76f6b6)
   1#include "cache.h"
   2#include "object.h"
   3#include "delta.h"
   4#include "pack.h"
   5#include "csum-file.h"
   6#include "diff.h"
   7#include <sys/time.h>
   8
   9static const char pack_usage[] = "git-pack-objects [-q] [--no-reuse-delta] [--non-empty] [--local] [--incremental] [--window=N] [--depth=N] {--stdout | base-name} < object-list";
  10
  11struct object_entry {
  12        unsigned char sha1[20];
  13        unsigned long size;     /* uncompressed size */
  14        unsigned long offset;   /* offset into the final pack file;
  15                                 * nonzero if already written.
  16                                 */
  17        unsigned int depth;     /* delta depth */
  18        unsigned int delta_limit;       /* base adjustment for in-pack delta */
  19        unsigned int hash;      /* name hint hash */
  20        enum object_type type;
  21        enum object_type in_pack_type;  /* could be delta */
  22        unsigned long delta_size;       /* delta data size (uncompressed) */
  23        struct object_entry *delta;     /* delta base object */
  24        struct packed_git *in_pack;     /* already in pack */
  25        unsigned int in_pack_offset;
  26        struct object_entry *delta_child; /* delitified objects who bases me */
  27        struct object_entry *delta_sibling; /* other deltified objects who
  28                                             * uses the same base as me
  29                                             */
  30        int preferred_base;     /* we do not pack this, but is encouraged to
  31                                 * be used as the base objectto delta huge
  32                                 * objects against.
  33                                 */
  34        int based_on_preferred; /* current delta candidate is a preferred
  35                                 * one, or delta against a preferred one.
  36                                 */
  37};
  38
  39/*
  40 * Objects we are going to pack are colected in objects array (dynamically
  41 * expanded).  nr_objects & nr_alloc controls this array.  They are stored
  42 * in the order we see -- typically rev-list --objects order that gives us
  43 * nice "minimum seek" order.
  44 *
  45 * sorted-by-sha ans sorted-by-type are arrays of pointers that point at
  46 * elements in the objects array.  The former is used to build the pack
  47 * index (lists object names in the ascending order to help offset lookup),
  48 * and the latter is used to group similar things together by try_delta()
  49 * heuristics.
  50 */
  51
  52static unsigned char object_list_sha1[20];
  53static int non_empty = 0;
  54static int no_reuse_delta = 0;
  55static int local = 0;
  56static int incremental = 0;
  57static struct object_entry **sorted_by_sha, **sorted_by_type;
  58static struct object_entry *objects = NULL;
  59static int nr_objects = 0, nr_alloc = 0, nr_result = 0;
  60static const char *base_name;
  61static unsigned char pack_file_sha1[20];
  62static int progress = 1;
  63
  64/*
  65 * The object names in objects array are hashed with this hashtable,
  66 * to help looking up the entry by object name.  Binary search from
  67 * sorted_by_sha is also possible but this was easier to code and faster.
  68 * This hashtable is built after all the objects are seen.
  69 */
  70static int *object_ix = NULL;
  71static int object_ix_hashsz = 0;
  72
  73/*
  74 * Pack index for existing packs give us easy access to the offsets into
  75 * corresponding pack file where each object's data starts, but the entries
  76 * do not store the size of the compressed representation (uncompressed
  77 * size is easily available by examining the pack entry header).  We build
  78 * a hashtable of existing packs (pack_revindex), and keep reverse index
  79 * here -- pack index file is sorted by object name mapping to offset; this
  80 * pack_revindex[].revindex array is an ordered list of offsets, so if you
  81 * know the offset of an object, next offset is where its packed
  82 * representation ends.
  83 */
  84struct pack_revindex {
  85        struct packed_git *p;
  86        unsigned long *revindex;
  87} *pack_revindex = NULL;
  88static int pack_revindex_hashsz = 0;
  89
  90/*
  91 * stats
  92 */
  93static int written = 0;
  94static int written_delta = 0;
  95static int reused = 0;
  96static int reused_delta = 0;
  97
  98static int pack_revindex_ix(struct packed_git *p)
  99{
 100        unsigned int ui = (unsigned int) p;
 101        int i;
 102
 103        ui = ui ^ (ui >> 16); /* defeat structure alignment */
 104        i = (int)(ui % pack_revindex_hashsz);
 105        while (pack_revindex[i].p) {
 106                if (pack_revindex[i].p == p)
 107                        return i;
 108                if (++i == pack_revindex_hashsz)
 109                        i = 0;
 110        }
 111        return -1 - i;
 112}
 113
 114static void prepare_pack_ix(void)
 115{
 116        int num;
 117        struct packed_git *p;
 118        for (num = 0, p = packed_git; p; p = p->next)
 119                num++;
 120        if (!num)
 121                return;
 122        pack_revindex_hashsz = num * 11;
 123        pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
 124        for (p = packed_git; p; p = p->next) {
 125                num = pack_revindex_ix(p);
 126                num = - 1 - num;
 127                pack_revindex[num].p = p;
 128        }
 129        /* revindex elements are lazily initialized */
 130}
 131
 132static int cmp_offset(const void *a_, const void *b_)
 133{
 134        unsigned long a = *(unsigned long *) a_;
 135        unsigned long b = *(unsigned long *) b_;
 136        if (a < b)
 137                return -1;
 138        else if (a == b)
 139                return 0;
 140        else
 141                return 1;
 142}
 143
 144/*
 145 * Ordered list of offsets of objects in the pack.
 146 */
 147static void prepare_pack_revindex(struct pack_revindex *rix)
 148{
 149        struct packed_git *p = rix->p;
 150        int num_ent = num_packed_objects(p);
 151        int i;
 152        void *index = p->index_base + 256;
 153
 154        rix->revindex = xmalloc(sizeof(unsigned long) * (num_ent + 1));
 155        for (i = 0; i < num_ent; i++) {
 156                long hl = *((long *)(index + 24 * i));
 157                rix->revindex[i] = ntohl(hl);
 158        }
 159        /* This knows the pack format -- the 20-byte trailer
 160         * follows immediately after the last object data.
 161         */
 162        rix->revindex[num_ent] = p->pack_size - 20;
 163        qsort(rix->revindex, num_ent, sizeof(unsigned long), cmp_offset);
 164}
 165
 166static unsigned long find_packed_object_size(struct packed_git *p,
 167                                             unsigned long ofs)
 168{
 169        int num;
 170        int lo, hi;
 171        struct pack_revindex *rix;
 172        unsigned long *revindex;
 173        num = pack_revindex_ix(p);
 174        if (num < 0)
 175                die("internal error: pack revindex uninitialized");
 176        rix = &pack_revindex[num];
 177        if (!rix->revindex)
 178                prepare_pack_revindex(rix);
 179        revindex = rix->revindex;
 180        lo = 0;
 181        hi = num_packed_objects(p) + 1;
 182        do {
 183                int mi = (lo + hi) / 2;
 184                if (revindex[mi] == ofs) {
 185                        return revindex[mi+1] - ofs;
 186                }
 187                else if (ofs < revindex[mi])
 188                        hi = mi;
 189                else
 190                        lo = mi + 1;
 191        } while (lo < hi);
 192        die("internal error: pack revindex corrupt");
 193}
 194
 195static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
 196{
 197        unsigned long othersize, delta_size;
 198        char type[10];
 199        void *otherbuf = read_sha1_file(entry->delta->sha1, type, &othersize);
 200        void *delta_buf;
 201
 202        if (!otherbuf)
 203                die("unable to read %s", sha1_to_hex(entry->delta->sha1));
 204        delta_buf = diff_delta(otherbuf, othersize,
 205                               buf, size, &delta_size, 0);
 206        if (!delta_buf || delta_size != entry->delta_size)
 207                die("delta size changed");
 208        free(buf);
 209        free(otherbuf);
 210        return delta_buf;
 211}
 212
 213/*
 214 * The per-object header is a pretty dense thing, which is
 215 *  - first byte: low four bits are "size", then three bits of "type",
 216 *    and the high bit is "size continues".
 217 *  - each byte afterwards: low seven bits are size continuation,
 218 *    with the high bit being "size continues"
 219 */
 220static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
 221{
 222        int n = 1;
 223        unsigned char c;
 224
 225        if (type < OBJ_COMMIT || type > OBJ_DELTA)
 226                die("bad type %d", type);
 227
 228        c = (type << 4) | (size & 15);
 229        size >>= 4;
 230        while (size) {
 231                *hdr++ = c | 0x80;
 232                c = size & 0x7f;
 233                size >>= 7;
 234                n++;
 235        }
 236        *hdr = c;
 237        return n;
 238}
 239
 240static unsigned long write_object(struct sha1file *f,
 241                                  struct object_entry *entry)
 242{
 243        unsigned long size;
 244        char type[10];
 245        void *buf;
 246        unsigned char header[10];
 247        unsigned hdrlen, datalen;
 248        enum object_type obj_type;
 249        int to_reuse = 0;
 250
 251        if (entry->preferred_base)
 252                return 0;
 253
 254        obj_type = entry->type;
 255        if (! entry->in_pack)
 256                to_reuse = 0;   /* can't reuse what we don't have */
 257        else if (obj_type == OBJ_DELTA)
 258                to_reuse = 1;   /* check_object() decided it for us */
 259        else if (obj_type != entry->in_pack_type)
 260                to_reuse = 0;   /* pack has delta which is unusable */
 261        else if (entry->delta)
 262                to_reuse = 0;   /* we want to pack afresh */
 263        else
 264                to_reuse = 1;   /* we have it in-pack undeltified,
 265                                 * and we do not need to deltify it.
 266                                 */
 267
 268        if (! to_reuse) {
 269                buf = read_sha1_file(entry->sha1, type, &size);
 270                if (!buf)
 271                        die("unable to read %s", sha1_to_hex(entry->sha1));
 272                if (size != entry->size)
 273                        die("object %s size inconsistency (%lu vs %lu)",
 274                            sha1_to_hex(entry->sha1), size, entry->size);
 275                if (entry->delta) {
 276                        buf = delta_against(buf, size, entry);
 277                        size = entry->delta_size;
 278                        obj_type = OBJ_DELTA;
 279                }
 280                /*
 281                 * The object header is a byte of 'type' followed by zero or
 282                 * more bytes of length.  For deltas, the 20 bytes of delta
 283                 * sha1 follows that.
 284                 */
 285                hdrlen = encode_header(obj_type, size, header);
 286                sha1write(f, header, hdrlen);
 287
 288                if (entry->delta) {
 289                        sha1write(f, entry->delta, 20);
 290                        hdrlen += 20;
 291                }
 292                datalen = sha1write_compressed(f, buf, size);
 293                free(buf);
 294        }
 295        else {
 296                struct packed_git *p = entry->in_pack;
 297                use_packed_git(p);
 298
 299                datalen = find_packed_object_size(p, entry->in_pack_offset);
 300                buf = p->pack_base + entry->in_pack_offset;
 301                sha1write(f, buf, datalen);
 302                unuse_packed_git(p);
 303                hdrlen = 0; /* not really */
 304                if (obj_type == OBJ_DELTA)
 305                        reused_delta++;
 306                reused++;
 307        }
 308        if (obj_type == OBJ_DELTA)
 309                written_delta++;
 310        written++;
 311        return hdrlen + datalen;
 312}
 313
 314static unsigned long write_one(struct sha1file *f,
 315                               struct object_entry *e,
 316                               unsigned long offset)
 317{
 318        if (e->offset)
 319                /* offset starts from header size and cannot be zero
 320                 * if it is written already.
 321                 */
 322                return offset;
 323        e->offset = offset;
 324        offset += write_object(f, e);
 325        /* if we are deltified, write out its base object. */
 326        if (e->delta)
 327                offset = write_one(f, e->delta, offset);
 328        return offset;
 329}
 330
 331static void write_pack_file(void)
 332{
 333        int i;
 334        struct sha1file *f;
 335        unsigned long offset;
 336        struct pack_header hdr;
 337
 338        if (!base_name)
 339                f = sha1fd(1, "<stdout>");
 340        else
 341                f = sha1create("%s-%s.%s", base_name,
 342                               sha1_to_hex(object_list_sha1), "pack");
 343        hdr.hdr_signature = htonl(PACK_SIGNATURE);
 344        hdr.hdr_version = htonl(PACK_VERSION);
 345        hdr.hdr_entries = htonl(nr_result);
 346        sha1write(f, &hdr, sizeof(hdr));
 347        offset = sizeof(hdr);
 348        for (i = 0; i < nr_objects; i++)
 349                offset = write_one(f, objects + i, offset);
 350
 351        sha1close(f, pack_file_sha1, 1);
 352}
 353
 354static void write_index_file(void)
 355{
 356        int i;
 357        struct sha1file *f = sha1create("%s-%s.%s", base_name,
 358                                        sha1_to_hex(object_list_sha1), "idx");
 359        struct object_entry **list = sorted_by_sha;
 360        struct object_entry **last = list + nr_result;
 361        unsigned int array[256];
 362
 363        /*
 364         * Write the first-level table (the list is sorted,
 365         * but we use a 256-entry lookup to be able to avoid
 366         * having to do eight extra binary search iterations).
 367         */
 368        for (i = 0; i < 256; i++) {
 369                struct object_entry **next = list;
 370                while (next < last) {
 371                        struct object_entry *entry = *next;
 372                        if (entry->sha1[0] != i)
 373                                break;
 374                        next++;
 375                }
 376                array[i] = htonl(next - sorted_by_sha);
 377                list = next;
 378        }
 379        sha1write(f, array, 256 * sizeof(int));
 380
 381        /*
 382         * Write the actual SHA1 entries..
 383         */
 384        list = sorted_by_sha;
 385        for (i = 0; i < nr_result; i++) {
 386                struct object_entry *entry = *list++;
 387                unsigned int offset = htonl(entry->offset);
 388                sha1write(f, &offset, 4);
 389                sha1write(f, entry->sha1, 20);
 390        }
 391        sha1write(f, pack_file_sha1, 20);
 392        sha1close(f, NULL, 1);
 393}
 394
 395static int locate_object_entry_hash(const unsigned char *sha1)
 396{
 397        int i;
 398        unsigned int ui;
 399        memcpy(&ui, sha1, sizeof(unsigned int));
 400        i = ui % object_ix_hashsz;
 401        while (0 < object_ix[i]) {
 402                if (!memcmp(sha1, objects[object_ix[i]-1].sha1, 20))
 403                        return i;
 404                if (++i == object_ix_hashsz)
 405                        i = 0;
 406        }
 407        return -1 - i;
 408}
 409
 410static struct object_entry *locate_object_entry(const unsigned char *sha1)
 411{
 412        int i;
 413
 414        if (!object_ix_hashsz)
 415                return NULL;
 416
 417        i = locate_object_entry_hash(sha1);
 418        if (0 <= i)
 419                return &objects[object_ix[i]-1];
 420        return NULL;
 421}
 422
 423static void rehash_objects(void)
 424{
 425        int i;
 426        struct object_entry *oe;
 427
 428        object_ix_hashsz = nr_objects * 3;
 429        if (object_ix_hashsz < 1024)
 430                object_ix_hashsz = 1024;
 431        object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
 432        object_ix = memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
 433        for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
 434                int ix = locate_object_entry_hash(oe->sha1);
 435                if (0 <= ix)
 436                        continue;
 437                ix = -1 - ix;
 438                object_ix[ix] = i + 1;
 439        }
 440}
 441
 442struct name_path {
 443        struct name_path *up;
 444        const char *elem;
 445        int len;
 446};
 447
 448static unsigned name_hash(struct name_path *path, const char *name)
 449{
 450        struct name_path *p = path;
 451        const char *n = name + strlen(name);
 452        unsigned hash = 0;
 453
 454        if (n != name && n[-1] == '\n')
 455                n--;
 456        while (name <= --n) {
 457                unsigned char c = *n;
 458                hash = hash * 11 + c;
 459        }
 460        for (p = path; p; p = p->up) {
 461                hash = hash * 11 + '/';
 462                n = p->elem + p->len;
 463                while (p->elem <= --n) {
 464                        unsigned char c = *n;
 465                        hash = hash * 11 + c;
 466                }
 467        }
 468        return hash;
 469}
 470
 471static int add_object_entry(const unsigned char *sha1, unsigned hash, int exclude)
 472{
 473        unsigned int idx = nr_objects;
 474        struct object_entry *entry;
 475        struct packed_git *p;
 476        unsigned int found_offset = 0;
 477        struct packed_git *found_pack = NULL;
 478        int ix, status = 0;
 479
 480        if (!exclude) {
 481                for (p = packed_git; p; p = p->next) {
 482                        struct pack_entry e;
 483                        if (find_pack_entry_one(sha1, &e, p)) {
 484                                if (incremental)
 485                                        return 0;
 486                                if (local && !p->pack_local)
 487                                        return 0;
 488                                if (!found_pack) {
 489                                        found_offset = e.offset;
 490                                        found_pack = e.p;
 491                                }
 492                        }
 493                }
 494        }
 495        if ((entry = locate_object_entry(sha1)) != NULL)
 496                goto already_added;
 497
 498        if (idx >= nr_alloc) {
 499                unsigned int needed = (idx + 1024) * 3 / 2;
 500                objects = xrealloc(objects, needed * sizeof(*entry));
 501                nr_alloc = needed;
 502        }
 503        entry = objects + idx;
 504        nr_objects = idx + 1;
 505        memset(entry, 0, sizeof(*entry));
 506        memcpy(entry->sha1, sha1, 20);
 507        entry->hash = hash;
 508
 509        if (object_ix_hashsz * 3 <= nr_objects * 4)
 510                rehash_objects();
 511        else {
 512                ix = locate_object_entry_hash(entry->sha1);
 513                if (0 <= ix)
 514                        die("internal error in object hashing.");
 515                object_ix[-1 - ix] = idx + 1;
 516        }
 517        status = 1;
 518
 519 already_added:
 520        if (exclude)
 521                entry->preferred_base = 1;
 522        else {
 523                if (found_pack) {
 524                        entry->in_pack = found_pack;
 525                        entry->in_pack_offset = found_offset;
 526                }
 527        }
 528        return status;
 529}
 530
 531static void add_pbase_tree(struct tree_desc *tree, struct name_path *up)
 532{
 533        while (tree->size) {
 534                const unsigned char *sha1;
 535                const char *name;
 536                unsigned mode, hash;
 537                unsigned long size;
 538                char type[20];
 539
 540                sha1 = tree_entry_extract(tree, &name, &mode);
 541                update_tree_entry(tree);
 542                if (!has_sha1_file(sha1))
 543                        continue;
 544                if (sha1_object_info(sha1, type, &size))
 545                        continue;
 546
 547                hash = name_hash(up, name);
 548                if (!add_object_entry(sha1, hash, 1))
 549                        continue;
 550
 551                if (!strcmp(type, "tree")) {
 552                        struct tree_desc sub;
 553                        void *elem;
 554                        struct name_path me;
 555
 556                        elem = read_sha1_file(sha1, type, &sub.size);
 557                        sub.buf = elem;
 558                        if (sub.buf) {
 559                                me.up = up;
 560                                me.elem = name;
 561                                me.len = strlen(name);
 562                                add_pbase_tree(&sub, &me);
 563                                free(elem);
 564                        }
 565                }
 566        }
 567}
 568
 569static void add_preferred_base(unsigned char *sha1)
 570{
 571        struct tree_desc tree;
 572        void *elem;
 573
 574        elem = read_object_with_reference(sha1, "tree", &tree.size, NULL);
 575        tree.buf = elem;
 576        if (!tree.buf)
 577                return;
 578        if (add_object_entry(sha1, name_hash(NULL, ""), 1))
 579                add_pbase_tree(&tree, NULL);
 580        free(elem);
 581}
 582
 583static void check_object(struct object_entry *entry)
 584{
 585        char type[20];
 586
 587        if (entry->in_pack && !entry->preferred_base) {
 588                unsigned char base[20];
 589                unsigned long size;
 590                struct object_entry *base_entry;
 591
 592                /* We want in_pack_type even if we do not reuse delta.
 593                 * There is no point not reusing non-delta representations.
 594                 */
 595                check_reuse_pack_delta(entry->in_pack,
 596                                       entry->in_pack_offset,
 597                                       base, &size,
 598                                       &entry->in_pack_type);
 599
 600                /* Check if it is delta, and the base is also an object
 601                 * we are going to pack.  If so we will reuse the existing
 602                 * delta.
 603                 */
 604                if (!no_reuse_delta &&
 605                    entry->in_pack_type == OBJ_DELTA &&
 606                    (base_entry = locate_object_entry(base)) &&
 607                    (!base_entry->preferred_base)) {
 608
 609                        /* Depth value does not matter - find_deltas()
 610                         * will never consider reused delta as the
 611                         * base object to deltify other objects
 612                         * against, in order to avoid circular deltas.
 613                         */
 614
 615                        /* uncompressed size of the delta data */
 616                        entry->size = entry->delta_size = size;
 617                        entry->delta = base_entry;
 618                        entry->type = OBJ_DELTA;
 619
 620                        entry->delta_sibling = base_entry->delta_child;
 621                        base_entry->delta_child = entry;
 622
 623                        return;
 624                }
 625                /* Otherwise we would do the usual */
 626        }
 627
 628        if (sha1_object_info(entry->sha1, type, &entry->size))
 629                die("unable to get type of object %s",
 630                    sha1_to_hex(entry->sha1));
 631
 632        if (!strcmp(type, "commit")) {
 633                entry->type = OBJ_COMMIT;
 634        } else if (!strcmp(type, "tree")) {
 635                entry->type = OBJ_TREE;
 636        } else if (!strcmp(type, "blob")) {
 637                entry->type = OBJ_BLOB;
 638        } else if (!strcmp(type, "tag")) {
 639                entry->type = OBJ_TAG;
 640        } else
 641                die("unable to pack object %s of type %s",
 642                    sha1_to_hex(entry->sha1), type);
 643}
 644
 645static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
 646{
 647        struct object_entry *child = me->delta_child;
 648        unsigned int m = n;
 649        while (child) {
 650                unsigned int c = check_delta_limit(child, n + 1);
 651                if (m < c)
 652                        m = c;
 653                child = child->delta_sibling;
 654        }
 655        return m;
 656}
 657
 658static void get_object_details(void)
 659{
 660        int i;
 661        struct object_entry *entry;
 662
 663        prepare_pack_ix();
 664        for (i = 0, entry = objects; i < nr_objects; i++, entry++)
 665                check_object(entry);
 666
 667        if (nr_objects == nr_result) {
 668                /*
 669                 * Depth of objects that depend on the entry -- this
 670                 * is subtracted from depth-max to break too deep
 671                 * delta chain because of delta data reusing.
 672                 * However, we loosen this restriction when we know we
 673                 * are creating a thin pack -- it will have to be
 674                 * expanded on the other end anyway, so do not
 675                 * artificially cut the delta chain and let it go as
 676                 * deep as it wants.
 677                 */
 678                for (i = 0, entry = objects; i < nr_objects; i++, entry++)
 679                        if (!entry->delta && entry->delta_child)
 680                                entry->delta_limit =
 681                                        check_delta_limit(entry, 1);
 682        }
 683}
 684
 685typedef int (*entry_sort_t)(const struct object_entry *, const struct object_entry *);
 686
 687static entry_sort_t current_sort;
 688
 689static int sort_comparator(const void *_a, const void *_b)
 690{
 691        struct object_entry *a = *(struct object_entry **)_a;
 692        struct object_entry *b = *(struct object_entry **)_b;
 693        return current_sort(a,b);
 694}
 695
 696static struct object_entry **create_sorted_list(entry_sort_t sort)
 697{
 698        struct object_entry **list = xmalloc(nr_objects * sizeof(struct object_entry *));
 699        int i;
 700
 701        for (i = 0; i < nr_objects; i++)
 702                list[i] = objects + i;
 703        current_sort = sort;
 704        qsort(list, nr_objects, sizeof(struct object_entry *), sort_comparator);
 705        return list;
 706}
 707
 708static int sha1_sort(const struct object_entry *a, const struct object_entry *b)
 709{
 710        return memcmp(a->sha1, b->sha1, 20);
 711}
 712
 713static struct object_entry **create_final_object_list()
 714{
 715        struct object_entry **list;
 716        int i, j;
 717
 718        for (i = nr_result = 0; i < nr_objects; i++)
 719                if (!objects[i].preferred_base)
 720                        nr_result++;
 721        list = xmalloc(nr_result * sizeof(struct object_entry *));
 722        for (i = j = 0; i < nr_objects; i++) {
 723                if (!objects[i].preferred_base)
 724                        list[j++] = objects + i;
 725        }
 726        current_sort = sha1_sort;
 727        qsort(list, nr_result, sizeof(struct object_entry *), sort_comparator);
 728        return list;
 729}
 730
 731static int type_size_sort(const struct object_entry *a, const struct object_entry *b)
 732{
 733        if (a->type < b->type)
 734                return -1;
 735        if (a->type > b->type)
 736                return 1;
 737        if (a->hash < b->hash)
 738                return -1;
 739        if (a->hash > b->hash)
 740                return 1;
 741        if (a->preferred_base < b->preferred_base)
 742                return -1;
 743        if (a->preferred_base > b->preferred_base)
 744                return 1;
 745        if (a->size < b->size)
 746                return -1;
 747        if (a->size > b->size)
 748                return 1;
 749        return a < b ? -1 : (a > b);
 750}
 751
 752struct unpacked {
 753        struct object_entry *entry;
 754        void *data;
 755};
 756
 757/*
 758 * We search for deltas _backwards_ in a list sorted by type and
 759 * by size, so that we see progressively smaller and smaller files.
 760 * That's because we prefer deltas to be from the bigger file
 761 * to the smaller - deletes are potentially cheaper, but perhaps
 762 * more importantly, the bigger file is likely the more recent
 763 * one.
 764 */
 765static int try_delta(struct unpacked *cur, struct unpacked *old, unsigned max_depth)
 766{
 767        struct object_entry *cur_entry = cur->entry;
 768        struct object_entry *old_entry = old->entry;
 769        int old_preferred = (old_entry->preferred_base ||
 770                             old_entry->based_on_preferred);
 771        unsigned long size, oldsize, delta_size, sizediff;
 772        long max_size;
 773        void *delta_buf;
 774
 775        /* Don't bother doing diffs between different types */
 776        if (cur_entry->type != old_entry->type)
 777                return -1;
 778
 779        /* We do not compute delta to *create* objects we are not
 780         * going to pack.
 781         */
 782        if (cur_entry->preferred_base)
 783                return -1;
 784
 785        /* If the current object is at pack edge, take the depth the
 786         * objects that depend on the current object into account --
 787         * otherwise they would become too deep.
 788         */
 789        if (cur_entry->delta_child) {
 790                if (max_depth <= cur_entry->delta_limit)
 791                        return 0;
 792                max_depth -= cur_entry->delta_limit;
 793        }
 794
 795        size = cur_entry->size;
 796        if (size < 50)
 797                return -1;
 798        oldsize = old_entry->size;
 799        sizediff = oldsize > size ? oldsize - size : size - oldsize;
 800        if (sizediff > size / 8)
 801                return -1;
 802        if (old_entry->depth >= max_depth)
 803                return 0;
 804
 805        /*
 806         * NOTE!
 807         *
 808         * We always delta from the bigger to the smaller, since that's
 809         * more space-efficient (deletes don't have to say _what_ they
 810         * delete).
 811         */
 812        max_size = size / 2 - 20;
 813        if (cur_entry->delta) {
 814                if (cur_entry->based_on_preferred) {
 815                        if (old_preferred)
 816                                max_size = cur_entry->delta_size-1;
 817                        else
 818                                /* trying with non-preferred one when we
 819                                 * already have a delta based on preferred
 820                                 * one is pointless.
 821                                 */
 822                                return -1;
 823                }
 824                else if (!old_preferred)
 825                        max_size = cur_entry->delta_size-1;
 826                else
 827                        /* otherwise...  even if delta with a
 828                         * preferred one produces a bigger result than
 829                         * what we currently have, which is based on a
 830                         * non-preferred one, it is OK.
 831                         */
 832                        ;
 833        }
 834        if (sizediff >= max_size)
 835                return -1;
 836        delta_buf = diff_delta(old->data, oldsize,
 837                               cur->data, size, &delta_size, max_size);
 838        if (!delta_buf)
 839                return 0;
 840        cur_entry->delta = old_entry;
 841        cur_entry->delta_size = delta_size;
 842        cur_entry->depth = old_entry->depth + 1;
 843        cur_entry->based_on_preferred = old_preferred;
 844        free(delta_buf);
 845        return 0;
 846}
 847
 848static void find_deltas(struct object_entry **list, int window, int depth)
 849{
 850        int i, idx;
 851        unsigned int array_size = window * sizeof(struct unpacked);
 852        struct unpacked *array = xmalloc(array_size);
 853        int eye_candy;
 854
 855        memset(array, 0, array_size);
 856        i = nr_objects;
 857        idx = 0;
 858        eye_candy = i - (nr_objects / 20);
 859
 860        while (--i >= 0) {
 861                struct object_entry *entry = list[i];
 862                struct unpacked *n = array + idx;
 863                unsigned long size;
 864                char type[10];
 865                int j;
 866
 867                if (progress && i <= eye_candy) {
 868                        eye_candy -= nr_objects / 20;
 869                        fputc('.', stderr);
 870                }
 871
 872                if (entry->delta)
 873                        /* This happens if we decided to reuse existing
 874                         * delta from a pack.  "!no_reuse_delta &&" is implied.
 875                         */
 876                        continue;
 877
 878                free(n->data);
 879                n->entry = entry;
 880                n->data = read_sha1_file(entry->sha1, type, &size);
 881                if (size != entry->size)
 882                        die("object %s inconsistent object length (%lu vs %lu)", sha1_to_hex(entry->sha1), size, entry->size);
 883
 884                j = window;
 885                while (--j > 0) {
 886                        unsigned int other_idx = idx + j;
 887                        struct unpacked *m;
 888                        if (other_idx >= window)
 889                                other_idx -= window;
 890                        m = array + other_idx;
 891                        if (!m->entry)
 892                                break;
 893                        if (try_delta(n, m, depth) < 0)
 894                                break;
 895                }
 896                idx++;
 897                if (idx >= window)
 898                        idx = 0;
 899        }
 900
 901        for (i = 0; i < window; ++i)
 902                free(array[i].data);
 903        free(array);
 904}
 905
 906static void prepare_pack(int window, int depth)
 907{
 908        if (progress)
 909                fprintf(stderr, "Packing %d objects", nr_result);
 910        get_object_details();
 911        if (progress)
 912                fputc('.', stderr);
 913
 914        sorted_by_type = create_sorted_list(type_size_sort);
 915        if (window && depth)
 916                find_deltas(sorted_by_type, window+1, depth);
 917        if (progress)
 918                fputc('\n', stderr);
 919        write_pack_file();
 920}
 921
 922static int reuse_cached_pack(unsigned char *sha1, int pack_to_stdout)
 923{
 924        static const char cache[] = "pack-cache/pack-%s.%s";
 925        char *cached_pack, *cached_idx;
 926        int ifd, ofd, ifd_ix = -1;
 927
 928        cached_pack = git_path(cache, sha1_to_hex(sha1), "pack");
 929        ifd = open(cached_pack, O_RDONLY);
 930        if (ifd < 0)
 931                return 0;
 932
 933        if (!pack_to_stdout) {
 934                cached_idx = git_path(cache, sha1_to_hex(sha1), "idx");
 935                ifd_ix = open(cached_idx, O_RDONLY);
 936                if (ifd_ix < 0) {
 937                        close(ifd);
 938                        return 0;
 939                }
 940        }
 941
 942        if (progress)
 943                fprintf(stderr, "Reusing %d objects pack %s\n", nr_objects,
 944                        sha1_to_hex(sha1));
 945
 946        if (pack_to_stdout) {
 947                if (copy_fd(ifd, 1))
 948                        exit(1);
 949                close(ifd);
 950        }
 951        else {
 952                char name[PATH_MAX];
 953                snprintf(name, sizeof(name),
 954                         "%s-%s.%s", base_name, sha1_to_hex(sha1), "pack");
 955                ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
 956                if (ofd < 0)
 957                        die("unable to open %s (%s)", name, strerror(errno));
 958                if (copy_fd(ifd, ofd))
 959                        exit(1);
 960                close(ifd);
 961
 962                snprintf(name, sizeof(name),
 963                         "%s-%s.%s", base_name, sha1_to_hex(sha1), "idx");
 964                ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
 965                if (ofd < 0)
 966                        die("unable to open %s (%s)", name, strerror(errno));
 967                if (copy_fd(ifd_ix, ofd))
 968                        exit(1);
 969                close(ifd_ix);
 970                puts(sha1_to_hex(sha1));
 971        }
 972
 973        return 1;
 974}
 975
 976int main(int argc, char **argv)
 977{
 978        SHA_CTX ctx;
 979        char line[PATH_MAX + 20];
 980        int window = 10, depth = 10, pack_to_stdout = 0;
 981        struct object_entry **list;
 982        int i;
 983        struct timeval prev_tv;
 984        int eye_candy = 0;
 985        int eye_candy_incr = 500;
 986
 987
 988        setup_git_directory();
 989
 990        for (i = 1; i < argc; i++) {
 991                const char *arg = argv[i];
 992
 993                if (*arg == '-') {
 994                        if (!strcmp("--non-empty", arg)) {
 995                                non_empty = 1;
 996                                continue;
 997                        }
 998                        if (!strcmp("--local", arg)) {
 999                                local = 1;
1000                                continue;
1001                        }
1002                        if (!strcmp("--incremental", arg)) {
1003                                incremental = 1;
1004                                continue;
1005                        }
1006                        if (!strncmp("--window=", arg, 9)) {
1007                                char *end;
1008                                window = strtoul(arg+9, &end, 0);
1009                                if (!arg[9] || *end)
1010                                        usage(pack_usage);
1011                                continue;
1012                        }
1013                        if (!strncmp("--depth=", arg, 8)) {
1014                                char *end;
1015                                depth = strtoul(arg+8, &end, 0);
1016                                if (!arg[8] || *end)
1017                                        usage(pack_usage);
1018                                continue;
1019                        }
1020                        if (!strcmp("-q", arg)) {
1021                                progress = 0;
1022                                continue;
1023                        }
1024                        if (!strcmp("--no-reuse-delta", arg)) {
1025                                no_reuse_delta = 1;
1026                                continue;
1027                        }
1028                        if (!strcmp("--stdout", arg)) {
1029                                pack_to_stdout = 1;
1030                                continue;
1031                        }
1032                        usage(pack_usage);
1033                }
1034                if (base_name)
1035                        usage(pack_usage);
1036                base_name = arg;
1037        }
1038
1039        if (pack_to_stdout != !base_name)
1040                usage(pack_usage);
1041
1042        prepare_packed_git();
1043        if (progress) {
1044                fprintf(stderr, "Generating pack...\n");
1045                gettimeofday(&prev_tv, NULL);
1046        }
1047        while (fgets(line, sizeof(line), stdin) != NULL) {
1048                unsigned char sha1[20];
1049
1050                if (progress && (eye_candy <= nr_objects)) {
1051                        fprintf(stderr, "Counting objects...%d\r", nr_objects);
1052                        if (eye_candy && (50 <= eye_candy_incr)) {
1053                                struct timeval tv;
1054                                int time_diff;
1055                                gettimeofday(&tv, NULL);
1056                                time_diff = (tv.tv_sec - prev_tv.tv_sec);
1057                                time_diff <<= 10;
1058                                time_diff += (tv.tv_usec - prev_tv.tv_usec);
1059                                if ((1 << 9) < time_diff)
1060                                        eye_candy_incr += 50;
1061                                else if (50 < eye_candy_incr)
1062                                        eye_candy_incr -= 50;
1063                        }
1064                        eye_candy += eye_candy_incr;
1065                }
1066                if (line[0] == '-') {
1067                        if (get_sha1_hex(line+1, sha1))
1068                                die("expected edge sha1, got garbage:\n %s",
1069                                    line+1);
1070                        add_preferred_base(sha1);
1071                        continue;
1072                }
1073                if (get_sha1_hex(line, sha1))
1074                        die("expected sha1, got garbage:\n %s", line);
1075                add_object_entry(sha1, name_hash(NULL, line+41), 0);
1076        }
1077        if (progress)
1078                fprintf(stderr, "Done counting %d objects.\n", nr_objects);
1079        if (non_empty && !nr_objects)
1080                return 0;
1081
1082        sorted_by_sha = create_final_object_list();
1083        SHA1_Init(&ctx);
1084        list = sorted_by_sha;
1085        for (i = 0; i < nr_result; i++) {
1086                struct object_entry *entry = *list++;
1087                SHA1_Update(&ctx, entry->sha1, 20);
1088        }
1089        SHA1_Final(object_list_sha1, &ctx);
1090        if (progress && (nr_objects != nr_result))
1091                fprintf(stderr, "Result has %d objects.\n", nr_result);
1092
1093        if (reuse_cached_pack(object_list_sha1, pack_to_stdout))
1094                ;
1095        else {
1096                prepare_pack(window, depth);
1097                if (!pack_to_stdout) {
1098                        write_index_file();
1099                        puts(sha1_to_hex(object_list_sha1));
1100                }
1101        }
1102        if (progress)
1103                fprintf(stderr, "Total %d, written %d (delta %d), reused %d (delta %d)\n",
1104                        nr_result, written, written_delta, reused, reused_delta);
1105        return 0;
1106}