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