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