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