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