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