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