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