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