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