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