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