builtin-pack-objects.con commit Merge branch 'js/read-tree' (eb45415)
   1#include "builtin.h"
   2#include "cache.h"
   3#include "object.h"
   4#include "blob.h"
   5#include "commit.h"
   6#include "tag.h"
   7#include "tree.h"
   8#include "delta.h"
   9#include "pack.h"
  10#include "csum-file.h"
  11#include "tree-walk.h"
  12#include <sys/time.h>
  13#include <signal.h>
  14
  15static const char pack_usage[] = "git-pack-objects [-q] [--no-reuse-delta] [--non-empty] [--local] [--incremental] [--window=N] [--depth=N] {--stdout | base-name} < object-list";
  16
  17struct object_entry {
  18        unsigned char sha1[20];
  19        unsigned long size;     /* uncompressed size */
  20        unsigned long offset;   /* offset into the final pack file;
  21                                 * nonzero if already written.
  22                                 */
  23        unsigned int depth;     /* delta depth */
  24        unsigned int delta_limit;       /* base adjustment for in-pack delta */
  25        unsigned int hash;      /* name hint hash */
  26        enum object_type type;
  27        enum object_type in_pack_type;  /* could be delta */
  28        unsigned long delta_size;       /* delta data size (uncompressed) */
  29        struct object_entry *delta;     /* delta base object */
  30        struct packed_git *in_pack;     /* already in pack */
  31        unsigned int in_pack_offset;
  32        struct object_entry *delta_child; /* deltified objects who bases me */
  33        struct object_entry *delta_sibling; /* other deltified objects who
  34                                             * uses the same base as me
  35                                             */
  36        int preferred_base;     /* we do not pack this, but is encouraged to
  37                                 * be used as the base objectto delta huge
  38                                 * objects against.
  39                                 */
  40};
  41
  42/*
  43 * Objects we are going to pack are collected in objects array (dynamically
  44 * expanded).  nr_objects & nr_alloc controls this array.  They are stored
  45 * in the order we see -- typically rev-list --objects order that gives us
  46 * nice "minimum seek" order.
  47 *
  48 * sorted-by-sha ans sorted-by-type are arrays of pointers that point at
  49 * elements in the objects array.  The former is used to build the pack
  50 * index (lists object names in the ascending order to help offset lookup),
  51 * and the latter is used to group similar things together by try_delta()
  52 * heuristics.
  53 */
  54
  55static unsigned char object_list_sha1[20];
  56static int non_empty = 0;
  57static int no_reuse_delta = 0;
  58static int local = 0;
  59static int incremental = 0;
  60static struct object_entry **sorted_by_sha, **sorted_by_type;
  61static struct object_entry *objects = NULL;
  62static int nr_objects = 0, nr_alloc = 0, nr_result = 0;
  63static const char *base_name;
  64static unsigned char pack_file_sha1[20];
  65static int progress = 1;
  66static volatile sig_atomic_t progress_update = 0;
  67static int window = 10;
  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                unsigned int hl = *((unsigned int *)((char *) 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 = (char *) 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
 468static unsigned name_hash(const char *name)
 469{
 470        unsigned char c;
 471        unsigned hash = 0;
 472
 473        /*
 474         * This effectively just creates a sortable number from the
 475         * last sixteen non-whitespace characters. Last characters
 476         * count "most", so things that end in ".c" sort together.
 477         */
 478        while ((c = *name++) != 0) {
 479                if (isspace(c))
 480                        continue;
 481                hash = (hash >> 2) + (c << 24);
 482        }
 483        return hash;
 484}
 485
 486static int add_object_entry(const unsigned char *sha1, unsigned hash, int exclude)
 487{
 488        unsigned int idx = nr_objects;
 489        struct object_entry *entry;
 490        struct packed_git *p;
 491        unsigned int found_offset = 0;
 492        struct packed_git *found_pack = NULL;
 493        int ix, status = 0;
 494
 495        if (!exclude) {
 496                for (p = packed_git; p; p = p->next) {
 497                        struct pack_entry e;
 498                        if (find_pack_entry_one(sha1, &e, p)) {
 499                                if (incremental)
 500                                        return 0;
 501                                if (local && !p->pack_local)
 502                                        return 0;
 503                                if (!found_pack) {
 504                                        found_offset = e.offset;
 505                                        found_pack = e.p;
 506                                }
 507                        }
 508                }
 509        }
 510        if ((entry = locate_object_entry(sha1)) != NULL)
 511                goto already_added;
 512
 513        if (idx >= nr_alloc) {
 514                unsigned int needed = (idx + 1024) * 3 / 2;
 515                objects = xrealloc(objects, needed * sizeof(*entry));
 516                nr_alloc = needed;
 517        }
 518        entry = objects + idx;
 519        nr_objects = idx + 1;
 520        memset(entry, 0, sizeof(*entry));
 521        memcpy(entry->sha1, sha1, 20);
 522        entry->hash = hash;
 523
 524        if (object_ix_hashsz * 3 <= nr_objects * 4)
 525                rehash_objects();
 526        else {
 527                ix = locate_object_entry_hash(entry->sha1);
 528                if (0 <= ix)
 529                        die("internal error in object hashing.");
 530                object_ix[-1 - ix] = idx + 1;
 531        }
 532        status = 1;
 533
 534 already_added:
 535        if (progress_update) {
 536                fprintf(stderr, "Counting objects...%d\r", nr_objects);
 537                progress_update = 0;
 538        }
 539        if (exclude)
 540                entry->preferred_base = 1;
 541        else {
 542                if (found_pack) {
 543                        entry->in_pack = found_pack;
 544                        entry->in_pack_offset = found_offset;
 545                }
 546        }
 547        return status;
 548}
 549
 550struct pbase_tree_cache {
 551        unsigned char sha1[20];
 552        int ref;
 553        int temporary;
 554        void *tree_data;
 555        unsigned long tree_size;
 556};
 557
 558static struct pbase_tree_cache *(pbase_tree_cache[256]);
 559static int pbase_tree_cache_ix(const unsigned char *sha1)
 560{
 561        return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
 562}
 563static int pbase_tree_cache_ix_incr(int ix)
 564{
 565        return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
 566}
 567
 568static struct pbase_tree {
 569        struct pbase_tree *next;
 570        /* This is a phony "cache" entry; we are not
 571         * going to evict it nor find it through _get()
 572         * mechanism -- this is for the toplevel node that
 573         * would almost always change with any commit.
 574         */
 575        struct pbase_tree_cache pcache;
 576} *pbase_tree;
 577
 578static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
 579{
 580        struct pbase_tree_cache *ent, *nent;
 581        void *data;
 582        unsigned long size;
 583        char type[20];
 584        int neigh;
 585        int my_ix = pbase_tree_cache_ix(sha1);
 586        int available_ix = -1;
 587
 588        /* pbase-tree-cache acts as a limited hashtable.
 589         * your object will be found at your index or within a few
 590         * slots after that slot if it is cached.
 591         */
 592        for (neigh = 0; neigh < 8; neigh++) {
 593                ent = pbase_tree_cache[my_ix];
 594                if (ent && !memcmp(ent->sha1, sha1, 20)) {
 595                        ent->ref++;
 596                        return ent;
 597                }
 598                else if (((available_ix < 0) && (!ent || !ent->ref)) ||
 599                         ((0 <= available_ix) &&
 600                          (!ent && pbase_tree_cache[available_ix])))
 601                        available_ix = my_ix;
 602                if (!ent)
 603                        break;
 604                my_ix = pbase_tree_cache_ix_incr(my_ix);
 605        }
 606
 607        /* Did not find one.  Either we got a bogus request or
 608         * we need to read and perhaps cache.
 609         */
 610        data = read_sha1_file(sha1, type, &size);
 611        if (!data)
 612                return NULL;
 613        if (strcmp(type, tree_type)) {
 614                free(data);
 615                return NULL;
 616        }
 617
 618        /* We need to either cache or return a throwaway copy */
 619
 620        if (available_ix < 0)
 621                ent = NULL;
 622        else {
 623                ent = pbase_tree_cache[available_ix];
 624                my_ix = available_ix;
 625        }
 626
 627        if (!ent) {
 628                nent = xmalloc(sizeof(*nent));
 629                nent->temporary = (available_ix < 0);
 630        }
 631        else {
 632                /* evict and reuse */
 633                free(ent->tree_data);
 634                nent = ent;
 635        }
 636        memcpy(nent->sha1, sha1, 20);
 637        nent->tree_data = data;
 638        nent->tree_size = size;
 639        nent->ref = 1;
 640        if (!nent->temporary)
 641                pbase_tree_cache[my_ix] = nent;
 642        return nent;
 643}
 644
 645static void pbase_tree_put(struct pbase_tree_cache *cache)
 646{
 647        if (!cache->temporary) {
 648                cache->ref--;
 649                return;
 650        }
 651        free(cache->tree_data);
 652        free(cache);
 653}
 654
 655static int name_cmp_len(const char *name)
 656{
 657        int i;
 658        for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
 659                ;
 660        return i;
 661}
 662
 663static void add_pbase_object(struct tree_desc *tree,
 664                             const char *name,
 665                             int cmplen,
 666                             const char *fullname)
 667{
 668        struct name_entry entry;
 669
 670        while (tree_entry(tree,&entry)) {
 671                unsigned long size;
 672                char type[20];
 673
 674                if (entry.pathlen != cmplen ||
 675                    memcmp(entry.path, name, cmplen) ||
 676                    !has_sha1_file(entry.sha1) ||
 677                    sha1_object_info(entry.sha1, type, &size))
 678                        continue;
 679                if (name[cmplen] != '/') {
 680                        unsigned hash = name_hash(fullname);
 681                        add_object_entry(entry.sha1, hash, 1);
 682                        return;
 683                }
 684                if (!strcmp(type, tree_type)) {
 685                        struct tree_desc sub;
 686                        struct pbase_tree_cache *tree;
 687                        const char *down = name+cmplen+1;
 688                        int downlen = name_cmp_len(down);
 689
 690                        tree = pbase_tree_get(entry.sha1);
 691                        if (!tree)
 692                                return;
 693                        sub.buf = tree->tree_data;
 694                        sub.size = tree->tree_size;
 695
 696                        add_pbase_object(&sub, down, downlen, fullname);
 697                        pbase_tree_put(tree);
 698                }
 699        }
 700}
 701
 702static unsigned *done_pbase_paths;
 703static int done_pbase_paths_num;
 704static int done_pbase_paths_alloc;
 705static int done_pbase_path_pos(unsigned hash)
 706{
 707        int lo = 0;
 708        int hi = done_pbase_paths_num;
 709        while (lo < hi) {
 710                int mi = (hi + lo) / 2;
 711                if (done_pbase_paths[mi] == hash)
 712                        return mi;
 713                if (done_pbase_paths[mi] < hash)
 714                        hi = mi;
 715                else
 716                        lo = mi + 1;
 717        }
 718        return -lo-1;
 719}
 720
 721static int check_pbase_path(unsigned hash)
 722{
 723        int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
 724        if (0 <= pos)
 725                return 1;
 726        pos = -pos - 1;
 727        if (done_pbase_paths_alloc <= done_pbase_paths_num) {
 728                done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
 729                done_pbase_paths = xrealloc(done_pbase_paths,
 730                                            done_pbase_paths_alloc *
 731                                            sizeof(unsigned));
 732        }
 733        done_pbase_paths_num++;
 734        if (pos < done_pbase_paths_num)
 735                memmove(done_pbase_paths + pos + 1,
 736                        done_pbase_paths + pos,
 737                        (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
 738        done_pbase_paths[pos] = hash;
 739        return 0;
 740}
 741
 742static void add_preferred_base_object(char *name, unsigned hash)
 743{
 744        struct pbase_tree *it;
 745        int cmplen = name_cmp_len(name);
 746
 747        if (check_pbase_path(hash))
 748                return;
 749
 750        for (it = pbase_tree; it; it = it->next) {
 751                if (cmplen == 0) {
 752                        hash = name_hash("");
 753                        add_object_entry(it->pcache.sha1, hash, 1);
 754                }
 755                else {
 756                        struct tree_desc tree;
 757                        tree.buf = it->pcache.tree_data;
 758                        tree.size = it->pcache.tree_size;
 759                        add_pbase_object(&tree, name, cmplen, name);
 760                }
 761        }
 762}
 763
 764static void add_preferred_base(unsigned char *sha1)
 765{
 766        struct pbase_tree *it;
 767        void *data;
 768        unsigned long size;
 769        unsigned char tree_sha1[20];
 770
 771        data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
 772        if (!data)
 773                return;
 774
 775        for (it = pbase_tree; it; it = it->next) {
 776                if (!memcmp(it->pcache.sha1, tree_sha1, 20)) {
 777                        free(data);
 778                        return;
 779                }
 780        }
 781
 782        it = xcalloc(1, sizeof(*it));
 783        it->next = pbase_tree;
 784        pbase_tree = it;
 785
 786        memcpy(it->pcache.sha1, tree_sha1, 20);
 787        it->pcache.tree_data = data;
 788        it->pcache.tree_size = size;
 789}
 790
 791static void check_object(struct object_entry *entry)
 792{
 793        char type[20];
 794
 795        if (entry->in_pack && !entry->preferred_base) {
 796                unsigned char base[20];
 797                unsigned long size;
 798                struct object_entry *base_entry;
 799
 800                /* We want in_pack_type even if we do not reuse delta.
 801                 * There is no point not reusing non-delta representations.
 802                 */
 803                check_reuse_pack_delta(entry->in_pack,
 804                                       entry->in_pack_offset,
 805                                       base, &size,
 806                                       &entry->in_pack_type);
 807
 808                /* Check if it is delta, and the base is also an object
 809                 * we are going to pack.  If so we will reuse the existing
 810                 * delta.
 811                 */
 812                if (!no_reuse_delta &&
 813                    entry->in_pack_type == OBJ_DELTA &&
 814                    (base_entry = locate_object_entry(base)) &&
 815                    (!base_entry->preferred_base)) {
 816
 817                        /* Depth value does not matter - find_deltas()
 818                         * will never consider reused delta as the
 819                         * base object to deltify other objects
 820                         * against, in order to avoid circular deltas.
 821                         */
 822
 823                        /* uncompressed size of the delta data */
 824                        entry->size = entry->delta_size = size;
 825                        entry->delta = base_entry;
 826                        entry->type = OBJ_DELTA;
 827
 828                        entry->delta_sibling = base_entry->delta_child;
 829                        base_entry->delta_child = entry;
 830
 831                        return;
 832                }
 833                /* Otherwise we would do the usual */
 834        }
 835
 836        if (sha1_object_info(entry->sha1, type, &entry->size))
 837                die("unable to get type of object %s",
 838                    sha1_to_hex(entry->sha1));
 839
 840        if (!strcmp(type, commit_type)) {
 841                entry->type = OBJ_COMMIT;
 842        } else if (!strcmp(type, tree_type)) {
 843                entry->type = OBJ_TREE;
 844        } else if (!strcmp(type, blob_type)) {
 845                entry->type = OBJ_BLOB;
 846        } else if (!strcmp(type, tag_type)) {
 847                entry->type = OBJ_TAG;
 848        } else
 849                die("unable to pack object %s of type %s",
 850                    sha1_to_hex(entry->sha1), type);
 851}
 852
 853static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
 854{
 855        struct object_entry *child = me->delta_child;
 856        unsigned int m = n;
 857        while (child) {
 858                unsigned int c = check_delta_limit(child, n + 1);
 859                if (m < c)
 860                        m = c;
 861                child = child->delta_sibling;
 862        }
 863        return m;
 864}
 865
 866static void get_object_details(void)
 867{
 868        int i;
 869        struct object_entry *entry;
 870
 871        prepare_pack_ix();
 872        for (i = 0, entry = objects; i < nr_objects; i++, entry++)
 873                check_object(entry);
 874
 875        if (nr_objects == nr_result) {
 876                /*
 877                 * Depth of objects that depend on the entry -- this
 878                 * is subtracted from depth-max to break too deep
 879                 * delta chain because of delta data reusing.
 880                 * However, we loosen this restriction when we know we
 881                 * are creating a thin pack -- it will have to be
 882                 * expanded on the other end anyway, so do not
 883                 * artificially cut the delta chain and let it go as
 884                 * deep as it wants.
 885                 */
 886                for (i = 0, entry = objects; i < nr_objects; i++, entry++)
 887                        if (!entry->delta && entry->delta_child)
 888                                entry->delta_limit =
 889                                        check_delta_limit(entry, 1);
 890        }
 891}
 892
 893typedef int (*entry_sort_t)(const struct object_entry *, const struct object_entry *);
 894
 895static entry_sort_t current_sort;
 896
 897static int sort_comparator(const void *_a, const void *_b)
 898{
 899        struct object_entry *a = *(struct object_entry **)_a;
 900        struct object_entry *b = *(struct object_entry **)_b;
 901        return current_sort(a,b);
 902}
 903
 904static struct object_entry **create_sorted_list(entry_sort_t sort)
 905{
 906        struct object_entry **list = xmalloc(nr_objects * sizeof(struct object_entry *));
 907        int i;
 908
 909        for (i = 0; i < nr_objects; i++)
 910                list[i] = objects + i;
 911        current_sort = sort;
 912        qsort(list, nr_objects, sizeof(struct object_entry *), sort_comparator);
 913        return list;
 914}
 915
 916static int sha1_sort(const struct object_entry *a, const struct object_entry *b)
 917{
 918        return memcmp(a->sha1, b->sha1, 20);
 919}
 920
 921static struct object_entry **create_final_object_list(void)
 922{
 923        struct object_entry **list;
 924        int i, j;
 925
 926        for (i = nr_result = 0; i < nr_objects; i++)
 927                if (!objects[i].preferred_base)
 928                        nr_result++;
 929        list = xmalloc(nr_result * sizeof(struct object_entry *));
 930        for (i = j = 0; i < nr_objects; i++) {
 931                if (!objects[i].preferred_base)
 932                        list[j++] = objects + i;
 933        }
 934        current_sort = sha1_sort;
 935        qsort(list, nr_result, sizeof(struct object_entry *), sort_comparator);
 936        return list;
 937}
 938
 939static int type_size_sort(const struct object_entry *a, const struct object_entry *b)
 940{
 941        if (a->type < b->type)
 942                return -1;
 943        if (a->type > b->type)
 944                return 1;
 945        if (a->hash < b->hash)
 946                return -1;
 947        if (a->hash > b->hash)
 948                return 1;
 949        if (a->preferred_base < b->preferred_base)
 950                return -1;
 951        if (a->preferred_base > b->preferred_base)
 952                return 1;
 953        if (a->size < b->size)
 954                return -1;
 955        if (a->size > b->size)
 956                return 1;
 957        return a < b ? -1 : (a > b);
 958}
 959
 960struct unpacked {
 961        struct object_entry *entry;
 962        void *data;
 963        struct delta_index *index;
 964};
 965
 966/*
 967 * We search for deltas _backwards_ in a list sorted by type and
 968 * by size, so that we see progressively smaller and smaller files.
 969 * That's because we prefer deltas to be from the bigger file
 970 * to the smaller - deletes are potentially cheaper, but perhaps
 971 * more importantly, the bigger file is likely the more recent
 972 * one.
 973 */
 974static int try_delta(struct unpacked *trg, struct unpacked *src,
 975                     unsigned max_depth)
 976{
 977        struct object_entry *trg_entry = trg->entry;
 978        struct object_entry *src_entry = src->entry;
 979        unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
 980        char type[10];
 981        void *delta_buf;
 982
 983        /* Don't bother doing diffs between different types */
 984        if (trg_entry->type != src_entry->type)
 985                return -1;
 986
 987        /* We do not compute delta to *create* objects we are not
 988         * going to pack.
 989         */
 990        if (trg_entry->preferred_base)
 991                return -1;
 992
 993        /*
 994         * We do not bother to try a delta that we discarded
 995         * on an earlier try, but only when reusing delta data.
 996         */
 997        if (!no_reuse_delta && trg_entry->in_pack &&
 998            trg_entry->in_pack == src_entry->in_pack)
 999                return 0;
1000
1001        /*
1002         * If the current object is at pack edge, take the depth the
1003         * objects that depend on the current object into account --
1004         * otherwise they would become too deep.
1005         */
1006        if (trg_entry->delta_child) {
1007                if (max_depth <= trg_entry->delta_limit)
1008                        return 0;
1009                max_depth -= trg_entry->delta_limit;
1010        }
1011        if (src_entry->depth >= max_depth)
1012                return 0;
1013
1014        /* Now some size filtering heuristics. */
1015        trg_size = trg_entry->size;
1016        max_size = trg_size/2 - 20;
1017        max_size = max_size * (max_depth - src_entry->depth) / max_depth;
1018        if (max_size == 0)
1019                return 0;
1020        if (trg_entry->delta && trg_entry->delta_size <= max_size)
1021                max_size = trg_entry->delta_size-1;
1022        src_size = src_entry->size;
1023        sizediff = src_size < trg_size ? trg_size - src_size : 0;
1024        if (sizediff >= max_size)
1025                return 0;
1026
1027        /* Load data if not already done */
1028        if (!trg->data) {
1029                trg->data = read_sha1_file(trg_entry->sha1, type, &sz);
1030                if (sz != trg_size)
1031                        die("object %s inconsistent object length (%lu vs %lu)",
1032                            sha1_to_hex(trg_entry->sha1), sz, trg_size);
1033        }
1034        if (!src->data) {
1035                src->data = read_sha1_file(src_entry->sha1, type, &sz);
1036                if (sz != src_size)
1037                        die("object %s inconsistent object length (%lu vs %lu)",
1038                            sha1_to_hex(src_entry->sha1), sz, src_size);
1039        }
1040        if (!src->index) {
1041                src->index = create_delta_index(src->data, src_size);
1042                if (!src->index)
1043                        die("out of memory");
1044        }
1045
1046        delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1047        if (!delta_buf)
1048                return 0;
1049
1050        trg_entry->delta = src_entry;
1051        trg_entry->delta_size = delta_size;
1052        trg_entry->depth = src_entry->depth + 1;
1053        free(delta_buf);
1054        return 1;
1055}
1056
1057static void progress_interval(int signum)
1058{
1059        progress_update = 1;
1060}
1061
1062static void find_deltas(struct object_entry **list, int window, int depth)
1063{
1064        int i, idx;
1065        unsigned int array_size = window * sizeof(struct unpacked);
1066        struct unpacked *array = xmalloc(array_size);
1067        unsigned processed = 0;
1068        unsigned last_percent = 999;
1069
1070        memset(array, 0, array_size);
1071        i = nr_objects;
1072        idx = 0;
1073        if (progress)
1074                fprintf(stderr, "Deltifying %d objects.\n", nr_result);
1075
1076        while (--i >= 0) {
1077                struct object_entry *entry = list[i];
1078                struct unpacked *n = array + idx;
1079                int j;
1080
1081                if (!entry->preferred_base)
1082                        processed++;
1083
1084                if (progress) {
1085                        unsigned percent = processed * 100 / nr_result;
1086                        if (percent != last_percent || progress_update) {
1087                                fprintf(stderr, "%4u%% (%u/%u) done\r",
1088                                        percent, processed, nr_result);
1089                                progress_update = 0;
1090                                last_percent = percent;
1091                        }
1092                }
1093
1094                if (entry->delta)
1095                        /* This happens if we decided to reuse existing
1096                         * delta from a pack.  "!no_reuse_delta &&" is implied.
1097                         */
1098                        continue;
1099
1100                if (entry->size < 50)
1101                        continue;
1102                free_delta_index(n->index);
1103                n->index = NULL;
1104                free(n->data);
1105                n->data = NULL;
1106                n->entry = entry;
1107
1108                j = window;
1109                while (--j > 0) {
1110                        unsigned int other_idx = idx + j;
1111                        struct unpacked *m;
1112                        if (other_idx >= window)
1113                                other_idx -= window;
1114                        m = array + other_idx;
1115                        if (!m->entry)
1116                                break;
1117                        if (try_delta(n, m, depth) < 0)
1118                                break;
1119                }
1120                /* if we made n a delta, and if n is already at max
1121                 * depth, leaving it in the window is pointless.  we
1122                 * should evict it first.
1123                 */
1124                if (entry->delta && depth <= entry->depth)
1125                        continue;
1126
1127                idx++;
1128                if (idx >= window)
1129                        idx = 0;
1130        }
1131
1132        if (progress)
1133                fputc('\n', stderr);
1134
1135        for (i = 0; i < window; ++i) {
1136                free_delta_index(array[i].index);
1137                free(array[i].data);
1138        }
1139        free(array);
1140}
1141
1142static void prepare_pack(int window, int depth)
1143{
1144        get_object_details();
1145        sorted_by_type = create_sorted_list(type_size_sort);
1146        if (window && depth)
1147                find_deltas(sorted_by_type, window+1, depth);
1148}
1149
1150static int reuse_cached_pack(unsigned char *sha1, int pack_to_stdout)
1151{
1152        static const char cache[] = "pack-cache/pack-%s.%s";
1153        char *cached_pack, *cached_idx;
1154        int ifd, ofd, ifd_ix = -1;
1155
1156        cached_pack = git_path(cache, sha1_to_hex(sha1), "pack");
1157        ifd = open(cached_pack, O_RDONLY);
1158        if (ifd < 0)
1159                return 0;
1160
1161        if (!pack_to_stdout) {
1162                cached_idx = git_path(cache, sha1_to_hex(sha1), "idx");
1163                ifd_ix = open(cached_idx, O_RDONLY);
1164                if (ifd_ix < 0) {
1165                        close(ifd);
1166                        return 0;
1167                }
1168        }
1169
1170        if (progress)
1171                fprintf(stderr, "Reusing %d objects pack %s\n", nr_objects,
1172                        sha1_to_hex(sha1));
1173
1174        if (pack_to_stdout) {
1175                if (copy_fd(ifd, 1))
1176                        exit(1);
1177                close(ifd);
1178        }
1179        else {
1180                char name[PATH_MAX];
1181                snprintf(name, sizeof(name),
1182                         "%s-%s.%s", base_name, sha1_to_hex(sha1), "pack");
1183                ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1184                if (ofd < 0)
1185                        die("unable to open %s (%s)", name, strerror(errno));
1186                if (copy_fd(ifd, ofd))
1187                        exit(1);
1188                close(ifd);
1189
1190                snprintf(name, sizeof(name),
1191                         "%s-%s.%s", base_name, sha1_to_hex(sha1), "idx");
1192                ofd = open(name, O_CREAT | O_EXCL | O_WRONLY, 0666);
1193                if (ofd < 0)
1194                        die("unable to open %s (%s)", name, strerror(errno));
1195                if (copy_fd(ifd_ix, ofd))
1196                        exit(1);
1197                close(ifd_ix);
1198                puts(sha1_to_hex(sha1));
1199        }
1200
1201        return 1;
1202}
1203
1204static void setup_progress_signal(void)
1205{
1206        struct sigaction sa;
1207        struct itimerval v;
1208
1209        memset(&sa, 0, sizeof(sa));
1210        sa.sa_handler = progress_interval;
1211        sigemptyset(&sa.sa_mask);
1212        sa.sa_flags = SA_RESTART;
1213        sigaction(SIGALRM, &sa, NULL);
1214
1215        v.it_interval.tv_sec = 1;
1216        v.it_interval.tv_usec = 0;
1217        v.it_value = v.it_interval;
1218        setitimer(ITIMER_REAL, &v, NULL);
1219}
1220
1221static int git_pack_config(const char *k, const char *v)
1222{
1223        if(!strcmp(k, "pack.window")) {
1224                window = git_config_int(k, v);
1225                return 0;
1226        }
1227        return git_default_config(k, v);
1228}
1229
1230int cmd_pack_objects(int argc, const char **argv, const char *prefix)
1231{
1232        SHA_CTX ctx;
1233        char line[40 + 1 + PATH_MAX + 2];
1234        int depth = 10, pack_to_stdout = 0;
1235        struct object_entry **list;
1236        int num_preferred_base = 0;
1237        int i;
1238
1239        git_config(git_pack_config);
1240
1241        progress = isatty(2);
1242        for (i = 1; i < argc; i++) {
1243                const char *arg = argv[i];
1244
1245                if (*arg == '-') {
1246                        if (!strcmp("--non-empty", arg)) {
1247                                non_empty = 1;
1248                                continue;
1249                        }
1250                        if (!strcmp("--local", arg)) {
1251                                local = 1;
1252                                continue;
1253                        }
1254                        if (!strcmp("--progress", arg)) {
1255                                progress = 1;
1256                                continue;
1257                        }
1258                        if (!strcmp("--incremental", arg)) {
1259                                incremental = 1;
1260                                continue;
1261                        }
1262                        if (!strncmp("--window=", arg, 9)) {
1263                                char *end;
1264                                window = strtoul(arg+9, &end, 0);
1265                                if (!arg[9] || *end)
1266                                        usage(pack_usage);
1267                                continue;
1268                        }
1269                        if (!strncmp("--depth=", arg, 8)) {
1270                                char *end;
1271                                depth = strtoul(arg+8, &end, 0);
1272                                if (!arg[8] || *end)
1273                                        usage(pack_usage);
1274                                continue;
1275                        }
1276                        if (!strcmp("--progress", arg)) {
1277                                progress = 1;
1278                                continue;
1279                        }
1280                        if (!strcmp("-q", arg)) {
1281                                progress = 0;
1282                                continue;
1283                        }
1284                        if (!strcmp("--no-reuse-delta", arg)) {
1285                                no_reuse_delta = 1;
1286                                continue;
1287                        }
1288                        if (!strcmp("--stdout", arg)) {
1289                                pack_to_stdout = 1;
1290                                continue;
1291                        }
1292                        usage(pack_usage);
1293                }
1294                if (base_name)
1295                        usage(pack_usage);
1296                base_name = arg;
1297        }
1298
1299        if (pack_to_stdout != !base_name)
1300                usage(pack_usage);
1301
1302        prepare_packed_git();
1303
1304        if (progress) {
1305                fprintf(stderr, "Generating pack...\n");
1306                setup_progress_signal();
1307        }
1308
1309        for (;;) {
1310                unsigned char sha1[20];
1311                unsigned hash;
1312
1313                if (!fgets(line, sizeof(line), stdin)) {
1314                        if (feof(stdin))
1315                                break;
1316                        if (!ferror(stdin))
1317                                die("fgets returned NULL, not EOF, not error!");
1318                        if (errno != EINTR)
1319                                die("fgets: %s", strerror(errno));
1320                        clearerr(stdin);
1321                        continue;
1322                }
1323
1324                if (line[0] == '-') {
1325                        if (get_sha1_hex(line+1, sha1))
1326                                die("expected edge sha1, got garbage:\n %s",
1327                                    line+1);
1328                        if (num_preferred_base++ < window)
1329                                add_preferred_base(sha1);
1330                        continue;
1331                }
1332                if (get_sha1_hex(line, sha1))
1333                        die("expected sha1, got garbage:\n %s", line);
1334                hash = name_hash(line+41);
1335                add_preferred_base_object(line+41, hash);
1336                add_object_entry(sha1, hash, 0);
1337        }
1338        if (progress)
1339                fprintf(stderr, "Done counting %d objects.\n", nr_objects);
1340        sorted_by_sha = create_final_object_list();
1341        if (non_empty && !nr_result)
1342                return 0;
1343
1344        SHA1_Init(&ctx);
1345        list = sorted_by_sha;
1346        for (i = 0; i < nr_result; i++) {
1347                struct object_entry *entry = *list++;
1348                SHA1_Update(&ctx, entry->sha1, 20);
1349        }
1350        SHA1_Final(object_list_sha1, &ctx);
1351        if (progress && (nr_objects != nr_result))
1352                fprintf(stderr, "Result has %d objects.\n", nr_result);
1353
1354        if (reuse_cached_pack(object_list_sha1, pack_to_stdout))
1355                ;
1356        else {
1357                if (nr_result)
1358                        prepare_pack(window, depth);
1359                if (progress && pack_to_stdout) {
1360                        /* the other end usually displays progress itself */
1361                        struct itimerval v = {{0,},};
1362                        setitimer(ITIMER_REAL, &v, NULL);
1363                        signal(SIGALRM, SIG_IGN );
1364                        progress_update = 0;
1365                }
1366                write_pack_file();
1367                if (!pack_to_stdout) {
1368                        write_index_file();
1369                        puts(sha1_to_hex(object_list_sha1));
1370                }
1371        }
1372        if (progress)
1373                fprintf(stderr, "Total %d, written %d (delta %d), reused %d (delta %d)\n",
1374                        nr_result, written, written_delta, reused, reused_delta);
1375        return 0;
1376}