6b011204150111d40cf8eb50117b24236eb214c8
   1/*
   2Format of STDIN stream:
   3
   4  stream ::= cmd*;
   5
   6  cmd ::= new_blob
   7        | new_commit
   8        | new_tag
   9        | reset_branch
  10        ;
  11
  12  new_blob ::= 'blob' lf
  13        mark?
  14    file_content;
  15  file_content ::= data;
  16
  17  new_commit ::= 'commit' sp ref_str lf
  18    mark?
  19    ('author' sp name '<' email '>' ts tz lf)?
  20    'committer' sp name '<' email '>' ts tz lf
  21    commit_msg
  22    ('from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf)?
  23    file_change*
  24    lf;
  25  commit_msg ::= data;
  26
  27  file_change ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf
  28                | 'D' sp path_str lf
  29                ;
  30  mode ::= '644' | '755';
  31
  32  new_tag ::= 'tag' sp tag_str lf
  33    'from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf
  34        'tagger' sp name '<' email '>' ts tz lf
  35    tag_msg;
  36  tag_msg ::= data;
  37
  38  reset_branch ::= 'reset' sp ref_str lf;
  39
  40     # note: the first idnum in a stream should be 1 and subsequent
  41     # idnums should not have gaps between values as this will cause
  42     # the stream parser to reserve space for the gapped values.  An
  43         # idnum can be updated in the future to a new object by issuing
  44     # a new mark directive with the old idnum.
  45         #
  46  mark ::= 'mark' sp idnum lf;
  47
  48     # note: declen indicates the length of binary_data in bytes.
  49     # declen does not include the lf preceeding or trailing the
  50     # binary data.
  51     #
  52  data ::= 'data' sp declen lf
  53    binary_data
  54        lf;
  55
  56     # note: quoted strings are C-style quoting supporting \c for
  57     # common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn
  58         # is the signed byte value in octal.  Note that the only
  59     # characters which must actually be escaped to protect the
  60     # stream formatting is: \, " and LF.  Otherwise these values
  61         # are UTF8.
  62     #
  63  ref_str     ::= ref     | '"' quoted(ref)     '"' ;
  64  sha1exp_str ::= sha1exp | '"' quoted(sha1exp) '"' ;
  65  tag_str     ::= tag     | '"' quoted(tag)     '"' ;
  66  path_str    ::= path    | '"' quoted(path)    '"' ;
  67
  68  declen ::= # unsigned 32 bit value, ascii base10 notation;
  69  binary_data ::= # file content, not interpreted;
  70
  71  sp ::= # ASCII space character;
  72  lf ::= # ASCII newline (LF) character;
  73
  74     # note: a colon (':') must precede the numerical value assigned to
  75         # an idnum.  This is to distinguish it from a ref or tag name as
  76     # GIT does not permit ':' in ref or tag strings.
  77         #
  78  idnum   ::= ':' declen;
  79  path    ::= # GIT style file path, e.g. "a/b/c";
  80  ref     ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT";
  81  tag     ::= # GIT tag name, e.g. "FIREFOX_1_5";
  82  sha1exp ::= # Any valid GIT SHA1 expression;
  83  hexsha1 ::= # SHA1 in hexadecimal format;
  84
  85     # note: name and email are UTF8 strings, however name must not
  86         # contain '<' or lf and email must not contain any of the
  87     # following: '<', '>', lf.
  88         #
  89  name  ::= # valid GIT author/committer name;
  90  email ::= # valid GIT author/committer email;
  91  ts    ::= # time since the epoch in seconds, ascii base10 notation;
  92  tz    ::= # GIT style timezone;
  93*/
  94
  95#include "builtin.h"
  96#include "cache.h"
  97#include "object.h"
  98#include "blob.h"
  99#include "tree.h"
 100#include "delta.h"
 101#include "pack.h"
 102#include "refs.h"
 103#include "csum-file.h"
 104#include "strbuf.h"
 105#include "quote.h"
 106
 107struct object_entry
 108{
 109        struct object_entry *next;
 110        enum object_type type;
 111        unsigned long offset;
 112        unsigned char sha1[20];
 113};
 114
 115struct object_entry_pool
 116{
 117        struct object_entry_pool *next_pool;
 118        struct object_entry *next_free;
 119        struct object_entry *end;
 120        struct object_entry entries[FLEX_ARRAY]; /* more */
 121};
 122
 123struct mark_set
 124{
 125        int shift;
 126        union {
 127                struct object_entry *marked[1024];
 128                struct mark_set *sets[1024];
 129        } data;
 130};
 131
 132struct last_object
 133{
 134        void *data;
 135        unsigned long len;
 136        unsigned int depth;
 137        unsigned char sha1[20];
 138};
 139
 140struct mem_pool
 141{
 142        struct mem_pool *next_pool;
 143        char *next_free;
 144        char *end;
 145        char space[FLEX_ARRAY]; /* more */
 146};
 147
 148struct atom_str
 149{
 150        struct atom_str *next_atom;
 151        int str_len;
 152        char str_dat[FLEX_ARRAY]; /* more */
 153};
 154
 155struct tree_content;
 156struct tree_entry
 157{
 158        struct tree_content *tree;
 159        struct atom_str* name;
 160        struct tree_entry_ms
 161        {
 162                unsigned int mode;
 163                unsigned char sha1[20];
 164        } versions[2];
 165};
 166
 167struct tree_content
 168{
 169        unsigned int entry_capacity; /* must match avail_tree_content */
 170        unsigned int entry_count;
 171        unsigned int delta_depth;
 172        struct tree_entry *entries[FLEX_ARRAY]; /* more */
 173};
 174
 175struct avail_tree_content
 176{
 177        unsigned int entry_capacity; /* must match tree_content */
 178        struct avail_tree_content *next_avail;
 179};
 180
 181struct branch
 182{
 183        struct branch *table_next_branch;
 184        struct branch *active_next_branch;
 185        const char *name;
 186        unsigned long last_commit;
 187        struct tree_entry branch_tree;
 188        unsigned char sha1[20];
 189};
 190
 191struct tag
 192{
 193        struct tag *next_tag;
 194        const char *name;
 195        unsigned char sha1[20];
 196};
 197
 198
 199/* Stats and misc. counters */
 200static unsigned long max_depth = 10;
 201static unsigned long alloc_count;
 202static unsigned long branch_count;
 203static unsigned long branch_load_count;
 204static unsigned long remap_count;
 205static unsigned long object_count;
 206static unsigned long duplicate_count;
 207static unsigned long marks_set_count;
 208static unsigned long object_count_by_type[9];
 209static unsigned long duplicate_count_by_type[9];
 210static unsigned long delta_count_by_type[9];
 211
 212/* Memory pools */
 213static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
 214static size_t total_allocd;
 215static struct mem_pool *mem_pool;
 216
 217/* Atom management */
 218static unsigned int atom_table_sz = 4451;
 219static unsigned int atom_cnt;
 220static struct atom_str **atom_table;
 221
 222/* The .pack file being generated */
 223static int pack_fd;
 224static unsigned long pack_size;
 225static unsigned char pack_sha1[20];
 226static unsigned char* pack_base;
 227static unsigned long pack_moff;
 228static unsigned long pack_mlen = 128*1024*1024;
 229static unsigned long page_size;
 230
 231/* Table of objects we've written. */
 232static unsigned int object_entry_alloc = 5000;
 233static struct object_entry_pool *blocks;
 234static struct object_entry *object_table[1 << 16];
 235static struct mark_set *marks;
 236static const char* mark_file;
 237
 238/* Our last blob */
 239static struct last_object last_blob;
 240
 241/* Tree management */
 242static unsigned int tree_entry_alloc = 1000;
 243static void *avail_tree_entry;
 244static unsigned int avail_tree_table_sz = 100;
 245static struct avail_tree_content **avail_tree_table;
 246
 247/* Branch data */
 248static unsigned long max_active_branches = 5;
 249static unsigned long cur_active_branches;
 250static unsigned long branch_table_sz = 1039;
 251static struct branch **branch_table;
 252static struct branch *active_branches;
 253
 254/* Tag data */
 255static struct tag *first_tag;
 256static struct tag *last_tag;
 257
 258/* Input stream parsing */
 259static struct strbuf command_buf;
 260static unsigned long next_mark;
 261static FILE* branch_log;
 262
 263
 264static void alloc_objects(int cnt)
 265{
 266        struct object_entry_pool *b;
 267
 268        b = xmalloc(sizeof(struct object_entry_pool)
 269                + cnt * sizeof(struct object_entry));
 270        b->next_pool = blocks;
 271        b->next_free = b->entries;
 272        b->end = b->entries + cnt;
 273        blocks = b;
 274        alloc_count += cnt;
 275}
 276
 277static struct object_entry* new_object(unsigned char *sha1)
 278{
 279        struct object_entry *e;
 280
 281        if (blocks->next_free == blocks->end)
 282                alloc_objects(object_entry_alloc);
 283
 284        e = blocks->next_free++;
 285        hashcpy(e->sha1, sha1);
 286        return e;
 287}
 288
 289static struct object_entry* find_object(unsigned char *sha1)
 290{
 291        unsigned int h = sha1[0] << 8 | sha1[1];
 292        struct object_entry *e;
 293        for (e = object_table[h]; e; e = e->next)
 294                if (!hashcmp(sha1, e->sha1))
 295                        return e;
 296        return NULL;
 297}
 298
 299static struct object_entry* insert_object(unsigned char *sha1)
 300{
 301        unsigned int h = sha1[0] << 8 | sha1[1];
 302        struct object_entry *e = object_table[h];
 303        struct object_entry *p = NULL;
 304
 305        while (e) {
 306                if (!hashcmp(sha1, e->sha1))
 307                        return e;
 308                p = e;
 309                e = e->next;
 310        }
 311
 312        e = new_object(sha1);
 313        e->next = NULL;
 314        e->offset = 0;
 315        if (p)
 316                p->next = e;
 317        else
 318                object_table[h] = e;
 319        return e;
 320}
 321
 322static unsigned int hc_str(const char *s, size_t len)
 323{
 324        unsigned int r = 0;
 325        while (len-- > 0)
 326                r = r * 31 + *s++;
 327        return r;
 328}
 329
 330static void* pool_alloc(size_t len)
 331{
 332        struct mem_pool *p;
 333        void *r;
 334
 335        for (p = mem_pool; p; p = p->next_pool)
 336                if ((p->end - p->next_free >= len))
 337                        break;
 338
 339        if (!p) {
 340                if (len >= (mem_pool_alloc/2)) {
 341                        total_allocd += len;
 342                        return xmalloc(len);
 343                }
 344                total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
 345                p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc);
 346                p->next_pool = mem_pool;
 347                p->next_free = p->space;
 348                p->end = p->next_free + mem_pool_alloc;
 349                mem_pool = p;
 350        }
 351
 352        r = p->next_free;
 353        /* round out to a pointer alignment */
 354        if (len & (sizeof(void*) - 1))
 355                len += sizeof(void*) - (len & (sizeof(void*) - 1));
 356        p->next_free += len;
 357        return r;
 358}
 359
 360static void* pool_calloc(size_t count, size_t size)
 361{
 362        size_t len = count * size;
 363        void *r = pool_alloc(len);
 364        memset(r, 0, len);
 365        return r;
 366}
 367
 368static char* pool_strdup(const char *s)
 369{
 370        char *r = pool_alloc(strlen(s) + 1);
 371        strcpy(r, s);
 372        return r;
 373}
 374
 375static void insert_mark(unsigned long idnum, struct object_entry *oe)
 376{
 377        struct mark_set *s = marks;
 378        while ((idnum >> s->shift) >= 1024) {
 379                s = pool_calloc(1, sizeof(struct mark_set));
 380                s->shift = marks->shift + 10;
 381                s->data.sets[0] = marks;
 382                marks = s;
 383        }
 384        while (s->shift) {
 385                unsigned long i = idnum >> s->shift;
 386                idnum -= i << s->shift;
 387                if (!s->data.sets[i]) {
 388                        s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
 389                        s->data.sets[i]->shift = s->shift - 10;
 390                }
 391                s = s->data.sets[i];
 392        }
 393        if (!s->data.marked[idnum])
 394                marks_set_count++;
 395        s->data.marked[idnum] = oe;
 396}
 397
 398static struct object_entry* find_mark(unsigned long idnum)
 399{
 400        unsigned long orig_idnum = idnum;
 401        struct mark_set *s = marks;
 402        struct object_entry *oe = NULL;
 403        if ((idnum >> s->shift) < 1024) {
 404                while (s && s->shift) {
 405                        unsigned long i = idnum >> s->shift;
 406                        idnum -= i << s->shift;
 407                        s = s->data.sets[i];
 408                }
 409                if (s)
 410                        oe = s->data.marked[idnum];
 411        }
 412        if (!oe)
 413                die("mark :%lu not declared", orig_idnum);
 414        return oe;
 415}
 416
 417static struct atom_str* to_atom(const char *s, size_t len)
 418{
 419        unsigned int hc = hc_str(s, len) % atom_table_sz;
 420        struct atom_str *c;
 421
 422        for (c = atom_table[hc]; c; c = c->next_atom)
 423                if (c->str_len == len && !strncmp(s, c->str_dat, len))
 424                        return c;
 425
 426        c = pool_alloc(sizeof(struct atom_str) + len + 1);
 427        c->str_len = len;
 428        strncpy(c->str_dat, s, len);
 429        c->str_dat[len] = 0;
 430        c->next_atom = atom_table[hc];
 431        atom_table[hc] = c;
 432        atom_cnt++;
 433        return c;
 434}
 435
 436static struct branch* lookup_branch(const char *name)
 437{
 438        unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
 439        struct branch *b;
 440
 441        for (b = branch_table[hc]; b; b = b->table_next_branch)
 442                if (!strcmp(name, b->name))
 443                        return b;
 444        return NULL;
 445}
 446
 447static struct branch* new_branch(const char *name)
 448{
 449        unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
 450        struct branch* b = lookup_branch(name);
 451
 452        if (b)
 453                die("Invalid attempt to create duplicate branch: %s", name);
 454        if (check_ref_format(name))
 455                die("Branch name doesn't conform to GIT standards: %s", name);
 456
 457        b = pool_calloc(1, sizeof(struct branch));
 458        b->name = pool_strdup(name);
 459        b->table_next_branch = branch_table[hc];
 460        branch_table[hc] = b;
 461        branch_count++;
 462        return b;
 463}
 464
 465static unsigned int hc_entries(unsigned int cnt)
 466{
 467        cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
 468        return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
 469}
 470
 471static struct tree_content* new_tree_content(unsigned int cnt)
 472{
 473        struct avail_tree_content *f, *l = NULL;
 474        struct tree_content *t;
 475        unsigned int hc = hc_entries(cnt);
 476
 477        for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
 478                if (f->entry_capacity >= cnt)
 479                        break;
 480
 481        if (f) {
 482                if (l)
 483                        l->next_avail = f->next_avail;
 484                else
 485                        avail_tree_table[hc] = f->next_avail;
 486        } else {
 487                cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
 488                f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
 489                f->entry_capacity = cnt;
 490        }
 491
 492        t = (struct tree_content*)f;
 493        t->entry_count = 0;
 494        t->delta_depth = 0;
 495        return t;
 496}
 497
 498static void release_tree_entry(struct tree_entry *e);
 499static void release_tree_content(struct tree_content *t)
 500{
 501        struct avail_tree_content *f = (struct avail_tree_content*)t;
 502        unsigned int hc = hc_entries(f->entry_capacity);
 503        f->next_avail = avail_tree_table[hc];
 504        avail_tree_table[hc] = f;
 505}
 506
 507static void release_tree_content_recursive(struct tree_content *t)
 508{
 509        unsigned int i;
 510        for (i = 0; i < t->entry_count; i++)
 511                release_tree_entry(t->entries[i]);
 512        release_tree_content(t);
 513}
 514
 515static struct tree_content* grow_tree_content(
 516        struct tree_content *t,
 517        int amt)
 518{
 519        struct tree_content *r = new_tree_content(t->entry_count + amt);
 520        r->entry_count = t->entry_count;
 521        r->delta_depth = t->delta_depth;
 522        memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
 523        release_tree_content(t);
 524        return r;
 525}
 526
 527static struct tree_entry* new_tree_entry()
 528{
 529        struct tree_entry *e;
 530
 531        if (!avail_tree_entry) {
 532                unsigned int n = tree_entry_alloc;
 533                total_allocd += n * sizeof(struct tree_entry);
 534                avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry));
 535                while (n-- > 1) {
 536                        *((void**)e) = e + 1;
 537                        e++;
 538                }
 539                *((void**)e) = NULL;
 540        }
 541
 542        e = avail_tree_entry;
 543        avail_tree_entry = *((void**)e);
 544        return e;
 545}
 546
 547static void release_tree_entry(struct tree_entry *e)
 548{
 549        if (e->tree)
 550                release_tree_content_recursive(e->tree);
 551        *((void**)e) = avail_tree_entry;
 552        avail_tree_entry = e;
 553}
 554
 555static void yread(int fd, void *buffer, size_t length)
 556{
 557        ssize_t ret = 0;
 558        while (ret < length) {
 559                ssize_t size = xread(fd, (char *) buffer + ret, length - ret);
 560                if (!size)
 561                        die("Read from descriptor %i: end of stream", fd);
 562                if (size < 0)
 563                        die("Read from descriptor %i: %s", fd, strerror(errno));
 564                ret += size;
 565        }
 566}
 567
 568static void ywrite(int fd, void *buffer, size_t length)
 569{
 570        ssize_t ret = 0;
 571        while (ret < length) {
 572                ssize_t size = xwrite(fd, (char *) buffer + ret, length - ret);
 573                if (!size)
 574                        die("Write to descriptor %i: end of file", fd);
 575                if (size < 0)
 576                        die("Write to descriptor %i: %s", fd, strerror(errno));
 577                ret += size;
 578        }
 579}
 580
 581static size_t encode_header(
 582        enum object_type type,
 583        size_t size,
 584        unsigned char *hdr)
 585{
 586        int n = 1;
 587        unsigned char c;
 588
 589        if (type < OBJ_COMMIT || type > OBJ_DELTA)
 590                die("bad type %d", type);
 591
 592        c = (type << 4) | (size & 15);
 593        size >>= 4;
 594        while (size) {
 595                *hdr++ = c | 0x80;
 596                c = size & 0x7f;
 597                size >>= 7;
 598                n++;
 599        }
 600        *hdr = c;
 601        return n;
 602}
 603
 604static int store_object(
 605        enum object_type type,
 606        void *dat,
 607        size_t datlen,
 608        struct last_object *last,
 609        unsigned char *sha1out,
 610        unsigned long mark)
 611{
 612        void *out, *delta;
 613        struct object_entry *e;
 614        unsigned char hdr[96];
 615        unsigned char sha1[20];
 616        unsigned long hdrlen, deltalen;
 617        SHA_CTX c;
 618        z_stream s;
 619
 620        hdrlen = sprintf((char*)hdr,"%s %lu",type_names[type],datlen) + 1;
 621        SHA1_Init(&c);
 622        SHA1_Update(&c, hdr, hdrlen);
 623        SHA1_Update(&c, dat, datlen);
 624        SHA1_Final(sha1, &c);
 625        if (sha1out)
 626                hashcpy(sha1out, sha1);
 627
 628        e = insert_object(sha1);
 629        if (mark)
 630                insert_mark(mark, e);
 631        if (e->offset) {
 632                duplicate_count++;
 633                duplicate_count_by_type[type]++;
 634                return 1;
 635        }
 636        e->type = type;
 637        e->offset = pack_size;
 638        object_count++;
 639        object_count_by_type[type]++;
 640
 641        if (last && last->data && last->depth < max_depth)
 642                delta = diff_delta(last->data, last->len,
 643                        dat, datlen,
 644                        &deltalen, 0);
 645        else
 646                delta = 0;
 647
 648        memset(&s, 0, sizeof(s));
 649        deflateInit(&s, zlib_compression_level);
 650
 651        if (delta) {
 652                delta_count_by_type[type]++;
 653                last->depth++;
 654                s.next_in = delta;
 655                s.avail_in = deltalen;
 656                hdrlen = encode_header(OBJ_DELTA, deltalen, hdr);
 657                ywrite(pack_fd, hdr, hdrlen);
 658                ywrite(pack_fd, last->sha1, sizeof(sha1));
 659                pack_size += hdrlen + sizeof(sha1);
 660        } else {
 661                if (last)
 662                        last->depth = 0;
 663                s.next_in = dat;
 664                s.avail_in = datlen;
 665                hdrlen = encode_header(type, datlen, hdr);
 666                ywrite(pack_fd, hdr, hdrlen);
 667                pack_size += hdrlen;
 668        }
 669
 670        s.avail_out = deflateBound(&s, s.avail_in);
 671        s.next_out = out = xmalloc(s.avail_out);
 672        while (deflate(&s, Z_FINISH) == Z_OK)
 673                /* nothing */;
 674        deflateEnd(&s);
 675
 676        ywrite(pack_fd, out, s.total_out);
 677        pack_size += s.total_out;
 678
 679        free(out);
 680        if (delta)
 681                free(delta);
 682        if (last) {
 683                if (last->data)
 684                        free(last->data);
 685                last->data = dat;
 686                last->len = datlen;
 687                hashcpy(last->sha1, sha1);
 688        }
 689        return 0;
 690}
 691
 692static unsigned char* map_pack(unsigned long offset, unsigned int *left)
 693{
 694        if (offset >= pack_size)
 695                die("object offset outside of pack file");
 696        if (!pack_base
 697                        || offset < pack_moff
 698                        || (offset + 20) >= (pack_moff + pack_mlen)) {
 699                if (pack_base)
 700                        munmap(pack_base, pack_mlen);
 701                pack_moff = (offset / page_size) * page_size;
 702                pack_base = mmap(NULL,pack_mlen,PROT_READ,MAP_SHARED,
 703                        pack_fd,pack_moff);
 704                if (pack_base == MAP_FAILED)
 705                        die("Failed to map generated pack: %s", strerror(errno));
 706                remap_count++;
 707        }
 708        offset -= pack_moff;
 709        if (left)
 710                *left = pack_mlen - offset;
 711        return pack_base + offset;
 712}
 713
 714static unsigned long unpack_object_header(unsigned long offset,
 715        enum object_type *type,
 716        unsigned long *sizep)
 717{
 718        unsigned shift;
 719        unsigned char c;
 720        unsigned long size;
 721
 722        c = *map_pack(offset++, NULL);
 723        *type = (c >> 4) & 7;
 724        size = c & 15;
 725        shift = 4;
 726        while (c & 0x80) {
 727                c = *map_pack(offset++, NULL);
 728                size += (c & 0x7f) << shift;
 729                shift += 7;
 730        }
 731        *sizep = size;
 732        return offset;
 733}
 734
 735static void *unpack_non_delta_entry(unsigned long o, unsigned long sz)
 736{
 737        z_stream stream;
 738        unsigned char *result;
 739
 740        result = xmalloc(sz + 1);
 741        result[sz] = 0;
 742
 743        memset(&stream, 0, sizeof(stream));
 744        stream.next_in = map_pack(o, &stream.avail_in);
 745        stream.next_out = result;
 746        stream.avail_out = sz;
 747
 748        inflateInit(&stream);
 749        for (;;) {
 750                int st = inflate(&stream, Z_FINISH);
 751                if (st == Z_STREAM_END)
 752                        break;
 753                if (st == Z_OK || st == Z_BUF_ERROR) {
 754                        o = stream.next_in - pack_base + pack_moff;
 755                        stream.next_in = map_pack(o, &stream.avail_in);
 756                        continue;
 757                }
 758                die("Error %i from zlib during inflate.", st);
 759        }
 760        inflateEnd(&stream);
 761        if (stream.total_out != sz)
 762                die("Error after inflate: sizes mismatch");
 763        return result;
 764}
 765
 766static void *unpack_entry(unsigned long offset,
 767        unsigned long *sizep,
 768        unsigned int *delta_depth);
 769
 770static void *unpack_delta_entry(unsigned long offset,
 771        unsigned long delta_size,
 772        unsigned long *sizep,
 773        unsigned int *delta_depth)
 774{
 775        struct object_entry *base_oe;
 776        unsigned char *base_sha1;
 777        void *delta_data, *base, *result;
 778        unsigned long base_size, result_size;
 779
 780        base_sha1 = map_pack(offset, NULL);
 781        base_oe = find_object(base_sha1);
 782        if (!base_oe)
 783                die("I'm broken; I can't find a base I know must be here.");
 784        base = unpack_entry(base_oe->offset, &base_size, delta_depth);
 785        delta_data = unpack_non_delta_entry(offset + 20, delta_size);
 786        result = patch_delta(base, base_size,
 787                             delta_data, delta_size,
 788                             &result_size);
 789        if (!result)
 790                die("failed to apply delta");
 791        free(delta_data);
 792        free(base);
 793        *sizep = result_size;
 794        (*delta_depth)++;
 795        return result;
 796}
 797
 798static void *unpack_entry(unsigned long offset,
 799        unsigned long *sizep,
 800        unsigned int *delta_depth)
 801{
 802        unsigned long size;
 803        enum object_type kind;
 804
 805        offset = unpack_object_header(offset, &kind, &size);
 806        switch (kind) {
 807        case OBJ_DELTA:
 808                return unpack_delta_entry(offset, size, sizep, delta_depth);
 809        case OBJ_COMMIT:
 810        case OBJ_TREE:
 811        case OBJ_BLOB:
 812        case OBJ_TAG:
 813                *sizep = size;
 814                *delta_depth = 0;
 815                return unpack_non_delta_entry(offset, size);
 816        default:
 817                die("I created an object I can't read!");
 818        }
 819}
 820
 821static const char *get_mode(const char *str, unsigned int *modep)
 822{
 823        unsigned char c;
 824        unsigned int mode = 0;
 825
 826        while ((c = *str++) != ' ') {
 827                if (c < '0' || c > '7')
 828                        return NULL;
 829                mode = (mode << 3) + (c - '0');
 830        }
 831        *modep = mode;
 832        return str;
 833}
 834
 835static void load_tree(struct tree_entry *root)
 836{
 837        unsigned char* sha1 = root->versions[1].sha1;
 838        struct object_entry *myoe;
 839        struct tree_content *t;
 840        unsigned long size;
 841        char *buf;
 842        const char *c;
 843
 844        root->tree = t = new_tree_content(8);
 845        if (is_null_sha1(sha1))
 846                return;
 847
 848        myoe = find_object(sha1);
 849        if (myoe) {
 850                if (myoe->type != OBJ_TREE)
 851                        die("Not a tree: %s", sha1_to_hex(sha1));
 852                buf = unpack_entry(myoe->offset, &size, &t->delta_depth);
 853        } else {
 854                char type[20];
 855                buf = read_sha1_file(sha1, type, &size);
 856                if (!buf || strcmp(type, tree_type))
 857                        die("Can't load tree %s", sha1_to_hex(sha1));
 858        }
 859
 860        c = buf;
 861        while (c != (buf + size)) {
 862                struct tree_entry *e = new_tree_entry();
 863
 864                if (t->entry_count == t->entry_capacity)
 865                        root->tree = t = grow_tree_content(t, 8);
 866                t->entries[t->entry_count++] = e;
 867
 868                e->tree = NULL;
 869                c = get_mode(c, &e->versions[1].mode);
 870                if (!c)
 871                        die("Corrupt mode in %s", sha1_to_hex(sha1));
 872                e->versions[0].mode = e->versions[1].mode;
 873                e->name = to_atom(c, strlen(c));
 874                c += e->name->str_len + 1;
 875                hashcpy(e->versions[0].sha1, (unsigned char*)c);
 876                hashcpy(e->versions[1].sha1, (unsigned char*)c);
 877                c += 20;
 878        }
 879        free(buf);
 880}
 881
 882static int tecmp0 (const void *_a, const void *_b)
 883{
 884        struct tree_entry *a = *((struct tree_entry**)_a);
 885        struct tree_entry *b = *((struct tree_entry**)_b);
 886        return base_name_compare(
 887                a->name->str_dat, a->name->str_len, a->versions[0].mode,
 888                b->name->str_dat, b->name->str_len, b->versions[0].mode);
 889}
 890
 891static int tecmp1 (const void *_a, const void *_b)
 892{
 893        struct tree_entry *a = *((struct tree_entry**)_a);
 894        struct tree_entry *b = *((struct tree_entry**)_b);
 895        return base_name_compare(
 896                a->name->str_dat, a->name->str_len, a->versions[1].mode,
 897                b->name->str_dat, b->name->str_len, b->versions[1].mode);
 898}
 899
 900static void* mktree(struct tree_content *t, int v, unsigned long *szp)
 901{
 902        size_t maxlen = 0;
 903        unsigned int i;
 904        char *buf, *c;
 905
 906        if (!v)
 907                qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0);
 908        else
 909                qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1);
 910
 911        for (i = 0; i < t->entry_count; i++) {
 912                if (t->entries[i]->versions[v].mode)
 913                        maxlen += t->entries[i]->name->str_len + 34;
 914        }
 915
 916        buf = c = xmalloc(maxlen);
 917        for (i = 0; i < t->entry_count; i++) {
 918                struct tree_entry *e = t->entries[i];
 919                if (!e->versions[v].mode)
 920                        continue;
 921                c += sprintf(c, "%o", e->versions[v].mode);
 922                *c++ = ' ';
 923                strcpy(c, e->name->str_dat);
 924                c += e->name->str_len + 1;
 925                hashcpy((unsigned char*)c, e->versions[v].sha1);
 926                c += 20;
 927        }
 928
 929        *szp = c - buf;
 930        return buf;
 931}
 932
 933static void store_tree(struct tree_entry *root)
 934{
 935        struct tree_content *t = root->tree;
 936        unsigned int i, j, del;
 937        unsigned long vers1len;
 938        void **vers1dat;
 939        struct last_object lo;
 940
 941        if (!is_null_sha1(root->versions[1].sha1))
 942                return;
 943
 944        for (i = 0; i < t->entry_count; i++) {
 945                if (t->entries[i]->tree)
 946                        store_tree(t->entries[i]);
 947        }
 948
 949        if (is_null_sha1(root->versions[0].sha1)
 950                        || !find_object(root->versions[0].sha1)) {
 951                lo.data = NULL;
 952                lo.depth = 0;
 953        } else {
 954                lo.data = mktree(t, 0, &lo.len);
 955                lo.depth = t->delta_depth;
 956                hashcpy(lo.sha1, root->versions[0].sha1);
 957        }
 958        vers1dat = mktree(t, 1, &vers1len);
 959
 960        store_object(OBJ_TREE, vers1dat, vers1len,
 961                &lo, root->versions[1].sha1, 0);
 962        /* note: lo.dat (if created) was freed by store_object */
 963        free(vers1dat);
 964
 965        t->delta_depth = lo.depth;
 966        hashcpy(root->versions[0].sha1, root->versions[1].sha1);
 967        for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
 968                struct tree_entry *e = t->entries[i];
 969                if (e->versions[1].mode) {
 970                        e->versions[0].mode = e->versions[1].mode;
 971                        hashcpy(e->versions[0].sha1, e->versions[1].sha1);
 972                        t->entries[j++] = e;
 973                } else {
 974                        release_tree_entry(e);
 975                        del++;
 976                }
 977        }
 978        t->entry_count -= del;
 979}
 980
 981static int tree_content_set(
 982        struct tree_entry *root,
 983        const char *p,
 984        const unsigned char *sha1,
 985        const unsigned int mode)
 986{
 987        struct tree_content *t = root->tree;
 988        const char *slash1;
 989        unsigned int i, n;
 990        struct tree_entry *e;
 991
 992        slash1 = strchr(p, '/');
 993        if (slash1)
 994                n = slash1 - p;
 995        else
 996                n = strlen(p);
 997
 998        for (i = 0; i < t->entry_count; i++) {
 999                e = t->entries[i];
1000                if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1001                        if (!slash1) {
1002                                if (e->versions[1].mode == mode
1003                                                && !hashcmp(e->versions[1].sha1, sha1))
1004                                        return 0;
1005                                e->versions[1].mode = mode;
1006                                hashcpy(e->versions[1].sha1, sha1);
1007                                if (e->tree) {
1008                                        release_tree_content_recursive(e->tree);
1009                                        e->tree = NULL;
1010                                }
1011                                hashclr(root->versions[1].sha1);
1012                                return 1;
1013                        }
1014                        if (!S_ISDIR(e->versions[1].mode)) {
1015                                e->tree = new_tree_content(8);
1016                                e->versions[1].mode = S_IFDIR;
1017                        }
1018                        if (!e->tree)
1019                                load_tree(e);
1020                        if (tree_content_set(e, slash1 + 1, sha1, mode)) {
1021                                hashclr(root->versions[1].sha1);
1022                                return 1;
1023                        }
1024                        return 0;
1025                }
1026        }
1027
1028        if (t->entry_count == t->entry_capacity)
1029                root->tree = t = grow_tree_content(t, 8);
1030        e = new_tree_entry();
1031        e->name = to_atom(p, n);
1032        e->versions[0].mode = 0;
1033        hashclr(e->versions[0].sha1);
1034        t->entries[t->entry_count++] = e;
1035        if (slash1) {
1036                e->tree = new_tree_content(8);
1037                e->versions[1].mode = S_IFDIR;
1038                tree_content_set(e, slash1 + 1, sha1, mode);
1039        } else {
1040                e->tree = NULL;
1041                e->versions[1].mode = mode;
1042                hashcpy(e->versions[1].sha1, sha1);
1043        }
1044        hashclr(root->versions[1].sha1);
1045        return 1;
1046}
1047
1048static int tree_content_remove(struct tree_entry *root, const char *p)
1049{
1050        struct tree_content *t = root->tree;
1051        const char *slash1;
1052        unsigned int i, n;
1053        struct tree_entry *e;
1054
1055        slash1 = strchr(p, '/');
1056        if (slash1)
1057                n = slash1 - p;
1058        else
1059                n = strlen(p);
1060
1061        for (i = 0; i < t->entry_count; i++) {
1062                e = t->entries[i];
1063                if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1064                        if (!slash1 || !S_ISDIR(e->versions[1].mode))
1065                                goto del_entry;
1066                        if (!e->tree)
1067                                load_tree(e);
1068                        if (tree_content_remove(e, slash1 + 1)) {
1069                                if (!e->tree->entry_count)
1070                                        goto del_entry;
1071                                hashclr(root->versions[1].sha1);
1072                                return 1;
1073                        }
1074                        return 0;
1075                }
1076        }
1077        return 0;
1078
1079del_entry:
1080        if (e->tree) {
1081                release_tree_content_recursive(e->tree);
1082                e->tree = NULL;
1083        }
1084        e->versions[1].mode = 0;
1085        hashclr(e->versions[1].sha1);
1086        hashclr(root->versions[1].sha1);
1087        return 1;
1088}
1089
1090static void init_pack_header()
1091{
1092        struct pack_header hdr;
1093
1094        hdr.hdr_signature = htonl(PACK_SIGNATURE);
1095        hdr.hdr_version = htonl(2);
1096        hdr.hdr_entries = 0;
1097
1098        ywrite(pack_fd, &hdr, sizeof(hdr));
1099        pack_size = sizeof(hdr);
1100}
1101
1102static void fixup_header_footer()
1103{
1104        SHA_CTX c;
1105        char hdr[8];
1106        unsigned long cnt;
1107        char *buf;
1108        size_t n;
1109
1110        if (lseek(pack_fd, 0, SEEK_SET) != 0)
1111                die("Failed seeking to start: %s", strerror(errno));
1112
1113        SHA1_Init(&c);
1114        yread(pack_fd, hdr, 8);
1115        SHA1_Update(&c, hdr, 8);
1116
1117        cnt = htonl(object_count);
1118        SHA1_Update(&c, &cnt, 4);
1119        ywrite(pack_fd, &cnt, 4);
1120
1121        buf = xmalloc(128 * 1024);
1122        for (;;) {
1123                n = xread(pack_fd, buf, 128 * 1024);
1124                if (n <= 0)
1125                        break;
1126                SHA1_Update(&c, buf, n);
1127        }
1128        free(buf);
1129
1130        SHA1_Final(pack_sha1, &c);
1131        ywrite(pack_fd, pack_sha1, sizeof(pack_sha1));
1132}
1133
1134static int oecmp (const void *_a, const void *_b)
1135{
1136        struct object_entry *a = *((struct object_entry**)_a);
1137        struct object_entry *b = *((struct object_entry**)_b);
1138        return hashcmp(a->sha1, b->sha1);
1139}
1140
1141static void write_index(const char *idx_name)
1142{
1143        struct sha1file *f;
1144        struct object_entry **idx, **c, **last;
1145        struct object_entry *e;
1146        struct object_entry_pool *o;
1147        unsigned int array[256];
1148        int i;
1149
1150        /* Build the sorted table of object IDs. */
1151        idx = xmalloc(object_count * sizeof(struct object_entry*));
1152        c = idx;
1153        for (o = blocks; o; o = o->next_pool)
1154                for (e = o->entries; e != o->next_free; e++)
1155                        *c++ = e;
1156        last = idx + object_count;
1157        qsort(idx, object_count, sizeof(struct object_entry*), oecmp);
1158
1159        /* Generate the fan-out array. */
1160        c = idx;
1161        for (i = 0; i < 256; i++) {
1162                struct object_entry **next = c;;
1163                while (next < last) {
1164                        if ((*next)->sha1[0] != i)
1165                                break;
1166                        next++;
1167                }
1168                array[i] = htonl(next - idx);
1169                c = next;
1170        }
1171
1172        f = sha1create("%s", idx_name);
1173        sha1write(f, array, 256 * sizeof(int));
1174        for (c = idx; c != last; c++) {
1175                unsigned int offset = htonl((*c)->offset);
1176                sha1write(f, &offset, 4);
1177                sha1write(f, (*c)->sha1, sizeof((*c)->sha1));
1178        }
1179        sha1write(f, pack_sha1, sizeof(pack_sha1));
1180        sha1close(f, NULL, 1);
1181        free(idx);
1182}
1183
1184static void dump_branches()
1185{
1186        static const char *msg = "fast-import";
1187        unsigned int i;
1188        struct branch *b;
1189        struct ref_lock *lock;
1190
1191        for (i = 0; i < branch_table_sz; i++) {
1192                for (b = branch_table[i]; b; b = b->table_next_branch) {
1193                        lock = lock_any_ref_for_update(b->name, NULL, 0);
1194                        if (!lock || write_ref_sha1(lock, b->sha1, msg) < 0)
1195                                die("Can't write %s", b->name);
1196                }
1197        }
1198}
1199
1200static void dump_tags()
1201{
1202        static const char *msg = "fast-import";
1203        struct tag *t;
1204        struct ref_lock *lock;
1205        char path[PATH_MAX];
1206
1207        for (t = first_tag; t; t = t->next_tag) {
1208                sprintf(path, "refs/tags/%s", t->name);
1209                lock = lock_any_ref_for_update(path, NULL, 0);
1210                if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
1211                        die("Can't write %s", path);
1212        }
1213}
1214
1215static void dump_marks_helper(FILE *f,
1216        unsigned long base,
1217        struct mark_set *m)
1218{
1219        int k;
1220        if (m->shift) {
1221                for (k = 0; k < 1024; k++) {
1222                        if (m->data.sets[k])
1223                                dump_marks_helper(f, (base + k) << m->shift,
1224                                        m->data.sets[k]);
1225                }
1226        } else {
1227                for (k = 0; k < 1024; k++) {
1228                        if (m->data.marked[k])
1229                                fprintf(f, ":%lu %s\n", base + k,
1230                                        sha1_to_hex(m->data.marked[k]->sha1));
1231                }
1232        }
1233}
1234
1235static void dump_marks()
1236{
1237        if (mark_file)
1238        {
1239                FILE *f = fopen(mark_file, "w");
1240                dump_marks_helper(f, 0, marks);
1241                fclose(f);
1242        }
1243}
1244
1245static void read_next_command()
1246{
1247        read_line(&command_buf, stdin, '\n');
1248}
1249
1250static void cmd_mark()
1251{
1252        if (!strncmp("mark :", command_buf.buf, 6)) {
1253                next_mark = strtoul(command_buf.buf + 6, NULL, 10);
1254                read_next_command();
1255        }
1256        else
1257                next_mark = 0;
1258}
1259
1260static void* cmd_data (size_t *size)
1261{
1262        size_t n = 0;
1263        void *buffer;
1264        size_t length;
1265
1266        if (strncmp("data ", command_buf.buf, 5))
1267                die("Expected 'data n' command, found: %s", command_buf.buf);
1268
1269        length = strtoul(command_buf.buf + 5, NULL, 10);
1270        buffer = xmalloc(length);
1271
1272        while (n < length) {
1273                size_t s = fread((char*)buffer + n, 1, length - n, stdin);
1274                if (!s && feof(stdin))
1275                        die("EOF in data (%lu bytes remaining)", length - n);
1276                n += s;
1277        }
1278
1279        if (fgetc(stdin) != '\n')
1280                die("An lf did not trail the binary data as expected.");
1281
1282        *size = length;
1283        return buffer;
1284}
1285
1286static void cmd_new_blob()
1287{
1288        size_t l;
1289        void *d;
1290
1291        read_next_command();
1292        cmd_mark();
1293        d = cmd_data(&l);
1294
1295        if (store_object(OBJ_BLOB, d, l, &last_blob, NULL, next_mark))
1296                free(d);
1297}
1298
1299static void unload_one_branch()
1300{
1301        while (cur_active_branches
1302                && cur_active_branches >= max_active_branches) {
1303                unsigned long min_commit = ULONG_MAX;
1304                struct branch *e, *l = NULL, *p = NULL;
1305
1306                for (e = active_branches; e; e = e->active_next_branch) {
1307                        if (e->last_commit < min_commit) {
1308                                p = l;
1309                                min_commit = e->last_commit;
1310                        }
1311                        l = e;
1312                }
1313
1314                if (p) {
1315                        e = p->active_next_branch;
1316                        p->active_next_branch = e->active_next_branch;
1317                } else {
1318                        e = active_branches;
1319                        active_branches = e->active_next_branch;
1320                }
1321                e->active_next_branch = NULL;
1322                if (e->branch_tree.tree) {
1323                        release_tree_content_recursive(e->branch_tree.tree);
1324                        e->branch_tree.tree = NULL;
1325                }
1326                cur_active_branches--;
1327        }
1328}
1329
1330static void load_branch(struct branch *b)
1331{
1332        load_tree(&b->branch_tree);
1333        b->active_next_branch = active_branches;
1334        active_branches = b;
1335        cur_active_branches++;
1336        branch_load_count++;
1337}
1338
1339static void file_change_m(struct branch *b)
1340{
1341        const char *p = command_buf.buf + 2;
1342        char *p_uq;
1343        const char *endp;
1344        struct object_entry *oe;
1345        unsigned char sha1[20];
1346        unsigned int mode;
1347        char type[20];
1348
1349        p = get_mode(p, &mode);
1350        if (!p)
1351                die("Corrupt mode: %s", command_buf.buf);
1352        switch (mode) {
1353        case S_IFREG | 0644:
1354        case S_IFREG | 0755:
1355        case S_IFLNK:
1356        case 0644:
1357        case 0755:
1358                /* ok */
1359                break;
1360        default:
1361                die("Corrupt mode: %s", command_buf.buf);
1362        }
1363
1364        if (*p == ':') {
1365                char *x;
1366                oe = find_mark(strtoul(p + 1, &x, 10));
1367                p = x;
1368        } else {
1369                if (get_sha1_hex(p, sha1))
1370                        die("Invalid SHA1: %s", command_buf.buf);
1371                oe = find_object(sha1);
1372                p += 40;
1373        }
1374        if (*p++ != ' ')
1375                die("Missing space after SHA1: %s", command_buf.buf);
1376
1377        p_uq = unquote_c_style(p, &endp);
1378        if (p_uq) {
1379                if (*endp)
1380                        die("Garbage after path in: %s", command_buf.buf);
1381                p = p_uq;
1382        }
1383
1384        if (oe) {
1385                if (oe->type != OBJ_BLOB)
1386                        die("Not a blob (actually a %s): %s",
1387                                command_buf.buf, type_names[oe->type]);
1388        } else {
1389                if (sha1_object_info(sha1, type, NULL))
1390                        die("Blob not found: %s", command_buf.buf);
1391                if (strcmp(blob_type, type))
1392                        die("Not a blob (actually a %s): %s",
1393                                command_buf.buf, type);
1394        }
1395
1396        tree_content_set(&b->branch_tree, p, sha1, S_IFREG | mode);
1397
1398        if (p_uq)
1399                free(p_uq);
1400}
1401
1402static void file_change_d(struct branch *b)
1403{
1404        const char *p = command_buf.buf + 2;
1405        char *p_uq;
1406        const char *endp;
1407
1408        p_uq = unquote_c_style(p, &endp);
1409        if (p_uq) {
1410                if (*endp)
1411                        die("Garbage after path in: %s", command_buf.buf);
1412                p = p_uq;
1413        }
1414        tree_content_remove(&b->branch_tree, p);
1415        if (p_uq)
1416                free(p_uq);
1417}
1418
1419static void cmd_from(struct branch *b)
1420{
1421        const char *from, *endp;
1422        char *str_uq;
1423        struct branch *s;
1424
1425        if (strncmp("from ", command_buf.buf, 5))
1426                return;
1427
1428        if (b->last_commit)
1429                die("Can't reinitailize branch %s", b->name);
1430
1431        from = strchr(command_buf.buf, ' ') + 1;
1432        str_uq = unquote_c_style(from, &endp);
1433        if (str_uq) {
1434                if (*endp)
1435                        die("Garbage after string in: %s", command_buf.buf);
1436                from = str_uq;
1437        }
1438
1439        s = lookup_branch(from);
1440        if (b == s)
1441                die("Can't create a branch from itself: %s", b->name);
1442        else if (s) {
1443                unsigned char *t = s->branch_tree.versions[1].sha1;
1444                hashcpy(b->sha1, s->sha1);
1445                hashcpy(b->branch_tree.versions[0].sha1, t);
1446                hashcpy(b->branch_tree.versions[1].sha1, t);
1447        } else if (*from == ':') {
1448                unsigned long idnum = strtoul(from + 1, NULL, 10);
1449                struct object_entry *oe = find_mark(idnum);
1450                unsigned long size;
1451                unsigned int depth;
1452                char *buf;
1453                if (oe->type != OBJ_COMMIT)
1454                        die("Mark :%lu not a commit", idnum);
1455                hashcpy(b->sha1, oe->sha1);
1456                buf = unpack_entry(oe->offset, &size, &depth);
1457                if (!buf || size < 46)
1458                        die("Not a valid commit: %s", from);
1459                if (memcmp("tree ", buf, 5)
1460                        || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
1461                        die("The commit %s is corrupt", sha1_to_hex(b->sha1));
1462                free(buf);
1463                hashcpy(b->branch_tree.versions[0].sha1,
1464                        b->branch_tree.versions[1].sha1);
1465        } else if (!get_sha1(from, b->sha1)) {
1466                if (is_null_sha1(b->sha1)) {
1467                        hashclr(b->branch_tree.versions[0].sha1);
1468                        hashclr(b->branch_tree.versions[1].sha1);
1469                } else {
1470                        unsigned long size;
1471                        char *buf;
1472
1473                        buf = read_object_with_reference(b->sha1,
1474                                type_names[OBJ_COMMIT], &size, b->sha1);
1475                        if (!buf || size < 46)
1476                                die("Not a valid commit: %s", from);
1477                        if (memcmp("tree ", buf, 5)
1478                                || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
1479                                die("The commit %s is corrupt", sha1_to_hex(b->sha1));
1480                        free(buf);
1481                        hashcpy(b->branch_tree.versions[0].sha1,
1482                                b->branch_tree.versions[1].sha1);
1483                }
1484        } else
1485                die("Invalid ref name or SHA1 expression: %s", from);
1486
1487        read_next_command();
1488}
1489
1490static void cmd_new_commit()
1491{
1492        struct branch *b;
1493        void *msg;
1494        size_t msglen;
1495        char *str_uq;
1496        const char *endp;
1497        char *sp;
1498        char *author = NULL;
1499        char *committer = NULL;
1500        char *body;
1501
1502        /* Obtain the branch name from the rest of our command */
1503        sp = strchr(command_buf.buf, ' ') + 1;
1504        str_uq = unquote_c_style(sp, &endp);
1505        if (str_uq) {
1506                if (*endp)
1507                        die("Garbage after ref in: %s", command_buf.buf);
1508                sp = str_uq;
1509        }
1510        b = lookup_branch(sp);
1511        if (!b)
1512                b = new_branch(sp);
1513        if (str_uq)
1514                free(str_uq);
1515
1516        read_next_command();
1517        cmd_mark();
1518        if (!strncmp("author ", command_buf.buf, 7)) {
1519                author = strdup(command_buf.buf);
1520                read_next_command();
1521        }
1522        if (!strncmp("committer ", command_buf.buf, 10)) {
1523                committer = strdup(command_buf.buf);
1524                read_next_command();
1525        }
1526        if (!committer)
1527                die("Expected committer but didn't get one");
1528        msg = cmd_data(&msglen);
1529        read_next_command();
1530        cmd_from(b);
1531
1532        /* ensure the branch is active/loaded */
1533        if (!b->branch_tree.tree || !max_active_branches) {
1534                unload_one_branch();
1535                load_branch(b);
1536        }
1537
1538        /* file_change* */
1539        for (;;) {
1540                if (1 == command_buf.len)
1541                        break;
1542                else if (!strncmp("M ", command_buf.buf, 2))
1543                        file_change_m(b);
1544                else if (!strncmp("D ", command_buf.buf, 2))
1545                        file_change_d(b);
1546                else
1547                        die("Unsupported file_change: %s", command_buf.buf);
1548                read_next_command();
1549        }
1550
1551        /* build the tree and the commit */
1552        store_tree(&b->branch_tree);
1553        body = xmalloc(97 + msglen
1554                + (author
1555                        ? strlen(author) + strlen(committer)
1556                        : 2 * strlen(committer)));
1557        sp = body;
1558        sp += sprintf(sp, "tree %s\n",
1559                sha1_to_hex(b->branch_tree.versions[1].sha1));
1560        if (!is_null_sha1(b->sha1))
1561                sp += sprintf(sp, "parent %s\n", sha1_to_hex(b->sha1));
1562        if (author)
1563                sp += sprintf(sp, "%s\n", author);
1564        else
1565                sp += sprintf(sp, "author %s\n", committer + 10);
1566        sp += sprintf(sp, "%s\n\n", committer);
1567        memcpy(sp, msg, msglen);
1568        sp += msglen;
1569        if (author)
1570                free(author);
1571        free(committer);
1572        free(msg);
1573
1574        store_object(OBJ_COMMIT, body, sp - body, NULL, b->sha1, next_mark);
1575        free(body);
1576        b->last_commit = object_count_by_type[OBJ_COMMIT];
1577
1578        if (branch_log) {
1579                int need_dq = quote_c_style(b->name, NULL, NULL, 0);
1580                fprintf(branch_log, "commit ");
1581                if (need_dq) {
1582                        fputc('"', branch_log);
1583                        quote_c_style(b->name, NULL, branch_log, 0);
1584                        fputc('"', branch_log);
1585                } else
1586                        fprintf(branch_log, "%s", b->name);
1587                fprintf(branch_log," :%lu %s\n",next_mark,sha1_to_hex(b->sha1));
1588        }
1589}
1590
1591static void cmd_new_tag()
1592{
1593        char *str_uq;
1594        const char *endp;
1595        char *sp;
1596        const char *from;
1597        char *tagger;
1598        struct branch *s;
1599        void *msg;
1600        size_t msglen;
1601        char *body;
1602        struct tag *t;
1603        unsigned long from_mark = 0;
1604        unsigned char sha1[20];
1605
1606        /* Obtain the new tag name from the rest of our command */
1607        sp = strchr(command_buf.buf, ' ') + 1;
1608        str_uq = unquote_c_style(sp, &endp);
1609        if (str_uq) {
1610                if (*endp)
1611                        die("Garbage after tag name in: %s", command_buf.buf);
1612                sp = str_uq;
1613        }
1614        t = pool_alloc(sizeof(struct tag));
1615        t->next_tag = NULL;
1616        t->name = pool_strdup(sp);
1617        if (last_tag)
1618                last_tag->next_tag = t;
1619        else
1620                first_tag = t;
1621        last_tag = t;
1622        if (str_uq)
1623                free(str_uq);
1624        read_next_command();
1625
1626        /* from ... */
1627        if (strncmp("from ", command_buf.buf, 5))
1628                die("Expected from command, got %s", command_buf.buf);
1629
1630        from = strchr(command_buf.buf, ' ') + 1;
1631        str_uq = unquote_c_style(from, &endp);
1632        if (str_uq) {
1633                if (*endp)
1634                        die("Garbage after string in: %s", command_buf.buf);
1635                from = str_uq;
1636        }
1637
1638        s = lookup_branch(from);
1639        if (s) {
1640                hashcpy(sha1, s->sha1);
1641        } else if (*from == ':') {
1642                from_mark = strtoul(from + 1, NULL, 10);
1643                struct object_entry *oe = find_mark(from_mark);
1644                if (oe->type != OBJ_COMMIT)
1645                        die("Mark :%lu not a commit", from_mark);
1646                hashcpy(sha1, oe->sha1);
1647        } else if (!get_sha1(from, sha1)) {
1648                unsigned long size;
1649                char *buf;
1650
1651                buf = read_object_with_reference(sha1,
1652                        type_names[OBJ_COMMIT], &size, sha1);
1653                if (!buf || size < 46)
1654                        die("Not a valid commit: %s", from);
1655                free(buf);
1656        } else
1657                die("Invalid ref name or SHA1 expression: %s", from);
1658
1659        if (str_uq)
1660                free(str_uq);
1661        read_next_command();
1662
1663        /* tagger ... */
1664        if (strncmp("tagger ", command_buf.buf, 7))
1665                die("Expected tagger command, got %s", command_buf.buf);
1666        tagger = strdup(command_buf.buf);
1667
1668        /* tag payload/message */
1669        read_next_command();
1670        msg = cmd_data(&msglen);
1671
1672        /* build the tag object */
1673        body = xmalloc(67 + strlen(t->name) + strlen(tagger) + msglen);
1674        sp = body;
1675        sp += sprintf(sp, "object %s\n", sha1_to_hex(sha1));
1676        sp += sprintf(sp, "type %s\n", type_names[OBJ_COMMIT]);
1677        sp += sprintf(sp, "tag %s\n", t->name);
1678        sp += sprintf(sp, "%s\n\n", tagger);
1679        memcpy(sp, msg, msglen);
1680        sp += msglen;
1681        free(tagger);
1682        free(msg);
1683
1684        store_object(OBJ_TAG, body, sp - body, NULL, t->sha1, 0);
1685        free(body);
1686
1687        if (branch_log) {
1688                int need_dq = quote_c_style(t->name, NULL, NULL, 0);
1689                fprintf(branch_log, "tag ");
1690                if (need_dq) {
1691                        fputc('"', branch_log);
1692                        quote_c_style(t->name, NULL, branch_log, 0);
1693                        fputc('"', branch_log);
1694                } else
1695                        fprintf(branch_log, "%s", t->name);
1696                fprintf(branch_log," :%lu %s\n",from_mark,sha1_to_hex(t->sha1));
1697        }
1698}
1699
1700static void cmd_reset_branch()
1701{
1702        struct branch *b;
1703        char *str_uq;
1704        const char *endp;
1705        char *sp;
1706
1707        /* Obtain the branch name from the rest of our command */
1708        sp = strchr(command_buf.buf, ' ') + 1;
1709        str_uq = unquote_c_style(sp, &endp);
1710        if (str_uq) {
1711                if (*endp)
1712                        die("Garbage after ref in: %s", command_buf.buf);
1713                sp = str_uq;
1714        }
1715        b = lookup_branch(sp);
1716        if (b) {
1717                b->last_commit = 0;
1718                if (b->branch_tree.tree) {
1719                        release_tree_content_recursive(b->branch_tree.tree);
1720                        b->branch_tree.tree = NULL;
1721                }
1722        }
1723        if (str_uq)
1724                free(str_uq);
1725}
1726
1727static const char fast_import_usage[] =
1728"git-fast-import [--objects=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file] [--branch-log=log] temp.pack";
1729
1730int main(int argc, const char **argv)
1731{
1732        const char *base_name;
1733        int i;
1734        unsigned long est_obj_cnt = 1000;
1735        char *pack_name;
1736        char *idx_name;
1737        struct stat sb;
1738
1739        setup_ident();
1740        git_config(git_default_config);
1741        page_size = getpagesize();
1742
1743        for (i = 1; i < argc; i++) {
1744                const char *a = argv[i];
1745
1746                if (*a != '-' || !strcmp(a, "--"))
1747                        break;
1748                else if (!strncmp(a, "--objects=", 10))
1749                        est_obj_cnt = strtoul(a + 10, NULL, 0);
1750                else if (!strncmp(a, "--depth=", 8))
1751                        max_depth = strtoul(a + 8, NULL, 0);
1752                else if (!strncmp(a, "--active-branches=", 18))
1753                        max_active_branches = strtoul(a + 18, NULL, 0);
1754                else if (!strncmp(a, "--export-marks=", 15))
1755                        mark_file = a + 15;
1756                else if (!strncmp(a, "--branch-log=", 13)) {
1757                        branch_log = fopen(a + 13, "w");
1758                        if (!branch_log)
1759                                die("Can't create %s: %s", a + 13, strerror(errno));
1760                }
1761                else
1762                        die("unknown option %s", a);
1763        }
1764        if ((i+1) != argc)
1765                usage(fast_import_usage);
1766        base_name = argv[i];
1767
1768        pack_name = xmalloc(strlen(base_name) + 6);
1769        sprintf(pack_name, "%s.pack", base_name);
1770        idx_name = xmalloc(strlen(base_name) + 5);
1771        sprintf(idx_name, "%s.idx", base_name);
1772
1773        pack_fd = open(pack_name, O_RDWR|O_CREAT|O_EXCL, 0666);
1774        if (pack_fd < 0)
1775                die("Can't create %s: %s", pack_name, strerror(errno));
1776
1777        init_pack_header();
1778        alloc_objects(est_obj_cnt);
1779        strbuf_init(&command_buf);
1780
1781        atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
1782        branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
1783        avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
1784        marks = pool_calloc(1, sizeof(struct mark_set));
1785
1786        for (;;) {
1787                read_next_command();
1788                if (command_buf.eof)
1789                        break;
1790                else if (!strcmp("blob", command_buf.buf))
1791                        cmd_new_blob();
1792                else if (!strncmp("commit ", command_buf.buf, 7))
1793                        cmd_new_commit();
1794                else if (!strncmp("tag ", command_buf.buf, 4))
1795                        cmd_new_tag();
1796                else if (!strncmp("reset ", command_buf.buf, 6))
1797                        cmd_reset_branch();
1798                else
1799                        die("Unsupported command: %s", command_buf.buf);
1800        }
1801
1802        fixup_header_footer();
1803        close(pack_fd);
1804        write_index(idx_name);
1805        dump_branches();
1806        dump_tags();
1807        dump_marks();
1808        if (branch_log)
1809                fclose(branch_log);
1810
1811        fprintf(stderr, "%s statistics:\n", argv[0]);
1812        fprintf(stderr, "---------------------------------------------------\n");
1813        fprintf(stderr, "Alloc'd objects: %10lu (%10lu overflow  )\n", alloc_count, alloc_count - est_obj_cnt);
1814        fprintf(stderr, "Total objects:   %10lu (%10lu duplicates)\n", object_count, duplicate_count);
1815        fprintf(stderr, "      blobs  :   %10lu (%10lu duplicates %10lu deltas)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB]);
1816        fprintf(stderr, "      trees  :   %10lu (%10lu duplicates %10lu deltas)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE]);
1817        fprintf(stderr, "      commits:   %10lu (%10lu duplicates %10lu deltas)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT]);
1818        fprintf(stderr, "      tags   :   %10lu (%10lu duplicates %10lu deltas)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG]);
1819        fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
1820        fprintf(stderr, "      marks:     %10u (%10lu unique    )\n", (1 << marks->shift) * 1024, marks_set_count);
1821        fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
1822        fprintf(stderr, "Memory total:    %10lu KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
1823        fprintf(stderr, "       pools:    %10lu KiB\n", total_allocd/1024);
1824        fprintf(stderr, "     objects:    %10lu KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
1825        fprintf(stderr, "Pack remaps:     %10lu\n", remap_count);
1826        fprintf(stderr, "---------------------------------------------------\n");
1827
1828        stat(pack_name, &sb);
1829        fprintf(stderr, "Pack size:       %10lu KiB\n", (unsigned long)(sb.st_size/1024));
1830        stat(idx_name, &sb);
1831        fprintf(stderr, "Index size:      %10lu KiB\n", (unsigned long)(sb.st_size/1024));
1832
1833        fprintf(stderr, "\n");
1834
1835        return 0;
1836}