fcd9e1e1e3dab46a63cadc93df1e4699e7682cf3
   1/*
   2(See Documentation/git-fast-import.txt for maintained documentation.)
   3Format of STDIN stream:
   4
   5  stream ::= cmd*;
   6
   7  cmd ::= new_blob
   8        | new_commit
   9        | new_tag
  10        | reset_branch
  11        | checkpoint
  12        | progress
  13        ;
  14
  15  new_blob ::= 'blob' lf
  16    mark?
  17    file_content;
  18  file_content ::= data;
  19
  20  new_commit ::= 'commit' sp ref_str lf
  21    mark?
  22    ('author' sp name sp '<' email '>' sp when lf)?
  23    'committer' sp name sp '<' email '>' sp when lf
  24    commit_msg
  25    ('from' sp committish lf)?
  26    ('merge' sp committish lf)*
  27    file_change*
  28    lf?;
  29  commit_msg ::= data;
  30
  31  file_change ::= file_clr
  32    | file_del
  33    | file_rnm
  34    | file_cpy
  35    | file_obm
  36    | file_inm;
  37  file_clr ::= 'deleteall' lf;
  38  file_del ::= 'D' sp path_str lf;
  39  file_rnm ::= 'R' sp path_str sp path_str lf;
  40  file_cpy ::= 'C' sp path_str sp path_str lf;
  41  file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf;
  42  file_inm ::= 'M' sp mode sp 'inline' sp path_str lf
  43    data;
  44  note_obm ::= 'N' sp (hexsha1 | idnum) sp committish lf;
  45  note_inm ::= 'N' sp 'inline' sp committish lf
  46    data;
  47
  48  new_tag ::= 'tag' sp tag_str lf
  49    'from' sp committish lf
  50    ('tagger' sp name sp '<' email '>' sp when lf)?
  51    tag_msg;
  52  tag_msg ::= data;
  53
  54  reset_branch ::= 'reset' sp ref_str lf
  55    ('from' sp committish lf)?
  56    lf?;
  57
  58  checkpoint ::= 'checkpoint' lf
  59    lf?;
  60
  61  progress ::= 'progress' sp not_lf* lf
  62    lf?;
  63
  64     # note: the first idnum in a stream should be 1 and subsequent
  65     # idnums should not have gaps between values as this will cause
  66     # the stream parser to reserve space for the gapped values.  An
  67     # idnum can be updated in the future to a new object by issuing
  68     # a new mark directive with the old idnum.
  69     #
  70  mark ::= 'mark' sp idnum lf;
  71  data ::= (delimited_data | exact_data)
  72    lf?;
  73
  74    # note: delim may be any string but must not contain lf.
  75    # data_line may contain any data but must not be exactly
  76    # delim.
  77  delimited_data ::= 'data' sp '<<' delim lf
  78    (data_line lf)*
  79    delim lf;
  80
  81     # note: declen indicates the length of binary_data in bytes.
  82     # declen does not include the lf preceding the binary data.
  83     #
  84  exact_data ::= 'data' sp declen lf
  85    binary_data;
  86
  87     # note: quoted strings are C-style quoting supporting \c for
  88     # common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn
  89     # is the signed byte value in octal.  Note that the only
  90     # characters which must actually be escaped to protect the
  91     # stream formatting is: \, " and LF.  Otherwise these values
  92     # are UTF8.
  93     #
  94  committish  ::= (ref_str | hexsha1 | sha1exp_str | idnum);
  95  ref_str     ::= ref;
  96  sha1exp_str ::= sha1exp;
  97  tag_str     ::= tag;
  98  path_str    ::= path    | '"' quoted(path)    '"' ;
  99  mode        ::= '100644' | '644'
 100                | '100755' | '755'
 101                | '120000'
 102                ;
 103
 104  declen ::= # unsigned 32 bit value, ascii base10 notation;
 105  bigint ::= # unsigned integer value, ascii base10 notation;
 106  binary_data ::= # file content, not interpreted;
 107
 108  when         ::= raw_when | rfc2822_when;
 109  raw_when     ::= ts sp tz;
 110  rfc2822_when ::= # Valid RFC 2822 date and time;
 111
 112  sp ::= # ASCII space character;
 113  lf ::= # ASCII newline (LF) character;
 114
 115     # note: a colon (':') must precede the numerical value assigned to
 116     # an idnum.  This is to distinguish it from a ref or tag name as
 117     # GIT does not permit ':' in ref or tag strings.
 118     #
 119  idnum   ::= ':' bigint;
 120  path    ::= # GIT style file path, e.g. "a/b/c";
 121  ref     ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT";
 122  tag     ::= # GIT tag name, e.g. "FIREFOX_1_5";
 123  sha1exp ::= # Any valid GIT SHA1 expression;
 124  hexsha1 ::= # SHA1 in hexadecimal format;
 125
 126     # note: name and email are UTF8 strings, however name must not
 127     # contain '<' or lf and email must not contain any of the
 128     # following: '<', '>', lf.
 129     #
 130  name  ::= # valid GIT author/committer name;
 131  email ::= # valid GIT author/committer email;
 132  ts    ::= # time since the epoch in seconds, ascii base10 notation;
 133  tz    ::= # GIT style timezone;
 134
 135     # note: comments may appear anywhere in the input, except
 136     # within a data command.  Any form of the data command
 137     # always escapes the related input from comment processing.
 138     #
 139     # In case it is not clear, the '#' that starts the comment
 140     # must be the first character on that line (an lf
 141     # preceded it).
 142     #
 143  comment ::= '#' not_lf* lf;
 144  not_lf  ::= # Any byte that is not ASCII newline (LF);
 145*/
 146
 147#include "builtin.h"
 148#include "cache.h"
 149#include "object.h"
 150#include "blob.h"
 151#include "tree.h"
 152#include "commit.h"
 153#include "delta.h"
 154#include "pack.h"
 155#include "refs.h"
 156#include "csum-file.h"
 157#include "quote.h"
 158#include "exec_cmd.h"
 159
 160#define PACK_ID_BITS 16
 161#define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
 162#define DEPTH_BITS 13
 163#define MAX_DEPTH ((1<<DEPTH_BITS)-1)
 164
 165struct object_entry
 166{
 167        struct object_entry *next;
 168        uint32_t offset;
 169        uint32_t type : TYPE_BITS,
 170                pack_id : PACK_ID_BITS,
 171                depth : DEPTH_BITS;
 172        unsigned char sha1[20];
 173};
 174
 175struct object_entry_pool
 176{
 177        struct object_entry_pool *next_pool;
 178        struct object_entry *next_free;
 179        struct object_entry *end;
 180        struct object_entry entries[FLEX_ARRAY]; /* more */
 181};
 182
 183struct mark_set
 184{
 185        union {
 186                struct object_entry *marked[1024];
 187                struct mark_set *sets[1024];
 188        } data;
 189        unsigned int shift;
 190};
 191
 192struct last_object
 193{
 194        struct strbuf data;
 195        uint32_t offset;
 196        unsigned int depth;
 197        unsigned no_swap : 1;
 198};
 199
 200struct mem_pool
 201{
 202        struct mem_pool *next_pool;
 203        char *next_free;
 204        char *end;
 205        uintmax_t space[FLEX_ARRAY]; /* more */
 206};
 207
 208struct atom_str
 209{
 210        struct atom_str *next_atom;
 211        unsigned short str_len;
 212        char str_dat[FLEX_ARRAY]; /* more */
 213};
 214
 215struct tree_content;
 216struct tree_entry
 217{
 218        struct tree_content *tree;
 219        struct atom_str *name;
 220        struct tree_entry_ms
 221        {
 222                uint16_t mode;
 223                unsigned char sha1[20];
 224        } versions[2];
 225};
 226
 227struct tree_content
 228{
 229        unsigned int entry_capacity; /* must match avail_tree_content */
 230        unsigned int entry_count;
 231        unsigned int delta_depth;
 232        struct tree_entry *entries[FLEX_ARRAY]; /* more */
 233};
 234
 235struct avail_tree_content
 236{
 237        unsigned int entry_capacity; /* must match tree_content */
 238        struct avail_tree_content *next_avail;
 239};
 240
 241struct branch
 242{
 243        struct branch *table_next_branch;
 244        struct branch *active_next_branch;
 245        const char *name;
 246        struct tree_entry branch_tree;
 247        uintmax_t last_commit;
 248        unsigned active : 1;
 249        unsigned pack_id : PACK_ID_BITS;
 250        unsigned char sha1[20];
 251};
 252
 253struct tag
 254{
 255        struct tag *next_tag;
 256        const char *name;
 257        unsigned int pack_id;
 258        unsigned char sha1[20];
 259};
 260
 261struct hash_list
 262{
 263        struct hash_list *next;
 264        unsigned char sha1[20];
 265};
 266
 267typedef enum {
 268        WHENSPEC_RAW = 1,
 269        WHENSPEC_RFC2822,
 270        WHENSPEC_NOW,
 271} whenspec_type;
 272
 273struct recent_command
 274{
 275        struct recent_command *prev;
 276        struct recent_command *next;
 277        char *buf;
 278};
 279
 280/* Configured limits on output */
 281static unsigned long max_depth = 10;
 282static off_t max_packsize = (1LL << 32) - 1;
 283static int force_update;
 284static int pack_compression_level = Z_DEFAULT_COMPRESSION;
 285static int pack_compression_seen;
 286
 287/* Stats and misc. counters */
 288static uintmax_t alloc_count;
 289static uintmax_t marks_set_count;
 290static uintmax_t object_count_by_type[1 << TYPE_BITS];
 291static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
 292static uintmax_t delta_count_by_type[1 << TYPE_BITS];
 293static unsigned long object_count;
 294static unsigned long branch_count;
 295static unsigned long branch_load_count;
 296static int failure;
 297static FILE *pack_edges;
 298static unsigned int show_stats = 1;
 299
 300/* Memory pools */
 301static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
 302static size_t total_allocd;
 303static struct mem_pool *mem_pool;
 304
 305/* Atom management */
 306static unsigned int atom_table_sz = 4451;
 307static unsigned int atom_cnt;
 308static struct atom_str **atom_table;
 309
 310/* The .pack file being generated */
 311static unsigned int pack_id;
 312static struct packed_git *pack_data;
 313static struct packed_git **all_packs;
 314static unsigned long pack_size;
 315
 316/* Table of objects we've written. */
 317static unsigned int object_entry_alloc = 5000;
 318static struct object_entry_pool *blocks;
 319static struct object_entry *object_table[1 << 16];
 320static struct mark_set *marks;
 321static const char *mark_file;
 322
 323/* Our last blob */
 324static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
 325
 326/* Tree management */
 327static unsigned int tree_entry_alloc = 1000;
 328static void *avail_tree_entry;
 329static unsigned int avail_tree_table_sz = 100;
 330static struct avail_tree_content **avail_tree_table;
 331static struct strbuf old_tree = STRBUF_INIT;
 332static struct strbuf new_tree = STRBUF_INIT;
 333
 334/* Branch data */
 335static unsigned long max_active_branches = 5;
 336static unsigned long cur_active_branches;
 337static unsigned long branch_table_sz = 1039;
 338static struct branch **branch_table;
 339static struct branch *active_branches;
 340
 341/* Tag data */
 342static struct tag *first_tag;
 343static struct tag *last_tag;
 344
 345/* Input stream parsing */
 346static whenspec_type whenspec = WHENSPEC_RAW;
 347static struct strbuf command_buf = STRBUF_INIT;
 348static int unread_command_buf;
 349static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
 350static struct recent_command *cmd_tail = &cmd_hist;
 351static struct recent_command *rc_free;
 352static unsigned int cmd_save = 100;
 353static uintmax_t next_mark;
 354static struct strbuf new_data = STRBUF_INIT;
 355
 356static void write_branch_report(FILE *rpt, struct branch *b)
 357{
 358        fprintf(rpt, "%s:\n", b->name);
 359
 360        fprintf(rpt, "  status      :");
 361        if (b->active)
 362                fputs(" active", rpt);
 363        if (b->branch_tree.tree)
 364                fputs(" loaded", rpt);
 365        if (is_null_sha1(b->branch_tree.versions[1].sha1))
 366                fputs(" dirty", rpt);
 367        fputc('\n', rpt);
 368
 369        fprintf(rpt, "  tip commit  : %s\n", sha1_to_hex(b->sha1));
 370        fprintf(rpt, "  old tree    : %s\n", sha1_to_hex(b->branch_tree.versions[0].sha1));
 371        fprintf(rpt, "  cur tree    : %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1));
 372        fprintf(rpt, "  commit clock: %" PRIuMAX "\n", b->last_commit);
 373
 374        fputs("  last pack   : ", rpt);
 375        if (b->pack_id < MAX_PACK_ID)
 376                fprintf(rpt, "%u", b->pack_id);
 377        fputc('\n', rpt);
 378
 379        fputc('\n', rpt);
 380}
 381
 382static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *);
 383
 384static void write_crash_report(const char *err)
 385{
 386        char *loc = git_path("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
 387        FILE *rpt = fopen(loc, "w");
 388        struct branch *b;
 389        unsigned long lu;
 390        struct recent_command *rc;
 391
 392        if (!rpt) {
 393                error("can't write crash report %s: %s", loc, strerror(errno));
 394                return;
 395        }
 396
 397        fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
 398
 399        fprintf(rpt, "fast-import crash report:\n");
 400        fprintf(rpt, "    fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
 401        fprintf(rpt, "    parent process     : %"PRIuMAX"\n", (uintmax_t) getppid());
 402        fprintf(rpt, "    at %s\n", show_date(time(NULL), 0, DATE_LOCAL));
 403        fputc('\n', rpt);
 404
 405        fputs("fatal: ", rpt);
 406        fputs(err, rpt);
 407        fputc('\n', rpt);
 408
 409        fputc('\n', rpt);
 410        fputs("Most Recent Commands Before Crash\n", rpt);
 411        fputs("---------------------------------\n", rpt);
 412        for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
 413                if (rc->next == &cmd_hist)
 414                        fputs("* ", rpt);
 415                else
 416                        fputs("  ", rpt);
 417                fputs(rc->buf, rpt);
 418                fputc('\n', rpt);
 419        }
 420
 421        fputc('\n', rpt);
 422        fputs("Active Branch LRU\n", rpt);
 423        fputs("-----------------\n", rpt);
 424        fprintf(rpt, "    active_branches = %lu cur, %lu max\n",
 425                cur_active_branches,
 426                max_active_branches);
 427        fputc('\n', rpt);
 428        fputs("  pos  clock name\n", rpt);
 429        fputs("  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
 430        for (b = active_branches, lu = 0; b; b = b->active_next_branch)
 431                fprintf(rpt, "  %2lu) %6" PRIuMAX" %s\n",
 432                        ++lu, b->last_commit, b->name);
 433
 434        fputc('\n', rpt);
 435        fputs("Inactive Branches\n", rpt);
 436        fputs("-----------------\n", rpt);
 437        for (lu = 0; lu < branch_table_sz; lu++) {
 438                for (b = branch_table[lu]; b; b = b->table_next_branch)
 439                        write_branch_report(rpt, b);
 440        }
 441
 442        if (first_tag) {
 443                struct tag *tg;
 444                fputc('\n', rpt);
 445                fputs("Annotated Tags\n", rpt);
 446                fputs("--------------\n", rpt);
 447                for (tg = first_tag; tg; tg = tg->next_tag) {
 448                        fputs(sha1_to_hex(tg->sha1), rpt);
 449                        fputc(' ', rpt);
 450                        fputs(tg->name, rpt);
 451                        fputc('\n', rpt);
 452                }
 453        }
 454
 455        fputc('\n', rpt);
 456        fputs("Marks\n", rpt);
 457        fputs("-----\n", rpt);
 458        if (mark_file)
 459                fprintf(rpt, "  exported to %s\n", mark_file);
 460        else
 461                dump_marks_helper(rpt, 0, marks);
 462
 463        fputc('\n', rpt);
 464        fputs("-------------------\n", rpt);
 465        fputs("END OF CRASH REPORT\n", rpt);
 466        fclose(rpt);
 467}
 468
 469static void end_packfile(void);
 470static void unkeep_all_packs(void);
 471static void dump_marks(void);
 472
 473static NORETURN void die_nicely(const char *err, va_list params)
 474{
 475        static int zombie;
 476        char message[2 * PATH_MAX];
 477
 478        vsnprintf(message, sizeof(message), err, params);
 479        fputs("fatal: ", stderr);
 480        fputs(message, stderr);
 481        fputc('\n', stderr);
 482
 483        if (!zombie) {
 484                zombie = 1;
 485                write_crash_report(message);
 486                end_packfile();
 487                unkeep_all_packs();
 488                dump_marks();
 489        }
 490        exit(128);
 491}
 492
 493static void alloc_objects(unsigned int cnt)
 494{
 495        struct object_entry_pool *b;
 496
 497        b = xmalloc(sizeof(struct object_entry_pool)
 498                + cnt * sizeof(struct object_entry));
 499        b->next_pool = blocks;
 500        b->next_free = b->entries;
 501        b->end = b->entries + cnt;
 502        blocks = b;
 503        alloc_count += cnt;
 504}
 505
 506static struct object_entry *new_object(unsigned char *sha1)
 507{
 508        struct object_entry *e;
 509
 510        if (blocks->next_free == blocks->end)
 511                alloc_objects(object_entry_alloc);
 512
 513        e = blocks->next_free++;
 514        hashcpy(e->sha1, sha1);
 515        return e;
 516}
 517
 518static struct object_entry *find_object(unsigned char *sha1)
 519{
 520        unsigned int h = sha1[0] << 8 | sha1[1];
 521        struct object_entry *e;
 522        for (e = object_table[h]; e; e = e->next)
 523                if (!hashcmp(sha1, e->sha1))
 524                        return e;
 525        return NULL;
 526}
 527
 528static struct object_entry *insert_object(unsigned char *sha1)
 529{
 530        unsigned int h = sha1[0] << 8 | sha1[1];
 531        struct object_entry *e = object_table[h];
 532        struct object_entry *p = NULL;
 533
 534        while (e) {
 535                if (!hashcmp(sha1, e->sha1))
 536                        return e;
 537                p = e;
 538                e = e->next;
 539        }
 540
 541        e = new_object(sha1);
 542        e->next = NULL;
 543        e->offset = 0;
 544        if (p)
 545                p->next = e;
 546        else
 547                object_table[h] = e;
 548        return e;
 549}
 550
 551static unsigned int hc_str(const char *s, size_t len)
 552{
 553        unsigned int r = 0;
 554        while (len-- > 0)
 555                r = r * 31 + *s++;
 556        return r;
 557}
 558
 559static void *pool_alloc(size_t len)
 560{
 561        struct mem_pool *p;
 562        void *r;
 563
 564        /* round up to a 'uintmax_t' alignment */
 565        if (len & (sizeof(uintmax_t) - 1))
 566                len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
 567
 568        for (p = mem_pool; p; p = p->next_pool)
 569                if ((p->end - p->next_free >= len))
 570                        break;
 571
 572        if (!p) {
 573                if (len >= (mem_pool_alloc/2)) {
 574                        total_allocd += len;
 575                        return xmalloc(len);
 576                }
 577                total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
 578                p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc);
 579                p->next_pool = mem_pool;
 580                p->next_free = (char *) p->space;
 581                p->end = p->next_free + mem_pool_alloc;
 582                mem_pool = p;
 583        }
 584
 585        r = p->next_free;
 586        p->next_free += len;
 587        return r;
 588}
 589
 590static void *pool_calloc(size_t count, size_t size)
 591{
 592        size_t len = count * size;
 593        void *r = pool_alloc(len);
 594        memset(r, 0, len);
 595        return r;
 596}
 597
 598static char *pool_strdup(const char *s)
 599{
 600        char *r = pool_alloc(strlen(s) + 1);
 601        strcpy(r, s);
 602        return r;
 603}
 604
 605static void insert_mark(uintmax_t idnum, struct object_entry *oe)
 606{
 607        struct mark_set *s = marks;
 608        while ((idnum >> s->shift) >= 1024) {
 609                s = pool_calloc(1, sizeof(struct mark_set));
 610                s->shift = marks->shift + 10;
 611                s->data.sets[0] = marks;
 612                marks = s;
 613        }
 614        while (s->shift) {
 615                uintmax_t i = idnum >> s->shift;
 616                idnum -= i << s->shift;
 617                if (!s->data.sets[i]) {
 618                        s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
 619                        s->data.sets[i]->shift = s->shift - 10;
 620                }
 621                s = s->data.sets[i];
 622        }
 623        if (!s->data.marked[idnum])
 624                marks_set_count++;
 625        s->data.marked[idnum] = oe;
 626}
 627
 628static struct object_entry *find_mark(uintmax_t idnum)
 629{
 630        uintmax_t orig_idnum = idnum;
 631        struct mark_set *s = marks;
 632        struct object_entry *oe = NULL;
 633        if ((idnum >> s->shift) < 1024) {
 634                while (s && s->shift) {
 635                        uintmax_t i = idnum >> s->shift;
 636                        idnum -= i << s->shift;
 637                        s = s->data.sets[i];
 638                }
 639                if (s)
 640                        oe = s->data.marked[idnum];
 641        }
 642        if (!oe)
 643                die("mark :%" PRIuMAX " not declared", orig_idnum);
 644        return oe;
 645}
 646
 647static struct atom_str *to_atom(const char *s, unsigned short len)
 648{
 649        unsigned int hc = hc_str(s, len) % atom_table_sz;
 650        struct atom_str *c;
 651
 652        for (c = atom_table[hc]; c; c = c->next_atom)
 653                if (c->str_len == len && !strncmp(s, c->str_dat, len))
 654                        return c;
 655
 656        c = pool_alloc(sizeof(struct atom_str) + len + 1);
 657        c->str_len = len;
 658        strncpy(c->str_dat, s, len);
 659        c->str_dat[len] = 0;
 660        c->next_atom = atom_table[hc];
 661        atom_table[hc] = c;
 662        atom_cnt++;
 663        return c;
 664}
 665
 666static struct branch *lookup_branch(const char *name)
 667{
 668        unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
 669        struct branch *b;
 670
 671        for (b = branch_table[hc]; b; b = b->table_next_branch)
 672                if (!strcmp(name, b->name))
 673                        return b;
 674        return NULL;
 675}
 676
 677static struct branch *new_branch(const char *name)
 678{
 679        unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
 680        struct branch *b = lookup_branch(name);
 681
 682        if (b)
 683                die("Invalid attempt to create duplicate branch: %s", name);
 684        switch (check_ref_format(name)) {
 685        case 0: break; /* its valid */
 686        case CHECK_REF_FORMAT_ONELEVEL:
 687                break; /* valid, but too few '/', allow anyway */
 688        default:
 689                die("Branch name doesn't conform to GIT standards: %s", name);
 690        }
 691
 692        b = pool_calloc(1, sizeof(struct branch));
 693        b->name = pool_strdup(name);
 694        b->table_next_branch = branch_table[hc];
 695        b->branch_tree.versions[0].mode = S_IFDIR;
 696        b->branch_tree.versions[1].mode = S_IFDIR;
 697        b->active = 0;
 698        b->pack_id = MAX_PACK_ID;
 699        branch_table[hc] = b;
 700        branch_count++;
 701        return b;
 702}
 703
 704static unsigned int hc_entries(unsigned int cnt)
 705{
 706        cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
 707        return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
 708}
 709
 710static struct tree_content *new_tree_content(unsigned int cnt)
 711{
 712        struct avail_tree_content *f, *l = NULL;
 713        struct tree_content *t;
 714        unsigned int hc = hc_entries(cnt);
 715
 716        for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
 717                if (f->entry_capacity >= cnt)
 718                        break;
 719
 720        if (f) {
 721                if (l)
 722                        l->next_avail = f->next_avail;
 723                else
 724                        avail_tree_table[hc] = f->next_avail;
 725        } else {
 726                cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
 727                f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
 728                f->entry_capacity = cnt;
 729        }
 730
 731        t = (struct tree_content*)f;
 732        t->entry_count = 0;
 733        t->delta_depth = 0;
 734        return t;
 735}
 736
 737static void release_tree_entry(struct tree_entry *e);
 738static void release_tree_content(struct tree_content *t)
 739{
 740        struct avail_tree_content *f = (struct avail_tree_content*)t;
 741        unsigned int hc = hc_entries(f->entry_capacity);
 742        f->next_avail = avail_tree_table[hc];
 743        avail_tree_table[hc] = f;
 744}
 745
 746static void release_tree_content_recursive(struct tree_content *t)
 747{
 748        unsigned int i;
 749        for (i = 0; i < t->entry_count; i++)
 750                release_tree_entry(t->entries[i]);
 751        release_tree_content(t);
 752}
 753
 754static struct tree_content *grow_tree_content(
 755        struct tree_content *t,
 756        int amt)
 757{
 758        struct tree_content *r = new_tree_content(t->entry_count + amt);
 759        r->entry_count = t->entry_count;
 760        r->delta_depth = t->delta_depth;
 761        memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
 762        release_tree_content(t);
 763        return r;
 764}
 765
 766static struct tree_entry *new_tree_entry(void)
 767{
 768        struct tree_entry *e;
 769
 770        if (!avail_tree_entry) {
 771                unsigned int n = tree_entry_alloc;
 772                total_allocd += n * sizeof(struct tree_entry);
 773                avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry));
 774                while (n-- > 1) {
 775                        *((void**)e) = e + 1;
 776                        e++;
 777                }
 778                *((void**)e) = NULL;
 779        }
 780
 781        e = avail_tree_entry;
 782        avail_tree_entry = *((void**)e);
 783        return e;
 784}
 785
 786static void release_tree_entry(struct tree_entry *e)
 787{
 788        if (e->tree)
 789                release_tree_content_recursive(e->tree);
 790        *((void**)e) = avail_tree_entry;
 791        avail_tree_entry = e;
 792}
 793
 794static struct tree_content *dup_tree_content(struct tree_content *s)
 795{
 796        struct tree_content *d;
 797        struct tree_entry *a, *b;
 798        unsigned int i;
 799
 800        if (!s)
 801                return NULL;
 802        d = new_tree_content(s->entry_count);
 803        for (i = 0; i < s->entry_count; i++) {
 804                a = s->entries[i];
 805                b = new_tree_entry();
 806                memcpy(b, a, sizeof(*a));
 807                if (a->tree && is_null_sha1(b->versions[1].sha1))
 808                        b->tree = dup_tree_content(a->tree);
 809                else
 810                        b->tree = NULL;
 811                d->entries[i] = b;
 812        }
 813        d->entry_count = s->entry_count;
 814        d->delta_depth = s->delta_depth;
 815
 816        return d;
 817}
 818
 819static void start_packfile(void)
 820{
 821        static char tmpfile[PATH_MAX];
 822        struct packed_git *p;
 823        struct pack_header hdr;
 824        int pack_fd;
 825
 826        pack_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
 827                              "pack/tmp_pack_XXXXXX");
 828        p = xcalloc(1, sizeof(*p) + strlen(tmpfile) + 2);
 829        strcpy(p->pack_name, tmpfile);
 830        p->pack_fd = pack_fd;
 831
 832        hdr.hdr_signature = htonl(PACK_SIGNATURE);
 833        hdr.hdr_version = htonl(2);
 834        hdr.hdr_entries = 0;
 835        write_or_die(p->pack_fd, &hdr, sizeof(hdr));
 836
 837        pack_data = p;
 838        pack_size = sizeof(hdr);
 839        object_count = 0;
 840
 841        all_packs = xrealloc(all_packs, sizeof(*all_packs) * (pack_id + 1));
 842        all_packs[pack_id] = p;
 843}
 844
 845static int oecmp (const void *a_, const void *b_)
 846{
 847        struct object_entry *a = *((struct object_entry**)a_);
 848        struct object_entry *b = *((struct object_entry**)b_);
 849        return hashcmp(a->sha1, b->sha1);
 850}
 851
 852static char *create_index(void)
 853{
 854        static char tmpfile[PATH_MAX];
 855        git_SHA_CTX ctx;
 856        struct sha1file *f;
 857        struct object_entry **idx, **c, **last, *e;
 858        struct object_entry_pool *o;
 859        uint32_t array[256];
 860        int i, idx_fd;
 861
 862        /* Build the sorted table of object IDs. */
 863        idx = xmalloc(object_count * sizeof(struct object_entry*));
 864        c = idx;
 865        for (o = blocks; o; o = o->next_pool)
 866                for (e = o->next_free; e-- != o->entries;)
 867                        if (pack_id == e->pack_id)
 868                                *c++ = e;
 869        last = idx + object_count;
 870        if (c != last)
 871                die("internal consistency error creating the index");
 872        qsort(idx, object_count, sizeof(struct object_entry*), oecmp);
 873
 874        /* Generate the fan-out array. */
 875        c = idx;
 876        for (i = 0; i < 256; i++) {
 877                struct object_entry **next = c;
 878                while (next < last) {
 879                        if ((*next)->sha1[0] != i)
 880                                break;
 881                        next++;
 882                }
 883                array[i] = htonl(next - idx);
 884                c = next;
 885        }
 886
 887        idx_fd = odb_mkstemp(tmpfile, sizeof(tmpfile),
 888                             "pack/tmp_idx_XXXXXX");
 889        f = sha1fd(idx_fd, tmpfile);
 890        sha1write(f, array, 256 * sizeof(int));
 891        git_SHA1_Init(&ctx);
 892        for (c = idx; c != last; c++) {
 893                uint32_t offset = htonl((*c)->offset);
 894                sha1write(f, &offset, 4);
 895                sha1write(f, (*c)->sha1, sizeof((*c)->sha1));
 896                git_SHA1_Update(&ctx, (*c)->sha1, 20);
 897        }
 898        sha1write(f, pack_data->sha1, sizeof(pack_data->sha1));
 899        sha1close(f, NULL, CSUM_FSYNC);
 900        free(idx);
 901        git_SHA1_Final(pack_data->sha1, &ctx);
 902        return tmpfile;
 903}
 904
 905static char *keep_pack(char *curr_index_name)
 906{
 907        static char name[PATH_MAX];
 908        static const char *keep_msg = "fast-import";
 909        int keep_fd;
 910
 911        keep_fd = odb_pack_keep(name, sizeof(name), pack_data->sha1);
 912        if (keep_fd < 0)
 913                die_errno("cannot create keep file");
 914        write_or_die(keep_fd, keep_msg, strlen(keep_msg));
 915        if (close(keep_fd))
 916                die_errno("failed to write keep file");
 917
 918        snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
 919                 get_object_directory(), sha1_to_hex(pack_data->sha1));
 920        if (move_temp_to_file(pack_data->pack_name, name))
 921                die("cannot store pack file");
 922
 923        snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
 924                 get_object_directory(), sha1_to_hex(pack_data->sha1));
 925        if (move_temp_to_file(curr_index_name, name))
 926                die("cannot store index file");
 927        return name;
 928}
 929
 930static void unkeep_all_packs(void)
 931{
 932        static char name[PATH_MAX];
 933        int k;
 934
 935        for (k = 0; k < pack_id; k++) {
 936                struct packed_git *p = all_packs[k];
 937                snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
 938                         get_object_directory(), sha1_to_hex(p->sha1));
 939                unlink_or_warn(name);
 940        }
 941}
 942
 943static void end_packfile(void)
 944{
 945        struct packed_git *old_p = pack_data, *new_p;
 946
 947        clear_delta_base_cache();
 948        if (object_count) {
 949                char *idx_name;
 950                int i;
 951                struct branch *b;
 952                struct tag *t;
 953
 954                close_pack_windows(pack_data);
 955                fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
 956                                    pack_data->pack_name, object_count,
 957                                    NULL, 0);
 958                close(pack_data->pack_fd);
 959                idx_name = keep_pack(create_index());
 960
 961                /* Register the packfile with core git's machinery. */
 962                new_p = add_packed_git(idx_name, strlen(idx_name), 1);
 963                if (!new_p)
 964                        die("core git rejected index %s", idx_name);
 965                all_packs[pack_id] = new_p;
 966                install_packed_git(new_p);
 967
 968                /* Print the boundary */
 969                if (pack_edges) {
 970                        fprintf(pack_edges, "%s:", new_p->pack_name);
 971                        for (i = 0; i < branch_table_sz; i++) {
 972                                for (b = branch_table[i]; b; b = b->table_next_branch) {
 973                                        if (b->pack_id == pack_id)
 974                                                fprintf(pack_edges, " %s", sha1_to_hex(b->sha1));
 975                                }
 976                        }
 977                        for (t = first_tag; t; t = t->next_tag) {
 978                                if (t->pack_id == pack_id)
 979                                        fprintf(pack_edges, " %s", sha1_to_hex(t->sha1));
 980                        }
 981                        fputc('\n', pack_edges);
 982                        fflush(pack_edges);
 983                }
 984
 985                pack_id++;
 986        }
 987        else {
 988                close(old_p->pack_fd);
 989                unlink_or_warn(old_p->pack_name);
 990        }
 991        free(old_p);
 992
 993        /* We can't carry a delta across packfiles. */
 994        strbuf_release(&last_blob.data);
 995        last_blob.offset = 0;
 996        last_blob.depth = 0;
 997}
 998
 999static void cycle_packfile(void)
1000{
1001        end_packfile();
1002        start_packfile();
1003}
1004
1005static size_t encode_header(
1006        enum object_type type,
1007        size_t size,
1008        unsigned char *hdr)
1009{
1010        int n = 1;
1011        unsigned char c;
1012
1013        if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
1014                die("bad type %d", type);
1015
1016        c = (type << 4) | (size & 15);
1017        size >>= 4;
1018        while (size) {
1019                *hdr++ = c | 0x80;
1020                c = size & 0x7f;
1021                size >>= 7;
1022                n++;
1023        }
1024        *hdr = c;
1025        return n;
1026}
1027
1028static int store_object(
1029        enum object_type type,
1030        struct strbuf *dat,
1031        struct last_object *last,
1032        unsigned char *sha1out,
1033        uintmax_t mark)
1034{
1035        void *out, *delta;
1036        struct object_entry *e;
1037        unsigned char hdr[96];
1038        unsigned char sha1[20];
1039        unsigned long hdrlen, deltalen;
1040        git_SHA_CTX c;
1041        z_stream s;
1042
1043        hdrlen = sprintf((char *)hdr,"%s %lu", typename(type),
1044                (unsigned long)dat->len) + 1;
1045        git_SHA1_Init(&c);
1046        git_SHA1_Update(&c, hdr, hdrlen);
1047        git_SHA1_Update(&c, dat->buf, dat->len);
1048        git_SHA1_Final(sha1, &c);
1049        if (sha1out)
1050                hashcpy(sha1out, sha1);
1051
1052        e = insert_object(sha1);
1053        if (mark)
1054                insert_mark(mark, e);
1055        if (e->offset) {
1056                duplicate_count_by_type[type]++;
1057                return 1;
1058        } else if (find_sha1_pack(sha1, packed_git)) {
1059                e->type = type;
1060                e->pack_id = MAX_PACK_ID;
1061                e->offset = 1; /* just not zero! */
1062                duplicate_count_by_type[type]++;
1063                return 1;
1064        }
1065
1066        if (last && last->data.buf && last->depth < max_depth) {
1067                delta = diff_delta(last->data.buf, last->data.len,
1068                        dat->buf, dat->len,
1069                        &deltalen, 0);
1070                if (delta && deltalen >= dat->len) {
1071                        free(delta);
1072                        delta = NULL;
1073                }
1074        } else
1075                delta = NULL;
1076
1077        memset(&s, 0, sizeof(s));
1078        deflateInit(&s, pack_compression_level);
1079        if (delta) {
1080                s.next_in = delta;
1081                s.avail_in = deltalen;
1082        } else {
1083                s.next_in = (void *)dat->buf;
1084                s.avail_in = dat->len;
1085        }
1086        s.avail_out = deflateBound(&s, s.avail_in);
1087        s.next_out = out = xmalloc(s.avail_out);
1088        while (deflate(&s, Z_FINISH) == Z_OK)
1089                /* nothing */;
1090        deflateEnd(&s);
1091
1092        /* Determine if we should auto-checkpoint. */
1093        if ((pack_size + 60 + s.total_out) > max_packsize
1094                || (pack_size + 60 + s.total_out) < pack_size) {
1095
1096                /* This new object needs to *not* have the current pack_id. */
1097                e->pack_id = pack_id + 1;
1098                cycle_packfile();
1099
1100                /* We cannot carry a delta into the new pack. */
1101                if (delta) {
1102                        free(delta);
1103                        delta = NULL;
1104
1105                        memset(&s, 0, sizeof(s));
1106                        deflateInit(&s, pack_compression_level);
1107                        s.next_in = (void *)dat->buf;
1108                        s.avail_in = dat->len;
1109                        s.avail_out = deflateBound(&s, s.avail_in);
1110                        s.next_out = out = xrealloc(out, s.avail_out);
1111                        while (deflate(&s, Z_FINISH) == Z_OK)
1112                                /* nothing */;
1113                        deflateEnd(&s);
1114                }
1115        }
1116
1117        e->type = type;
1118        e->pack_id = pack_id;
1119        e->offset = pack_size;
1120        object_count++;
1121        object_count_by_type[type]++;
1122
1123        if (delta) {
1124                unsigned long ofs = e->offset - last->offset;
1125                unsigned pos = sizeof(hdr) - 1;
1126
1127                delta_count_by_type[type]++;
1128                e->depth = last->depth + 1;
1129
1130                hdrlen = encode_header(OBJ_OFS_DELTA, deltalen, hdr);
1131                write_or_die(pack_data->pack_fd, hdr, hdrlen);
1132                pack_size += hdrlen;
1133
1134                hdr[pos] = ofs & 127;
1135                while (ofs >>= 7)
1136                        hdr[--pos] = 128 | (--ofs & 127);
1137                write_or_die(pack_data->pack_fd, hdr + pos, sizeof(hdr) - pos);
1138                pack_size += sizeof(hdr) - pos;
1139        } else {
1140                e->depth = 0;
1141                hdrlen = encode_header(type, dat->len, hdr);
1142                write_or_die(pack_data->pack_fd, hdr, hdrlen);
1143                pack_size += hdrlen;
1144        }
1145
1146        write_or_die(pack_data->pack_fd, out, s.total_out);
1147        pack_size += s.total_out;
1148
1149        free(out);
1150        free(delta);
1151        if (last) {
1152                if (last->no_swap) {
1153                        last->data = *dat;
1154                } else {
1155                        strbuf_swap(&last->data, dat);
1156                }
1157                last->offset = e->offset;
1158                last->depth = e->depth;
1159        }
1160        return 0;
1161}
1162
1163/* All calls must be guarded by find_object() or find_mark() to
1164 * ensure the 'struct object_entry' passed was written by this
1165 * process instance.  We unpack the entry by the offset, avoiding
1166 * the need for the corresponding .idx file.  This unpacking rule
1167 * works because we only use OBJ_REF_DELTA within the packfiles
1168 * created by fast-import.
1169 *
1170 * oe must not be NULL.  Such an oe usually comes from giving
1171 * an unknown SHA-1 to find_object() or an undefined mark to
1172 * find_mark().  Callers must test for this condition and use
1173 * the standard read_sha1_file() when it happens.
1174 *
1175 * oe->pack_id must not be MAX_PACK_ID.  Such an oe is usually from
1176 * find_mark(), where the mark was reloaded from an existing marks
1177 * file and is referencing an object that this fast-import process
1178 * instance did not write out to a packfile.  Callers must test for
1179 * this condition and use read_sha1_file() instead.
1180 */
1181static void *gfi_unpack_entry(
1182        struct object_entry *oe,
1183        unsigned long *sizep)
1184{
1185        enum object_type type;
1186        struct packed_git *p = all_packs[oe->pack_id];
1187        if (p == pack_data && p->pack_size < (pack_size + 20)) {
1188                /* The object is stored in the packfile we are writing to
1189                 * and we have modified it since the last time we scanned
1190                 * back to read a previously written object.  If an old
1191                 * window covered [p->pack_size, p->pack_size + 20) its
1192                 * data is stale and is not valid.  Closing all windows
1193                 * and updating the packfile length ensures we can read
1194                 * the newly written data.
1195                 */
1196                close_pack_windows(p);
1197
1198                /* We have to offer 20 bytes additional on the end of
1199                 * the packfile as the core unpacker code assumes the
1200                 * footer is present at the file end and must promise
1201                 * at least 20 bytes within any window it maps.  But
1202                 * we don't actually create the footer here.
1203                 */
1204                p->pack_size = pack_size + 20;
1205        }
1206        return unpack_entry(p, oe->offset, &type, sizep);
1207}
1208
1209static const char *get_mode(const char *str, uint16_t *modep)
1210{
1211        unsigned char c;
1212        uint16_t mode = 0;
1213
1214        while ((c = *str++) != ' ') {
1215                if (c < '0' || c > '7')
1216                        return NULL;
1217                mode = (mode << 3) + (c - '0');
1218        }
1219        *modep = mode;
1220        return str;
1221}
1222
1223static void load_tree(struct tree_entry *root)
1224{
1225        unsigned char *sha1 = root->versions[1].sha1;
1226        struct object_entry *myoe;
1227        struct tree_content *t;
1228        unsigned long size;
1229        char *buf;
1230        const char *c;
1231
1232        root->tree = t = new_tree_content(8);
1233        if (is_null_sha1(sha1))
1234                return;
1235
1236        myoe = find_object(sha1);
1237        if (myoe && myoe->pack_id != MAX_PACK_ID) {
1238                if (myoe->type != OBJ_TREE)
1239                        die("Not a tree: %s", sha1_to_hex(sha1));
1240                t->delta_depth = myoe->depth;
1241                buf = gfi_unpack_entry(myoe, &size);
1242                if (!buf)
1243                        die("Can't load tree %s", sha1_to_hex(sha1));
1244        } else {
1245                enum object_type type;
1246                buf = read_sha1_file(sha1, &type, &size);
1247                if (!buf || type != OBJ_TREE)
1248                        die("Can't load tree %s", sha1_to_hex(sha1));
1249        }
1250
1251        c = buf;
1252        while (c != (buf + size)) {
1253                struct tree_entry *e = new_tree_entry();
1254
1255                if (t->entry_count == t->entry_capacity)
1256                        root->tree = t = grow_tree_content(t, t->entry_count);
1257                t->entries[t->entry_count++] = e;
1258
1259                e->tree = NULL;
1260                c = get_mode(c, &e->versions[1].mode);
1261                if (!c)
1262                        die("Corrupt mode in %s", sha1_to_hex(sha1));
1263                e->versions[0].mode = e->versions[1].mode;
1264                e->name = to_atom(c, strlen(c));
1265                c += e->name->str_len + 1;
1266                hashcpy(e->versions[0].sha1, (unsigned char *)c);
1267                hashcpy(e->versions[1].sha1, (unsigned char *)c);
1268                c += 20;
1269        }
1270        free(buf);
1271}
1272
1273static int tecmp0 (const void *_a, const void *_b)
1274{
1275        struct tree_entry *a = *((struct tree_entry**)_a);
1276        struct tree_entry *b = *((struct tree_entry**)_b);
1277        return base_name_compare(
1278                a->name->str_dat, a->name->str_len, a->versions[0].mode,
1279                b->name->str_dat, b->name->str_len, b->versions[0].mode);
1280}
1281
1282static int tecmp1 (const void *_a, const void *_b)
1283{
1284        struct tree_entry *a = *((struct tree_entry**)_a);
1285        struct tree_entry *b = *((struct tree_entry**)_b);
1286        return base_name_compare(
1287                a->name->str_dat, a->name->str_len, a->versions[1].mode,
1288                b->name->str_dat, b->name->str_len, b->versions[1].mode);
1289}
1290
1291static void mktree(struct tree_content *t, int v, struct strbuf *b)
1292{
1293        size_t maxlen = 0;
1294        unsigned int i;
1295
1296        if (!v)
1297                qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0);
1298        else
1299                qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1);
1300
1301        for (i = 0; i < t->entry_count; i++) {
1302                if (t->entries[i]->versions[v].mode)
1303                        maxlen += t->entries[i]->name->str_len + 34;
1304        }
1305
1306        strbuf_reset(b);
1307        strbuf_grow(b, maxlen);
1308        for (i = 0; i < t->entry_count; i++) {
1309                struct tree_entry *e = t->entries[i];
1310                if (!e->versions[v].mode)
1311                        continue;
1312                strbuf_addf(b, "%o %s%c", (unsigned int)e->versions[v].mode,
1313                                        e->name->str_dat, '\0');
1314                strbuf_add(b, e->versions[v].sha1, 20);
1315        }
1316}
1317
1318static void store_tree(struct tree_entry *root)
1319{
1320        struct tree_content *t = root->tree;
1321        unsigned int i, j, del;
1322        struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1323        struct object_entry *le;
1324
1325        if (!is_null_sha1(root->versions[1].sha1))
1326                return;
1327
1328        for (i = 0; i < t->entry_count; i++) {
1329                if (t->entries[i]->tree)
1330                        store_tree(t->entries[i]);
1331        }
1332
1333        le = find_object(root->versions[0].sha1);
1334        if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1335                mktree(t, 0, &old_tree);
1336                lo.data = old_tree;
1337                lo.offset = le->offset;
1338                lo.depth = t->delta_depth;
1339        }
1340
1341        mktree(t, 1, &new_tree);
1342        store_object(OBJ_TREE, &new_tree, &lo, root->versions[1].sha1, 0);
1343
1344        t->delta_depth = lo.depth;
1345        for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1346                struct tree_entry *e = t->entries[i];
1347                if (e->versions[1].mode) {
1348                        e->versions[0].mode = e->versions[1].mode;
1349                        hashcpy(e->versions[0].sha1, e->versions[1].sha1);
1350                        t->entries[j++] = e;
1351                } else {
1352                        release_tree_entry(e);
1353                        del++;
1354                }
1355        }
1356        t->entry_count -= del;
1357}
1358
1359static int tree_content_set(
1360        struct tree_entry *root,
1361        const char *p,
1362        const unsigned char *sha1,
1363        const uint16_t mode,
1364        struct tree_content *subtree)
1365{
1366        struct tree_content *t = root->tree;
1367        const char *slash1;
1368        unsigned int i, n;
1369        struct tree_entry *e;
1370
1371        slash1 = strchr(p, '/');
1372        if (slash1)
1373                n = slash1 - p;
1374        else
1375                n = strlen(p);
1376        if (!n)
1377                die("Empty path component found in input");
1378        if (!slash1 && !S_ISDIR(mode) && subtree)
1379                die("Non-directories cannot have subtrees");
1380
1381        for (i = 0; i < t->entry_count; i++) {
1382                e = t->entries[i];
1383                if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1384                        if (!slash1) {
1385                                if (!S_ISDIR(mode)
1386                                                && e->versions[1].mode == mode
1387                                                && !hashcmp(e->versions[1].sha1, sha1))
1388                                        return 0;
1389                                e->versions[1].mode = mode;
1390                                hashcpy(e->versions[1].sha1, sha1);
1391                                if (e->tree)
1392                                        release_tree_content_recursive(e->tree);
1393                                e->tree = subtree;
1394                                hashclr(root->versions[1].sha1);
1395                                return 1;
1396                        }
1397                        if (!S_ISDIR(e->versions[1].mode)) {
1398                                e->tree = new_tree_content(8);
1399                                e->versions[1].mode = S_IFDIR;
1400                        }
1401                        if (!e->tree)
1402                                load_tree(e);
1403                        if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) {
1404                                hashclr(root->versions[1].sha1);
1405                                return 1;
1406                        }
1407                        return 0;
1408                }
1409        }
1410
1411        if (t->entry_count == t->entry_capacity)
1412                root->tree = t = grow_tree_content(t, t->entry_count);
1413        e = new_tree_entry();
1414        e->name = to_atom(p, n);
1415        e->versions[0].mode = 0;
1416        hashclr(e->versions[0].sha1);
1417        t->entries[t->entry_count++] = e;
1418        if (slash1) {
1419                e->tree = new_tree_content(8);
1420                e->versions[1].mode = S_IFDIR;
1421                tree_content_set(e, slash1 + 1, sha1, mode, subtree);
1422        } else {
1423                e->tree = subtree;
1424                e->versions[1].mode = mode;
1425                hashcpy(e->versions[1].sha1, sha1);
1426        }
1427        hashclr(root->versions[1].sha1);
1428        return 1;
1429}
1430
1431static int tree_content_remove(
1432        struct tree_entry *root,
1433        const char *p,
1434        struct tree_entry *backup_leaf)
1435{
1436        struct tree_content *t = root->tree;
1437        const char *slash1;
1438        unsigned int i, n;
1439        struct tree_entry *e;
1440
1441        slash1 = strchr(p, '/');
1442        if (slash1)
1443                n = slash1 - p;
1444        else
1445                n = strlen(p);
1446
1447        for (i = 0; i < t->entry_count; i++) {
1448                e = t->entries[i];
1449                if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1450                        if (!slash1 || !S_ISDIR(e->versions[1].mode))
1451                                goto del_entry;
1452                        if (!e->tree)
1453                                load_tree(e);
1454                        if (tree_content_remove(e, slash1 + 1, backup_leaf)) {
1455                                for (n = 0; n < e->tree->entry_count; n++) {
1456                                        if (e->tree->entries[n]->versions[1].mode) {
1457                                                hashclr(root->versions[1].sha1);
1458                                                return 1;
1459                                        }
1460                                }
1461                                backup_leaf = NULL;
1462                                goto del_entry;
1463                        }
1464                        return 0;
1465                }
1466        }
1467        return 0;
1468
1469del_entry:
1470        if (backup_leaf)
1471                memcpy(backup_leaf, e, sizeof(*backup_leaf));
1472        else if (e->tree)
1473                release_tree_content_recursive(e->tree);
1474        e->tree = NULL;
1475        e->versions[1].mode = 0;
1476        hashclr(e->versions[1].sha1);
1477        hashclr(root->versions[1].sha1);
1478        return 1;
1479}
1480
1481static int tree_content_get(
1482        struct tree_entry *root,
1483        const char *p,
1484        struct tree_entry *leaf)
1485{
1486        struct tree_content *t = root->tree;
1487        const char *slash1;
1488        unsigned int i, n;
1489        struct tree_entry *e;
1490
1491        slash1 = strchr(p, '/');
1492        if (slash1)
1493                n = slash1 - p;
1494        else
1495                n = strlen(p);
1496
1497        for (i = 0; i < t->entry_count; i++) {
1498                e = t->entries[i];
1499                if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1500                        if (!slash1) {
1501                                memcpy(leaf, e, sizeof(*leaf));
1502                                if (e->tree && is_null_sha1(e->versions[1].sha1))
1503                                        leaf->tree = dup_tree_content(e->tree);
1504                                else
1505                                        leaf->tree = NULL;
1506                                return 1;
1507                        }
1508                        if (!S_ISDIR(e->versions[1].mode))
1509                                return 0;
1510                        if (!e->tree)
1511                                load_tree(e);
1512                        return tree_content_get(e, slash1 + 1, leaf);
1513                }
1514        }
1515        return 0;
1516}
1517
1518static int update_branch(struct branch *b)
1519{
1520        static const char *msg = "fast-import";
1521        struct ref_lock *lock;
1522        unsigned char old_sha1[20];
1523
1524        if (is_null_sha1(b->sha1))
1525                return 0;
1526        if (read_ref(b->name, old_sha1))
1527                hashclr(old_sha1);
1528        lock = lock_any_ref_for_update(b->name, old_sha1, 0);
1529        if (!lock)
1530                return error("Unable to lock %s", b->name);
1531        if (!force_update && !is_null_sha1(old_sha1)) {
1532                struct commit *old_cmit, *new_cmit;
1533
1534                old_cmit = lookup_commit_reference_gently(old_sha1, 0);
1535                new_cmit = lookup_commit_reference_gently(b->sha1, 0);
1536                if (!old_cmit || !new_cmit) {
1537                        unlock_ref(lock);
1538                        return error("Branch %s is missing commits.", b->name);
1539                }
1540
1541                if (!in_merge_bases(old_cmit, &new_cmit, 1)) {
1542                        unlock_ref(lock);
1543                        warning("Not updating %s"
1544                                " (new tip %s does not contain %s)",
1545                                b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1));
1546                        return -1;
1547                }
1548        }
1549        if (write_ref_sha1(lock, b->sha1, msg) < 0)
1550                return error("Unable to update %s", b->name);
1551        return 0;
1552}
1553
1554static void dump_branches(void)
1555{
1556        unsigned int i;
1557        struct branch *b;
1558
1559        for (i = 0; i < branch_table_sz; i++) {
1560                for (b = branch_table[i]; b; b = b->table_next_branch)
1561                        failure |= update_branch(b);
1562        }
1563}
1564
1565static void dump_tags(void)
1566{
1567        static const char *msg = "fast-import";
1568        struct tag *t;
1569        struct ref_lock *lock;
1570        char ref_name[PATH_MAX];
1571
1572        for (t = first_tag; t; t = t->next_tag) {
1573                sprintf(ref_name, "tags/%s", t->name);
1574                lock = lock_ref_sha1(ref_name, NULL);
1575                if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
1576                        failure |= error("Unable to update %s", ref_name);
1577        }
1578}
1579
1580static void dump_marks_helper(FILE *f,
1581        uintmax_t base,
1582        struct mark_set *m)
1583{
1584        uintmax_t k;
1585        if (m->shift) {
1586                for (k = 0; k < 1024; k++) {
1587                        if (m->data.sets[k])
1588                                dump_marks_helper(f, (base + k) << m->shift,
1589                                        m->data.sets[k]);
1590                }
1591        } else {
1592                for (k = 0; k < 1024; k++) {
1593                        if (m->data.marked[k])
1594                                fprintf(f, ":%" PRIuMAX " %s\n", base + k,
1595                                        sha1_to_hex(m->data.marked[k]->sha1));
1596                }
1597        }
1598}
1599
1600static void dump_marks(void)
1601{
1602        static struct lock_file mark_lock;
1603        int mark_fd;
1604        FILE *f;
1605
1606        if (!mark_file)
1607                return;
1608
1609        mark_fd = hold_lock_file_for_update(&mark_lock, mark_file, 0);
1610        if (mark_fd < 0) {
1611                failure |= error("Unable to write marks file %s: %s",
1612                        mark_file, strerror(errno));
1613                return;
1614        }
1615
1616        f = fdopen(mark_fd, "w");
1617        if (!f) {
1618                int saved_errno = errno;
1619                rollback_lock_file(&mark_lock);
1620                failure |= error("Unable to write marks file %s: %s",
1621                        mark_file, strerror(saved_errno));
1622                return;
1623        }
1624
1625        /*
1626         * Since the lock file was fdopen()'ed, it should not be close()'ed.
1627         * Assign -1 to the lock file descriptor so that commit_lock_file()
1628         * won't try to close() it.
1629         */
1630        mark_lock.fd = -1;
1631
1632        dump_marks_helper(f, 0, marks);
1633        if (ferror(f) || fclose(f)) {
1634                int saved_errno = errno;
1635                rollback_lock_file(&mark_lock);
1636                failure |= error("Unable to write marks file %s: %s",
1637                        mark_file, strerror(saved_errno));
1638                return;
1639        }
1640
1641        if (commit_lock_file(&mark_lock)) {
1642                int saved_errno = errno;
1643                rollback_lock_file(&mark_lock);
1644                failure |= error("Unable to commit marks file %s: %s",
1645                        mark_file, strerror(saved_errno));
1646                return;
1647        }
1648}
1649
1650static int read_next_command(void)
1651{
1652        static int stdin_eof = 0;
1653
1654        if (stdin_eof) {
1655                unread_command_buf = 0;
1656                return EOF;
1657        }
1658
1659        do {
1660                if (unread_command_buf) {
1661                        unread_command_buf = 0;
1662                } else {
1663                        struct recent_command *rc;
1664
1665                        strbuf_detach(&command_buf, NULL);
1666                        stdin_eof = strbuf_getline(&command_buf, stdin, '\n');
1667                        if (stdin_eof)
1668                                return EOF;
1669
1670                        rc = rc_free;
1671                        if (rc)
1672                                rc_free = rc->next;
1673                        else {
1674                                rc = cmd_hist.next;
1675                                cmd_hist.next = rc->next;
1676                                cmd_hist.next->prev = &cmd_hist;
1677                                free(rc->buf);
1678                        }
1679
1680                        rc->buf = command_buf.buf;
1681                        rc->prev = cmd_tail;
1682                        rc->next = cmd_hist.prev;
1683                        rc->prev->next = rc;
1684                        cmd_tail = rc;
1685                }
1686        } while (command_buf.buf[0] == '#');
1687
1688        return 0;
1689}
1690
1691static void skip_optional_lf(void)
1692{
1693        int term_char = fgetc(stdin);
1694        if (term_char != '\n' && term_char != EOF)
1695                ungetc(term_char, stdin);
1696}
1697
1698static void parse_mark(void)
1699{
1700        if (!prefixcmp(command_buf.buf, "mark :")) {
1701                next_mark = strtoumax(command_buf.buf + 6, NULL, 10);
1702                read_next_command();
1703        }
1704        else
1705                next_mark = 0;
1706}
1707
1708static void parse_data(struct strbuf *sb)
1709{
1710        strbuf_reset(sb);
1711
1712        if (prefixcmp(command_buf.buf, "data "))
1713                die("Expected 'data n' command, found: %s", command_buf.buf);
1714
1715        if (!prefixcmp(command_buf.buf + 5, "<<")) {
1716                char *term = xstrdup(command_buf.buf + 5 + 2);
1717                size_t term_len = command_buf.len - 5 - 2;
1718
1719                strbuf_detach(&command_buf, NULL);
1720                for (;;) {
1721                        if (strbuf_getline(&command_buf, stdin, '\n') == EOF)
1722                                die("EOF in data (terminator '%s' not found)", term);
1723                        if (term_len == command_buf.len
1724                                && !strcmp(term, command_buf.buf))
1725                                break;
1726                        strbuf_addbuf(sb, &command_buf);
1727                        strbuf_addch(sb, '\n');
1728                }
1729                free(term);
1730        }
1731        else {
1732                size_t n = 0, length;
1733
1734                length = strtoul(command_buf.buf + 5, NULL, 10);
1735
1736                while (n < length) {
1737                        size_t s = strbuf_fread(sb, length - n, stdin);
1738                        if (!s && feof(stdin))
1739                                die("EOF in data (%lu bytes remaining)",
1740                                        (unsigned long)(length - n));
1741                        n += s;
1742                }
1743        }
1744
1745        skip_optional_lf();
1746}
1747
1748static int validate_raw_date(const char *src, char *result, int maxlen)
1749{
1750        const char *orig_src = src;
1751        char *endp;
1752        unsigned long num;
1753
1754        errno = 0;
1755
1756        num = strtoul(src, &endp, 10);
1757        /* NEEDSWORK: perhaps check for reasonable values? */
1758        if (errno || endp == src || *endp != ' ')
1759                return -1;
1760
1761        src = endp + 1;
1762        if (*src != '-' && *src != '+')
1763                return -1;
1764
1765        num = strtoul(src + 1, &endp, 10);
1766        if (errno || endp == src + 1 || *endp || (endp - orig_src) >= maxlen ||
1767            1400 < num)
1768                return -1;
1769
1770        strcpy(result, orig_src);
1771        return 0;
1772}
1773
1774static char *parse_ident(const char *buf)
1775{
1776        const char *gt;
1777        size_t name_len;
1778        char *ident;
1779
1780        gt = strrchr(buf, '>');
1781        if (!gt)
1782                die("Missing > in ident string: %s", buf);
1783        gt++;
1784        if (*gt != ' ')
1785                die("Missing space after > in ident string: %s", buf);
1786        gt++;
1787        name_len = gt - buf;
1788        ident = xmalloc(name_len + 24);
1789        strncpy(ident, buf, name_len);
1790
1791        switch (whenspec) {
1792        case WHENSPEC_RAW:
1793                if (validate_raw_date(gt, ident + name_len, 24) < 0)
1794                        die("Invalid raw date \"%s\" in ident: %s", gt, buf);
1795                break;
1796        case WHENSPEC_RFC2822:
1797                if (parse_date(gt, ident + name_len, 24) < 0)
1798                        die("Invalid rfc2822 date \"%s\" in ident: %s", gt, buf);
1799                break;
1800        case WHENSPEC_NOW:
1801                if (strcmp("now", gt))
1802                        die("Date in ident must be 'now': %s", buf);
1803                datestamp(ident + name_len, 24);
1804                break;
1805        }
1806
1807        return ident;
1808}
1809
1810static void parse_new_blob(void)
1811{
1812        static struct strbuf buf = STRBUF_INIT;
1813
1814        read_next_command();
1815        parse_mark();
1816        parse_data(&buf);
1817        store_object(OBJ_BLOB, &buf, &last_blob, NULL, next_mark);
1818}
1819
1820static void unload_one_branch(void)
1821{
1822        while (cur_active_branches
1823                && cur_active_branches >= max_active_branches) {
1824                uintmax_t min_commit = ULONG_MAX;
1825                struct branch *e, *l = NULL, *p = NULL;
1826
1827                for (e = active_branches; e; e = e->active_next_branch) {
1828                        if (e->last_commit < min_commit) {
1829                                p = l;
1830                                min_commit = e->last_commit;
1831                        }
1832                        l = e;
1833                }
1834
1835                if (p) {
1836                        e = p->active_next_branch;
1837                        p->active_next_branch = e->active_next_branch;
1838                } else {
1839                        e = active_branches;
1840                        active_branches = e->active_next_branch;
1841                }
1842                e->active = 0;
1843                e->active_next_branch = NULL;
1844                if (e->branch_tree.tree) {
1845                        release_tree_content_recursive(e->branch_tree.tree);
1846                        e->branch_tree.tree = NULL;
1847                }
1848                cur_active_branches--;
1849        }
1850}
1851
1852static void load_branch(struct branch *b)
1853{
1854        load_tree(&b->branch_tree);
1855        if (!b->active) {
1856                b->active = 1;
1857                b->active_next_branch = active_branches;
1858                active_branches = b;
1859                cur_active_branches++;
1860                branch_load_count++;
1861        }
1862}
1863
1864static void file_change_m(struct branch *b)
1865{
1866        const char *p = command_buf.buf + 2;
1867        static struct strbuf uq = STRBUF_INIT;
1868        const char *endp;
1869        struct object_entry *oe = oe;
1870        unsigned char sha1[20];
1871        uint16_t mode, inline_data = 0;
1872
1873        p = get_mode(p, &mode);
1874        if (!p)
1875                die("Corrupt mode: %s", command_buf.buf);
1876        switch (mode) {
1877        case 0644:
1878        case 0755:
1879                mode |= S_IFREG;
1880        case S_IFREG | 0644:
1881        case S_IFREG | 0755:
1882        case S_IFLNK:
1883        case S_IFGITLINK:
1884                /* ok */
1885                break;
1886        default:
1887                die("Corrupt mode: %s", command_buf.buf);
1888        }
1889
1890        if (*p == ':') {
1891                char *x;
1892                oe = find_mark(strtoumax(p + 1, &x, 10));
1893                hashcpy(sha1, oe->sha1);
1894                p = x;
1895        } else if (!prefixcmp(p, "inline")) {
1896                inline_data = 1;
1897                p += 6;
1898        } else {
1899                if (get_sha1_hex(p, sha1))
1900                        die("Invalid SHA1: %s", command_buf.buf);
1901                oe = find_object(sha1);
1902                p += 40;
1903        }
1904        if (*p++ != ' ')
1905                die("Missing space after SHA1: %s", command_buf.buf);
1906
1907        strbuf_reset(&uq);
1908        if (!unquote_c_style(&uq, p, &endp)) {
1909                if (*endp)
1910                        die("Garbage after path in: %s", command_buf.buf);
1911                p = uq.buf;
1912        }
1913
1914        if (S_ISGITLINK(mode)) {
1915                if (inline_data)
1916                        die("Git links cannot be specified 'inline': %s",
1917                                command_buf.buf);
1918                else if (oe) {
1919                        if (oe->type != OBJ_COMMIT)
1920                                die("Not a commit (actually a %s): %s",
1921                                        typename(oe->type), command_buf.buf);
1922                }
1923                /*
1924                 * Accept the sha1 without checking; it expected to be in
1925                 * another repository.
1926                 */
1927        } else if (inline_data) {
1928                static struct strbuf buf = STRBUF_INIT;
1929
1930                if (p != uq.buf) {
1931                        strbuf_addstr(&uq, p);
1932                        p = uq.buf;
1933                }
1934                read_next_command();
1935                parse_data(&buf);
1936                store_object(OBJ_BLOB, &buf, &last_blob, sha1, 0);
1937        } else if (oe) {
1938                if (oe->type != OBJ_BLOB)
1939                        die("Not a blob (actually a %s): %s",
1940                                typename(oe->type), command_buf.buf);
1941        } else {
1942                enum object_type type = sha1_object_info(sha1, NULL);
1943                if (type < 0)
1944                        die("Blob not found: %s", command_buf.buf);
1945                if (type != OBJ_BLOB)
1946                        die("Not a blob (actually a %s): %s",
1947                            typename(type), command_buf.buf);
1948        }
1949
1950        tree_content_set(&b->branch_tree, p, sha1, mode, NULL);
1951}
1952
1953static void file_change_d(struct branch *b)
1954{
1955        const char *p = command_buf.buf + 2;
1956        static struct strbuf uq = STRBUF_INIT;
1957        const char *endp;
1958
1959        strbuf_reset(&uq);
1960        if (!unquote_c_style(&uq, p, &endp)) {
1961                if (*endp)
1962                        die("Garbage after path in: %s", command_buf.buf);
1963                p = uq.buf;
1964        }
1965        tree_content_remove(&b->branch_tree, p, NULL);
1966}
1967
1968static void file_change_cr(struct branch *b, int rename)
1969{
1970        const char *s, *d;
1971        static struct strbuf s_uq = STRBUF_INIT;
1972        static struct strbuf d_uq = STRBUF_INIT;
1973        const char *endp;
1974        struct tree_entry leaf;
1975
1976        s = command_buf.buf + 2;
1977        strbuf_reset(&s_uq);
1978        if (!unquote_c_style(&s_uq, s, &endp)) {
1979                if (*endp != ' ')
1980                        die("Missing space after source: %s", command_buf.buf);
1981        } else {
1982                endp = strchr(s, ' ');
1983                if (!endp)
1984                        die("Missing space after source: %s", command_buf.buf);
1985                strbuf_add(&s_uq, s, endp - s);
1986        }
1987        s = s_uq.buf;
1988
1989        endp++;
1990        if (!*endp)
1991                die("Missing dest: %s", command_buf.buf);
1992
1993        d = endp;
1994        strbuf_reset(&d_uq);
1995        if (!unquote_c_style(&d_uq, d, &endp)) {
1996                if (*endp)
1997                        die("Garbage after dest in: %s", command_buf.buf);
1998                d = d_uq.buf;
1999        }
2000
2001        memset(&leaf, 0, sizeof(leaf));
2002        if (rename)
2003                tree_content_remove(&b->branch_tree, s, &leaf);
2004        else
2005                tree_content_get(&b->branch_tree, s, &leaf);
2006        if (!leaf.versions[1].mode)
2007                die("Path %s not in branch", s);
2008        tree_content_set(&b->branch_tree, d,
2009                leaf.versions[1].sha1,
2010                leaf.versions[1].mode,
2011                leaf.tree);
2012}
2013
2014static void note_change_n(struct branch *b)
2015{
2016        const char *p = command_buf.buf + 2;
2017        static struct strbuf uq = STRBUF_INIT;
2018        struct object_entry *oe = oe;
2019        struct branch *s;
2020        unsigned char sha1[20], commit_sha1[20];
2021        uint16_t inline_data = 0;
2022
2023        /* <dataref> or 'inline' */
2024        if (*p == ':') {
2025                char *x;
2026                oe = find_mark(strtoumax(p + 1, &x, 10));
2027                hashcpy(sha1, oe->sha1);
2028                p = x;
2029        } else if (!prefixcmp(p, "inline")) {
2030                inline_data = 1;
2031                p += 6;
2032        } else {
2033                if (get_sha1_hex(p, sha1))
2034                        die("Invalid SHA1: %s", command_buf.buf);
2035                oe = find_object(sha1);
2036                p += 40;
2037        }
2038        if (*p++ != ' ')
2039                die("Missing space after SHA1: %s", command_buf.buf);
2040
2041        /* <committish> */
2042        s = lookup_branch(p);
2043        if (s) {
2044                hashcpy(commit_sha1, s->sha1);
2045        } else if (*p == ':') {
2046                uintmax_t commit_mark = strtoumax(p + 1, NULL, 10);
2047                struct object_entry *commit_oe = find_mark(commit_mark);
2048                if (commit_oe->type != OBJ_COMMIT)
2049                        die("Mark :%" PRIuMAX " not a commit", commit_mark);
2050                hashcpy(commit_sha1, commit_oe->sha1);
2051        } else if (!get_sha1(p, commit_sha1)) {
2052                unsigned long size;
2053                char *buf = read_object_with_reference(commit_sha1,
2054                        commit_type, &size, commit_sha1);
2055                if (!buf || size < 46)
2056                        die("Not a valid commit: %s", p);
2057                free(buf);
2058        } else
2059                die("Invalid ref name or SHA1 expression: %s", p);
2060
2061        if (inline_data) {
2062                static struct strbuf buf = STRBUF_INIT;
2063
2064                if (p != uq.buf) {
2065                        strbuf_addstr(&uq, p);
2066                        p = uq.buf;
2067                }
2068                read_next_command();
2069                parse_data(&buf);
2070                store_object(OBJ_BLOB, &buf, &last_blob, sha1, 0);
2071        } else if (oe) {
2072                if (oe->type != OBJ_BLOB)
2073                        die("Not a blob (actually a %s): %s",
2074                                typename(oe->type), command_buf.buf);
2075        } else {
2076                enum object_type type = sha1_object_info(sha1, NULL);
2077                if (type < 0)
2078                        die("Blob not found: %s", command_buf.buf);
2079                if (type != OBJ_BLOB)
2080                        die("Not a blob (actually a %s): %s",
2081                            typename(type), command_buf.buf);
2082        }
2083
2084        tree_content_set(&b->branch_tree, sha1_to_hex(commit_sha1), sha1,
2085                S_IFREG | 0644, NULL);
2086}
2087
2088static void file_change_deleteall(struct branch *b)
2089{
2090        release_tree_content_recursive(b->branch_tree.tree);
2091        hashclr(b->branch_tree.versions[0].sha1);
2092        hashclr(b->branch_tree.versions[1].sha1);
2093        load_tree(&b->branch_tree);
2094}
2095
2096static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2097{
2098        if (!buf || size < 46)
2099                die("Not a valid commit: %s", sha1_to_hex(b->sha1));
2100        if (memcmp("tree ", buf, 5)
2101                || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
2102                die("The commit %s is corrupt", sha1_to_hex(b->sha1));
2103        hashcpy(b->branch_tree.versions[0].sha1,
2104                b->branch_tree.versions[1].sha1);
2105}
2106
2107static void parse_from_existing(struct branch *b)
2108{
2109        if (is_null_sha1(b->sha1)) {
2110                hashclr(b->branch_tree.versions[0].sha1);
2111                hashclr(b->branch_tree.versions[1].sha1);
2112        } else {
2113                unsigned long size;
2114                char *buf;
2115
2116                buf = read_object_with_reference(b->sha1,
2117                        commit_type, &size, b->sha1);
2118                parse_from_commit(b, buf, size);
2119                free(buf);
2120        }
2121}
2122
2123static int parse_from(struct branch *b)
2124{
2125        const char *from;
2126        struct branch *s;
2127
2128        if (prefixcmp(command_buf.buf, "from "))
2129                return 0;
2130
2131        if (b->branch_tree.tree) {
2132                release_tree_content_recursive(b->branch_tree.tree);
2133                b->branch_tree.tree = NULL;
2134        }
2135
2136        from = strchr(command_buf.buf, ' ') + 1;
2137        s = lookup_branch(from);
2138        if (b == s)
2139                die("Can't create a branch from itself: %s", b->name);
2140        else if (s) {
2141                unsigned char *t = s->branch_tree.versions[1].sha1;
2142                hashcpy(b->sha1, s->sha1);
2143                hashcpy(b->branch_tree.versions[0].sha1, t);
2144                hashcpy(b->branch_tree.versions[1].sha1, t);
2145        } else if (*from == ':') {
2146                uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2147                struct object_entry *oe = find_mark(idnum);
2148                if (oe->type != OBJ_COMMIT)
2149                        die("Mark :%" PRIuMAX " not a commit", idnum);
2150                hashcpy(b->sha1, oe->sha1);
2151                if (oe->pack_id != MAX_PACK_ID) {
2152                        unsigned long size;
2153                        char *buf = gfi_unpack_entry(oe, &size);
2154                        parse_from_commit(b, buf, size);
2155                        free(buf);
2156                } else
2157                        parse_from_existing(b);
2158        } else if (!get_sha1(from, b->sha1))
2159                parse_from_existing(b);
2160        else
2161                die("Invalid ref name or SHA1 expression: %s", from);
2162
2163        read_next_command();
2164        return 1;
2165}
2166
2167static struct hash_list *parse_merge(unsigned int *count)
2168{
2169        struct hash_list *list = NULL, *n, *e = e;
2170        const char *from;
2171        struct branch *s;
2172
2173        *count = 0;
2174        while (!prefixcmp(command_buf.buf, "merge ")) {
2175                from = strchr(command_buf.buf, ' ') + 1;
2176                n = xmalloc(sizeof(*n));
2177                s = lookup_branch(from);
2178                if (s)
2179                        hashcpy(n->sha1, s->sha1);
2180                else if (*from == ':') {
2181                        uintmax_t idnum = strtoumax(from + 1, NULL, 10);
2182                        struct object_entry *oe = find_mark(idnum);
2183                        if (oe->type != OBJ_COMMIT)
2184                                die("Mark :%" PRIuMAX " not a commit", idnum);
2185                        hashcpy(n->sha1, oe->sha1);
2186                } else if (!get_sha1(from, n->sha1)) {
2187                        unsigned long size;
2188                        char *buf = read_object_with_reference(n->sha1,
2189                                commit_type, &size, n->sha1);
2190                        if (!buf || size < 46)
2191                                die("Not a valid commit: %s", from);
2192                        free(buf);
2193                } else
2194                        die("Invalid ref name or SHA1 expression: %s", from);
2195
2196                n->next = NULL;
2197                if (list)
2198                        e->next = n;
2199                else
2200                        list = n;
2201                e = n;
2202                (*count)++;
2203                read_next_command();
2204        }
2205        return list;
2206}
2207
2208static void parse_new_commit(void)
2209{
2210        static struct strbuf msg = STRBUF_INIT;
2211        struct branch *b;
2212        char *sp;
2213        char *author = NULL;
2214        char *committer = NULL;
2215        struct hash_list *merge_list = NULL;
2216        unsigned int merge_count;
2217
2218        /* Obtain the branch name from the rest of our command */
2219        sp = strchr(command_buf.buf, ' ') + 1;
2220        b = lookup_branch(sp);
2221        if (!b)
2222                b = new_branch(sp);
2223
2224        read_next_command();
2225        parse_mark();
2226        if (!prefixcmp(command_buf.buf, "author ")) {
2227                author = parse_ident(command_buf.buf + 7);
2228                read_next_command();
2229        }
2230        if (!prefixcmp(command_buf.buf, "committer ")) {
2231                committer = parse_ident(command_buf.buf + 10);
2232                read_next_command();
2233        }
2234        if (!committer)
2235                die("Expected committer but didn't get one");
2236        parse_data(&msg);
2237        read_next_command();
2238        parse_from(b);
2239        merge_list = parse_merge(&merge_count);
2240
2241        /* ensure the branch is active/loaded */
2242        if (!b->branch_tree.tree || !max_active_branches) {
2243                unload_one_branch();
2244                load_branch(b);
2245        }
2246
2247        /* file_change* */
2248        while (command_buf.len > 0) {
2249                if (!prefixcmp(command_buf.buf, "M "))
2250                        file_change_m(b);
2251                else if (!prefixcmp(command_buf.buf, "D "))
2252                        file_change_d(b);
2253                else if (!prefixcmp(command_buf.buf, "R "))
2254                        file_change_cr(b, 1);
2255                else if (!prefixcmp(command_buf.buf, "C "))
2256                        file_change_cr(b, 0);
2257                else if (!prefixcmp(command_buf.buf, "N "))
2258                        note_change_n(b);
2259                else if (!strcmp("deleteall", command_buf.buf))
2260                        file_change_deleteall(b);
2261                else {
2262                        unread_command_buf = 1;
2263                        break;
2264                }
2265                if (read_next_command() == EOF)
2266                        break;
2267        }
2268
2269        /* build the tree and the commit */
2270        store_tree(&b->branch_tree);
2271        hashcpy(b->branch_tree.versions[0].sha1,
2272                b->branch_tree.versions[1].sha1);
2273
2274        strbuf_reset(&new_data);
2275        strbuf_addf(&new_data, "tree %s\n",
2276                sha1_to_hex(b->branch_tree.versions[1].sha1));
2277        if (!is_null_sha1(b->sha1))
2278                strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(b->sha1));
2279        while (merge_list) {
2280                struct hash_list *next = merge_list->next;
2281                strbuf_addf(&new_data, "parent %s\n", sha1_to_hex(merge_list->sha1));
2282                free(merge_list);
2283                merge_list = next;
2284        }
2285        strbuf_addf(&new_data,
2286                "author %s\n"
2287                "committer %s\n"
2288                "\n",
2289                author ? author : committer, committer);
2290        strbuf_addbuf(&new_data, &msg);
2291        free(author);
2292        free(committer);
2293
2294        if (!store_object(OBJ_COMMIT, &new_data, NULL, b->sha1, next_mark))
2295                b->pack_id = pack_id;
2296        b->last_commit = object_count_by_type[OBJ_COMMIT];
2297}
2298
2299static void parse_new_tag(void)
2300{
2301        static struct strbuf msg = STRBUF_INIT;
2302        char *sp;
2303        const char *from;
2304        char *tagger;
2305        struct branch *s;
2306        struct tag *t;
2307        uintmax_t from_mark = 0;
2308        unsigned char sha1[20];
2309
2310        /* Obtain the new tag name from the rest of our command */
2311        sp = strchr(command_buf.buf, ' ') + 1;
2312        t = pool_alloc(sizeof(struct tag));
2313        t->next_tag = NULL;
2314        t->name = pool_strdup(sp);
2315        if (last_tag)
2316                last_tag->next_tag = t;
2317        else
2318                first_tag = t;
2319        last_tag = t;
2320        read_next_command();
2321
2322        /* from ... */
2323        if (prefixcmp(command_buf.buf, "from "))
2324                die("Expected from command, got %s", command_buf.buf);
2325        from = strchr(command_buf.buf, ' ') + 1;
2326        s = lookup_branch(from);
2327        if (s) {
2328                hashcpy(sha1, s->sha1);
2329        } else if (*from == ':') {
2330                struct object_entry *oe;
2331                from_mark = strtoumax(from + 1, NULL, 10);
2332                oe = find_mark(from_mark);
2333                if (oe->type != OBJ_COMMIT)
2334                        die("Mark :%" PRIuMAX " not a commit", from_mark);
2335                hashcpy(sha1, oe->sha1);
2336        } else if (!get_sha1(from, sha1)) {
2337                unsigned long size;
2338                char *buf;
2339
2340                buf = read_object_with_reference(sha1,
2341                        commit_type, &size, sha1);
2342                if (!buf || size < 46)
2343                        die("Not a valid commit: %s", from);
2344                free(buf);
2345        } else
2346                die("Invalid ref name or SHA1 expression: %s", from);
2347        read_next_command();
2348
2349        /* tagger ... */
2350        if (!prefixcmp(command_buf.buf, "tagger ")) {
2351                tagger = parse_ident(command_buf.buf + 7);
2352                read_next_command();
2353        } else
2354                tagger = NULL;
2355
2356        /* tag payload/message */
2357        parse_data(&msg);
2358
2359        /* build the tag object */
2360        strbuf_reset(&new_data);
2361
2362        strbuf_addf(&new_data,
2363                    "object %s\n"
2364                    "type %s\n"
2365                    "tag %s\n",
2366                    sha1_to_hex(sha1), commit_type, t->name);
2367        if (tagger)
2368                strbuf_addf(&new_data,
2369                            "tagger %s\n", tagger);
2370        strbuf_addch(&new_data, '\n');
2371        strbuf_addbuf(&new_data, &msg);
2372        free(tagger);
2373
2374        if (store_object(OBJ_TAG, &new_data, NULL, t->sha1, 0))
2375                t->pack_id = MAX_PACK_ID;
2376        else
2377                t->pack_id = pack_id;
2378}
2379
2380static void parse_reset_branch(void)
2381{
2382        struct branch *b;
2383        char *sp;
2384
2385        /* Obtain the branch name from the rest of our command */
2386        sp = strchr(command_buf.buf, ' ') + 1;
2387        b = lookup_branch(sp);
2388        if (b) {
2389                hashclr(b->sha1);
2390                hashclr(b->branch_tree.versions[0].sha1);
2391                hashclr(b->branch_tree.versions[1].sha1);
2392                if (b->branch_tree.tree) {
2393                        release_tree_content_recursive(b->branch_tree.tree);
2394                        b->branch_tree.tree = NULL;
2395                }
2396        }
2397        else
2398                b = new_branch(sp);
2399        read_next_command();
2400        parse_from(b);
2401        if (command_buf.len > 0)
2402                unread_command_buf = 1;
2403}
2404
2405static void parse_checkpoint(void)
2406{
2407        if (object_count) {
2408                cycle_packfile();
2409                dump_branches();
2410                dump_tags();
2411                dump_marks();
2412        }
2413        skip_optional_lf();
2414}
2415
2416static void parse_progress(void)
2417{
2418        fwrite(command_buf.buf, 1, command_buf.len, stdout);
2419        fputc('\n', stdout);
2420        fflush(stdout);
2421        skip_optional_lf();
2422}
2423
2424static void option_import_marks(const char *input_file)
2425{
2426        char line[512];
2427        FILE *f = fopen(input_file, "r");
2428        if (!f)
2429                die_errno("cannot read '%s'", input_file);
2430        while (fgets(line, sizeof(line), f)) {
2431                uintmax_t mark;
2432                char *end;
2433                unsigned char sha1[20];
2434                struct object_entry *e;
2435
2436                end = strchr(line, '\n');
2437                if (line[0] != ':' || !end)
2438                        die("corrupt mark line: %s", line);
2439                *end = 0;
2440                mark = strtoumax(line + 1, &end, 10);
2441                if (!mark || end == line + 1
2442                        || *end != ' ' || get_sha1(end + 1, sha1))
2443                        die("corrupt mark line: %s", line);
2444                e = find_object(sha1);
2445                if (!e) {
2446                        enum object_type type = sha1_object_info(sha1, NULL);
2447                        if (type < 0)
2448                                die("object not found: %s", sha1_to_hex(sha1));
2449                        e = insert_object(sha1);
2450                        e->type = type;
2451                        e->pack_id = MAX_PACK_ID;
2452                        e->offset = 1; /* just not zero! */
2453                }
2454                insert_mark(mark, e);
2455        }
2456        fclose(f);
2457}
2458
2459static void option_date_format(const char *fmt)
2460{
2461        if (!strcmp(fmt, "raw"))
2462                whenspec = WHENSPEC_RAW;
2463        else if (!strcmp(fmt, "rfc2822"))
2464                whenspec = WHENSPEC_RFC2822;
2465        else if (!strcmp(fmt, "now"))
2466                whenspec = WHENSPEC_NOW;
2467        else
2468                die("unknown --date-format argument %s", fmt);
2469}
2470
2471static void option_max_pack_size(const char *packsize)
2472{
2473        max_packsize = strtoumax(packsize, NULL, 0) * 1024 * 1024;
2474}
2475
2476static void option_depth(const char *depth)
2477{
2478        max_depth = strtoul(depth, NULL, 0);
2479        if (max_depth > MAX_DEPTH)
2480                die("--depth cannot exceed %u", MAX_DEPTH);
2481}
2482
2483static void option_active_branches(const char *branches)
2484{
2485        max_active_branches = strtoul(branches, NULL, 0);
2486}
2487
2488static void option_export_marks(const char *marks)
2489{
2490        mark_file = xstrdup(marks);
2491}
2492
2493static void option_export_pack_edges(const char *edges)
2494{
2495        if (pack_edges)
2496                fclose(pack_edges);
2497        pack_edges = fopen(edges, "a");
2498        if (!pack_edges)
2499                die_errno("Cannot open '%s'", edges);
2500}
2501
2502static void parse_one_option(const char *option)
2503{
2504        if (!prefixcmp(option, "date-format=")) {
2505                option_date_format(option + 12);
2506        } else if (!prefixcmp(option, "max-pack-size=")) {
2507                option_max_pack_size(option + 14);
2508        } else if (!prefixcmp(option, "depth=")) {
2509                option_depth(option + 6);
2510        } else if (!prefixcmp(option, "active-branches=")) {
2511                option_active_branches(option + 16);
2512        } else if (!prefixcmp(option, "import-marks=")) {
2513                option_import_marks(option + 13);
2514        } else if (!prefixcmp(option, "export-marks=")) {
2515                option_export_marks(option + 13);
2516        } else if (!prefixcmp(option, "export-pack-edges=")) {
2517                option_export_pack_edges(option + 18);
2518        } else if (!prefixcmp(option, "force")) {
2519                force_update = 1;
2520        } else if (!prefixcmp(option, "quiet")) {
2521                show_stats = 0;
2522        } else if (!prefixcmp(option, "stats")) {
2523                show_stats = 1;
2524        } else {
2525                die("Unsupported option: %s", option);
2526        }
2527}
2528
2529static int git_pack_config(const char *k, const char *v, void *cb)
2530{
2531        if (!strcmp(k, "pack.depth")) {
2532                max_depth = git_config_int(k, v);
2533                if (max_depth > MAX_DEPTH)
2534                        max_depth = MAX_DEPTH;
2535                return 0;
2536        }
2537        if (!strcmp(k, "pack.compression")) {
2538                int level = git_config_int(k, v);
2539                if (level == -1)
2540                        level = Z_DEFAULT_COMPRESSION;
2541                else if (level < 0 || level > Z_BEST_COMPRESSION)
2542                        die("bad pack compression level %d", level);
2543                pack_compression_level = level;
2544                pack_compression_seen = 1;
2545                return 0;
2546        }
2547        return git_default_config(k, v, cb);
2548}
2549
2550static const char fast_import_usage[] =
2551"git fast-import [--date-format=f] [--max-pack-size=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file]";
2552
2553int main(int argc, const char **argv)
2554{
2555        unsigned int i;
2556
2557        git_extract_argv0_path(argv[0]);
2558
2559        if (argc == 2 && !strcmp(argv[1], "-h"))
2560                usage(fast_import_usage);
2561
2562        setup_git_directory();
2563        git_config(git_pack_config, NULL);
2564        if (!pack_compression_seen && core_compression_seen)
2565                pack_compression_level = core_compression_level;
2566
2567        alloc_objects(object_entry_alloc);
2568        strbuf_init(&command_buf, 0);
2569        atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
2570        branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
2571        avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
2572        marks = pool_calloc(1, sizeof(struct mark_set));
2573
2574        for (i = 1; i < argc; i++) {
2575                const char *a = argv[i];
2576
2577                if (*a != '-' || !strcmp(a, "--"))
2578                        break;
2579
2580                parse_one_option(a + 2);
2581        }
2582        if (i != argc)
2583                usage(fast_import_usage);
2584
2585        rc_free = pool_alloc(cmd_save * sizeof(*rc_free));
2586        for (i = 0; i < (cmd_save - 1); i++)
2587                rc_free[i].next = &rc_free[i + 1];
2588        rc_free[cmd_save - 1].next = NULL;
2589
2590        prepare_packed_git();
2591        start_packfile();
2592        set_die_routine(die_nicely);
2593        while (read_next_command() != EOF) {
2594                if (!strcmp("blob", command_buf.buf))
2595                        parse_new_blob();
2596                else if (!prefixcmp(command_buf.buf, "commit "))
2597                        parse_new_commit();
2598                else if (!prefixcmp(command_buf.buf, "tag "))
2599                        parse_new_tag();
2600                else if (!prefixcmp(command_buf.buf, "reset "))
2601                        parse_reset_branch();
2602                else if (!strcmp("checkpoint", command_buf.buf))
2603                        parse_checkpoint();
2604                else if (!prefixcmp(command_buf.buf, "progress "))
2605                        parse_progress();
2606                else
2607                        die("Unsupported command: %s", command_buf.buf);
2608        }
2609        end_packfile();
2610
2611        dump_branches();
2612        dump_tags();
2613        unkeep_all_packs();
2614        dump_marks();
2615
2616        if (pack_edges)
2617                fclose(pack_edges);
2618
2619        if (show_stats) {
2620                uintmax_t total_count = 0, duplicate_count = 0;
2621                for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
2622                        total_count += object_count_by_type[i];
2623                for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
2624                        duplicate_count += duplicate_count_by_type[i];
2625
2626                fprintf(stderr, "%s statistics:\n", argv[0]);
2627                fprintf(stderr, "---------------------------------------------------------------------\n");
2628                fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
2629                fprintf(stderr, "Total objects:   %10" PRIuMAX " (%10" PRIuMAX " duplicates                  )\n", total_count, duplicate_count);
2630                fprintf(stderr, "      blobs  :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB]);
2631                fprintf(stderr, "      trees  :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE]);
2632                fprintf(stderr, "      commits:   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT]);
2633                fprintf(stderr, "      tags   :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG]);
2634                fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
2635                fprintf(stderr, "      marks:     %10" PRIuMAX " (%10" PRIuMAX " unique    )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
2636                fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
2637                fprintf(stderr, "Memory total:    %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
2638                fprintf(stderr, "       pools:    %10lu KiB\n", (unsigned long)(total_allocd/1024));
2639                fprintf(stderr, "     objects:    %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
2640                fprintf(stderr, "---------------------------------------------------------------------\n");
2641                pack_report();
2642                fprintf(stderr, "---------------------------------------------------------------------\n");
2643                fprintf(stderr, "\n");
2644        }
2645
2646        return failure ? 1 : 0;
2647}