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