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