fast-import.con commit fast-import: introduce mem_pool type (96c47d1)
   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 commit-ish lf)?
  26    ('merge' sp commit-ish lf)*
  27    (file_change | ls)*
  28    lf?;
  29  commit_msg ::= data;
  30
  31  ls ::= 'ls' sp '"' quoted(path) '"' lf;
  32
  33  file_change ::= file_clr
  34    | file_del
  35    | file_rnm
  36    | file_cpy
  37    | file_obm
  38    | file_inm;
  39  file_clr ::= 'deleteall' lf;
  40  file_del ::= 'D' sp path_str lf;
  41  file_rnm ::= 'R' sp path_str sp path_str lf;
  42  file_cpy ::= 'C' sp path_str sp path_str lf;
  43  file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf;
  44  file_inm ::= 'M' sp mode sp 'inline' sp path_str lf
  45    data;
  46  note_obm ::= 'N' sp (hexsha1 | idnum) sp commit-ish lf;
  47  note_inm ::= 'N' sp 'inline' sp commit-ish lf
  48    data;
  49
  50  new_tag ::= 'tag' sp tag_str lf
  51    'from' sp commit-ish lf
  52    ('tagger' (sp name)? sp '<' email '>' sp when lf)?
  53    tag_msg;
  54  tag_msg ::= data;
  55
  56  reset_branch ::= 'reset' sp ref_str lf
  57    ('from' sp commit-ish lf)?
  58    lf?;
  59
  60  checkpoint ::= 'checkpoint' lf
  61    lf?;
  62
  63  progress ::= 'progress' sp not_lf* lf
  64    lf?;
  65
  66     # note: the first idnum in a stream should be 1 and subsequent
  67     # idnums should not have gaps between values as this will cause
  68     # the stream parser to reserve space for the gapped values.  An
  69     # idnum can be updated in the future to a new object by issuing
  70     # a new mark directive with the old idnum.
  71     #
  72  mark ::= 'mark' sp idnum lf;
  73  data ::= (delimited_data | exact_data)
  74    lf?;
  75
  76    # note: delim may be any string but must not contain lf.
  77    # data_line may contain any data but must not be exactly
  78    # delim.
  79  delimited_data ::= 'data' sp '<<' delim lf
  80    (data_line lf)*
  81    delim lf;
  82
  83     # note: declen indicates the length of binary_data in bytes.
  84     # declen does not include the lf preceding the binary data.
  85     #
  86  exact_data ::= 'data' sp declen lf
  87    binary_data;
  88
  89     # note: quoted strings are C-style quoting supporting \c for
  90     # common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn
  91     # is the signed byte value in octal.  Note that the only
  92     # characters which must actually be escaped to protect the
  93     # stream formatting is: \, " and LF.  Otherwise these values
  94     # are UTF8.
  95     #
  96  commit-ish  ::= (ref_str | hexsha1 | sha1exp_str | idnum);
  97  ref_str     ::= ref;
  98  sha1exp_str ::= sha1exp;
  99  tag_str     ::= tag;
 100  path_str    ::= path    | '"' quoted(path)    '"' ;
 101  mode        ::= '100644' | '644'
 102                | '100755' | '755'
 103                | '120000'
 104                ;
 105
 106  declen ::= # unsigned 32 bit value, ascii base10 notation;
 107  bigint ::= # unsigned integer value, ascii base10 notation;
 108  binary_data ::= # file content, not interpreted;
 109
 110  when         ::= raw_when | rfc2822_when;
 111  raw_when     ::= ts sp tz;
 112  rfc2822_when ::= # Valid RFC 2822 date and time;
 113
 114  sp ::= # ASCII space character;
 115  lf ::= # ASCII newline (LF) character;
 116
 117     # note: a colon (':') must precede the numerical value assigned to
 118     # an idnum.  This is to distinguish it from a ref or tag name as
 119     # GIT does not permit ':' in ref or tag strings.
 120     #
 121  idnum   ::= ':' bigint;
 122  path    ::= # GIT style file path, e.g. "a/b/c";
 123  ref     ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT";
 124  tag     ::= # GIT tag name, e.g. "FIREFOX_1_5";
 125  sha1exp ::= # Any valid GIT SHA1 expression;
 126  hexsha1 ::= # SHA1 in hexadecimal format;
 127
 128     # note: name and email are UTF8 strings, however name must not
 129     # contain '<' or lf and email must not contain any of the
 130     # following: '<', '>', lf.
 131     #
 132  name  ::= # valid GIT author/committer name;
 133  email ::= # valid GIT author/committer email;
 134  ts    ::= # time since the epoch in seconds, ascii base10 notation;
 135  tz    ::= # GIT style timezone;
 136
 137     # note: comments, get-mark, ls-tree, and cat-blob requests may
 138     # appear anywhere in the input, except within a data command. Any
 139     # form of the data command always escapes the related input from
 140     # comment processing.
 141     #
 142     # In case it is not clear, the '#' that starts the comment
 143     # must be the first character on that line (an lf
 144     # preceded it).
 145     #
 146
 147  get_mark ::= 'get-mark' sp idnum lf;
 148  cat_blob ::= 'cat-blob' sp (hexsha1 | idnum) lf;
 149  ls_tree  ::= 'ls' sp (hexsha1 | idnum) sp path_str lf;
 150
 151  comment ::= '#' not_lf* lf;
 152  not_lf  ::= # Any byte that is not ASCII newline (LF);
 153*/
 154
 155#include "builtin.h"
 156#include "cache.h"
 157#include "config.h"
 158#include "lockfile.h"
 159#include "object.h"
 160#include "blob.h"
 161#include "tree.h"
 162#include "commit.h"
 163#include "delta.h"
 164#include "pack.h"
 165#include "refs.h"
 166#include "csum-file.h"
 167#include "quote.h"
 168#include "dir.h"
 169#include "run-command.h"
 170#include "packfile.h"
 171
 172#define PACK_ID_BITS 16
 173#define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
 174#define DEPTH_BITS 13
 175#define MAX_DEPTH ((1<<DEPTH_BITS)-1)
 176
 177/*
 178 * We abuse the setuid bit on directories to mean "do not delta".
 179 */
 180#define NO_DELTA S_ISUID
 181
 182struct object_entry {
 183        struct pack_idx_entry idx;
 184        struct object_entry *next;
 185        uint32_t type : TYPE_BITS,
 186                pack_id : PACK_ID_BITS,
 187                depth : DEPTH_BITS;
 188};
 189
 190struct object_entry_pool {
 191        struct object_entry_pool *next_pool;
 192        struct object_entry *next_free;
 193        struct object_entry *end;
 194        struct object_entry entries[FLEX_ARRAY]; /* more */
 195};
 196
 197struct mark_set {
 198        union {
 199                struct object_entry *marked[1024];
 200                struct mark_set *sets[1024];
 201        } data;
 202        unsigned int shift;
 203};
 204
 205struct last_object {
 206        struct strbuf data;
 207        off_t offset;
 208        unsigned int depth;
 209        unsigned no_swap : 1;
 210};
 211
 212struct mp_block {
 213        struct mp_block *next_block;
 214        char *next_free;
 215        char *end;
 216        uintmax_t space[FLEX_ARRAY]; /* more */
 217};
 218
 219struct mem_pool {
 220        struct mp_block *mp_block;
 221
 222        /*
 223         * The amount of available memory to grow the pool by.
 224         * This size does not include the overhead for the mp_block.
 225         */
 226        size_t block_alloc;
 227
 228        /* The total amount of memory allocated by the pool. */
 229        size_t pool_alloc;
 230};
 231
 232struct atom_str {
 233        struct atom_str *next_atom;
 234        unsigned short str_len;
 235        char str_dat[FLEX_ARRAY]; /* more */
 236};
 237
 238struct tree_content;
 239struct tree_entry {
 240        struct tree_content *tree;
 241        struct atom_str *name;
 242        struct tree_entry_ms {
 243                uint16_t mode;
 244                struct object_id oid;
 245        } versions[2];
 246};
 247
 248struct tree_content {
 249        unsigned int entry_capacity; /* must match avail_tree_content */
 250        unsigned int entry_count;
 251        unsigned int delta_depth;
 252        struct tree_entry *entries[FLEX_ARRAY]; /* more */
 253};
 254
 255struct avail_tree_content {
 256        unsigned int entry_capacity; /* must match tree_content */
 257        struct avail_tree_content *next_avail;
 258};
 259
 260struct branch {
 261        struct branch *table_next_branch;
 262        struct branch *active_next_branch;
 263        const char *name;
 264        struct tree_entry branch_tree;
 265        uintmax_t last_commit;
 266        uintmax_t num_notes;
 267        unsigned active : 1;
 268        unsigned delete : 1;
 269        unsigned pack_id : PACK_ID_BITS;
 270        struct object_id oid;
 271};
 272
 273struct tag {
 274        struct tag *next_tag;
 275        const char *name;
 276        unsigned int pack_id;
 277        struct object_id oid;
 278};
 279
 280struct hash_list {
 281        struct hash_list *next;
 282        struct object_id oid;
 283};
 284
 285typedef enum {
 286        WHENSPEC_RAW = 1,
 287        WHENSPEC_RFC2822,
 288        WHENSPEC_NOW
 289} whenspec_type;
 290
 291struct recent_command {
 292        struct recent_command *prev;
 293        struct recent_command *next;
 294        char *buf;
 295};
 296
 297/* Configured limits on output */
 298static unsigned long max_depth = 50;
 299static off_t max_packsize;
 300static int unpack_limit = 100;
 301static int force_update;
 302
 303/* Stats and misc. counters */
 304static uintmax_t alloc_count;
 305static uintmax_t marks_set_count;
 306static uintmax_t object_count_by_type[1 << TYPE_BITS];
 307static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
 308static uintmax_t delta_count_by_type[1 << TYPE_BITS];
 309static uintmax_t delta_count_attempts_by_type[1 << TYPE_BITS];
 310static unsigned long object_count;
 311static unsigned long branch_count;
 312static unsigned long branch_load_count;
 313static int failure;
 314static FILE *pack_edges;
 315static unsigned int show_stats = 1;
 316static int global_argc;
 317static const char **global_argv;
 318
 319/* Memory pools */
 320static struct mem_pool fi_mem_pool =  {NULL, 2*1024*1024 -
 321                                       sizeof(struct mp_block), 0 };
 322
 323/* Atom management */
 324static unsigned int atom_table_sz = 4451;
 325static unsigned int atom_cnt;
 326static struct atom_str **atom_table;
 327
 328/* The .pack file being generated */
 329static struct pack_idx_option pack_idx_opts;
 330static unsigned int pack_id;
 331static struct hashfile *pack_file;
 332static struct packed_git *pack_data;
 333static struct packed_git **all_packs;
 334static off_t pack_size;
 335
 336/* Table of objects we've written. */
 337static unsigned int object_entry_alloc = 5000;
 338static struct object_entry_pool *blocks;
 339static struct object_entry *object_table[1 << 16];
 340static struct mark_set *marks;
 341static const char *export_marks_file;
 342static const char *import_marks_file;
 343static int import_marks_file_from_stream;
 344static int import_marks_file_ignore_missing;
 345static int import_marks_file_done;
 346static int relative_marks_paths;
 347
 348/* Our last blob */
 349static struct last_object last_blob = { STRBUF_INIT, 0, 0, 0 };
 350
 351/* Tree management */
 352static unsigned int tree_entry_alloc = 1000;
 353static void *avail_tree_entry;
 354static unsigned int avail_tree_table_sz = 100;
 355static struct avail_tree_content **avail_tree_table;
 356static size_t tree_entry_allocd;
 357static struct strbuf old_tree = STRBUF_INIT;
 358static struct strbuf new_tree = STRBUF_INIT;
 359
 360/* Branch data */
 361static unsigned long max_active_branches = 5;
 362static unsigned long cur_active_branches;
 363static unsigned long branch_table_sz = 1039;
 364static struct branch **branch_table;
 365static struct branch *active_branches;
 366
 367/* Tag data */
 368static struct tag *first_tag;
 369static struct tag *last_tag;
 370
 371/* Input stream parsing */
 372static whenspec_type whenspec = WHENSPEC_RAW;
 373static struct strbuf command_buf = STRBUF_INIT;
 374static int unread_command_buf;
 375static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
 376static struct recent_command *cmd_tail = &cmd_hist;
 377static struct recent_command *rc_free;
 378static unsigned int cmd_save = 100;
 379static uintmax_t next_mark;
 380static struct strbuf new_data = STRBUF_INIT;
 381static int seen_data_command;
 382static int require_explicit_termination;
 383
 384/* Signal handling */
 385static volatile sig_atomic_t checkpoint_requested;
 386
 387/* Where to write output of cat-blob commands */
 388static int cat_blob_fd = STDOUT_FILENO;
 389
 390static void parse_argv(void);
 391static void parse_get_mark(const char *p);
 392static void parse_cat_blob(const char *p);
 393static void parse_ls(const char *p, struct branch *b);
 394
 395static void write_branch_report(FILE *rpt, struct branch *b)
 396{
 397        fprintf(rpt, "%s:\n", b->name);
 398
 399        fprintf(rpt, "  status      :");
 400        if (b->active)
 401                fputs(" active", rpt);
 402        if (b->branch_tree.tree)
 403                fputs(" loaded", rpt);
 404        if (is_null_oid(&b->branch_tree.versions[1].oid))
 405                fputs(" dirty", rpt);
 406        fputc('\n', rpt);
 407
 408        fprintf(rpt, "  tip commit  : %s\n", oid_to_hex(&b->oid));
 409        fprintf(rpt, "  old tree    : %s\n",
 410                oid_to_hex(&b->branch_tree.versions[0].oid));
 411        fprintf(rpt, "  cur tree    : %s\n",
 412                oid_to_hex(&b->branch_tree.versions[1].oid));
 413        fprintf(rpt, "  commit clock: %" PRIuMAX "\n", b->last_commit);
 414
 415        fputs("  last pack   : ", rpt);
 416        if (b->pack_id < MAX_PACK_ID)
 417                fprintf(rpt, "%u", b->pack_id);
 418        fputc('\n', rpt);
 419
 420        fputc('\n', rpt);
 421}
 422
 423static void dump_marks_helper(FILE *, uintmax_t, struct mark_set *);
 424
 425static void write_crash_report(const char *err)
 426{
 427        char *loc = git_pathdup("fast_import_crash_%"PRIuMAX, (uintmax_t) getpid());
 428        FILE *rpt = fopen(loc, "w");
 429        struct branch *b;
 430        unsigned long lu;
 431        struct recent_command *rc;
 432
 433        if (!rpt) {
 434                error_errno("can't write crash report %s", loc);
 435                free(loc);
 436                return;
 437        }
 438
 439        fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
 440
 441        fprintf(rpt, "fast-import crash report:\n");
 442        fprintf(rpt, "    fast-import process: %"PRIuMAX"\n", (uintmax_t) getpid());
 443        fprintf(rpt, "    parent process     : %"PRIuMAX"\n", (uintmax_t) getppid());
 444        fprintf(rpt, "    at %s\n", show_date(time(NULL), 0, DATE_MODE(ISO8601)));
 445        fputc('\n', rpt);
 446
 447        fputs("fatal: ", rpt);
 448        fputs(err, rpt);
 449        fputc('\n', rpt);
 450
 451        fputc('\n', rpt);
 452        fputs("Most Recent Commands Before Crash\n", rpt);
 453        fputs("---------------------------------\n", rpt);
 454        for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
 455                if (rc->next == &cmd_hist)
 456                        fputs("* ", rpt);
 457                else
 458                        fputs("  ", rpt);
 459                fputs(rc->buf, rpt);
 460                fputc('\n', rpt);
 461        }
 462
 463        fputc('\n', rpt);
 464        fputs("Active Branch LRU\n", rpt);
 465        fputs("-----------------\n", rpt);
 466        fprintf(rpt, "    active_branches = %lu cur, %lu max\n",
 467                cur_active_branches,
 468                max_active_branches);
 469        fputc('\n', rpt);
 470        fputs("  pos  clock name\n", rpt);
 471        fputs("  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
 472        for (b = active_branches, lu = 0; b; b = b->active_next_branch)
 473                fprintf(rpt, "  %2lu) %6" PRIuMAX" %s\n",
 474                        ++lu, b->last_commit, b->name);
 475
 476        fputc('\n', rpt);
 477        fputs("Inactive Branches\n", rpt);
 478        fputs("-----------------\n", rpt);
 479        for (lu = 0; lu < branch_table_sz; lu++) {
 480                for (b = branch_table[lu]; b; b = b->table_next_branch)
 481                        write_branch_report(rpt, b);
 482        }
 483
 484        if (first_tag) {
 485                struct tag *tg;
 486                fputc('\n', rpt);
 487                fputs("Annotated Tags\n", rpt);
 488                fputs("--------------\n", rpt);
 489                for (tg = first_tag; tg; tg = tg->next_tag) {
 490                        fputs(oid_to_hex(&tg->oid), rpt);
 491                        fputc(' ', rpt);
 492                        fputs(tg->name, rpt);
 493                        fputc('\n', rpt);
 494                }
 495        }
 496
 497        fputc('\n', rpt);
 498        fputs("Marks\n", rpt);
 499        fputs("-----\n", rpt);
 500        if (export_marks_file)
 501                fprintf(rpt, "  exported to %s\n", export_marks_file);
 502        else
 503                dump_marks_helper(rpt, 0, marks);
 504
 505        fputc('\n', rpt);
 506        fputs("-------------------\n", rpt);
 507        fputs("END OF CRASH REPORT\n", rpt);
 508        fclose(rpt);
 509        free(loc);
 510}
 511
 512static void end_packfile(void);
 513static void unkeep_all_packs(void);
 514static void dump_marks(void);
 515
 516static NORETURN void die_nicely(const char *err, va_list params)
 517{
 518        static int zombie;
 519        char message[2 * PATH_MAX];
 520
 521        vsnprintf(message, sizeof(message), err, params);
 522        fputs("fatal: ", stderr);
 523        fputs(message, stderr);
 524        fputc('\n', stderr);
 525
 526        if (!zombie) {
 527                zombie = 1;
 528                write_crash_report(message);
 529                end_packfile();
 530                unkeep_all_packs();
 531                dump_marks();
 532        }
 533        exit(128);
 534}
 535
 536#ifndef SIGUSR1 /* Windows, for example */
 537
 538static void set_checkpoint_signal(void)
 539{
 540}
 541
 542#else
 543
 544static void checkpoint_signal(int signo)
 545{
 546        checkpoint_requested = 1;
 547}
 548
 549static void set_checkpoint_signal(void)
 550{
 551        struct sigaction sa;
 552
 553        memset(&sa, 0, sizeof(sa));
 554        sa.sa_handler = checkpoint_signal;
 555        sigemptyset(&sa.sa_mask);
 556        sa.sa_flags = SA_RESTART;
 557        sigaction(SIGUSR1, &sa, NULL);
 558}
 559
 560#endif
 561
 562static void alloc_objects(unsigned int cnt)
 563{
 564        struct object_entry_pool *b;
 565
 566        b = xmalloc(sizeof(struct object_entry_pool)
 567                + cnt * sizeof(struct object_entry));
 568        b->next_pool = blocks;
 569        b->next_free = b->entries;
 570        b->end = b->entries + cnt;
 571        blocks = b;
 572        alloc_count += cnt;
 573}
 574
 575static struct object_entry *new_object(struct object_id *oid)
 576{
 577        struct object_entry *e;
 578
 579        if (blocks->next_free == blocks->end)
 580                alloc_objects(object_entry_alloc);
 581
 582        e = blocks->next_free++;
 583        oidcpy(&e->idx.oid, oid);
 584        return e;
 585}
 586
 587static struct object_entry *find_object(struct object_id *oid)
 588{
 589        unsigned int h = oid->hash[0] << 8 | oid->hash[1];
 590        struct object_entry *e;
 591        for (e = object_table[h]; e; e = e->next)
 592                if (!oidcmp(oid, &e->idx.oid))
 593                        return e;
 594        return NULL;
 595}
 596
 597static struct object_entry *insert_object(struct object_id *oid)
 598{
 599        unsigned int h = oid->hash[0] << 8 | oid->hash[1];
 600        struct object_entry *e = object_table[h];
 601
 602        while (e) {
 603                if (!oidcmp(oid, &e->idx.oid))
 604                        return e;
 605                e = e->next;
 606        }
 607
 608        e = new_object(oid);
 609        e->next = object_table[h];
 610        e->idx.offset = 0;
 611        object_table[h] = e;
 612        return e;
 613}
 614
 615static void invalidate_pack_id(unsigned int id)
 616{
 617        unsigned int h;
 618        unsigned long lu;
 619        struct tag *t;
 620
 621        for (h = 0; h < ARRAY_SIZE(object_table); h++) {
 622                struct object_entry *e;
 623
 624                for (e = object_table[h]; e; e = e->next)
 625                        if (e->pack_id == id)
 626                                e->pack_id = MAX_PACK_ID;
 627        }
 628
 629        for (lu = 0; lu < branch_table_sz; lu++) {
 630                struct branch *b;
 631
 632                for (b = branch_table[lu]; b; b = b->table_next_branch)
 633                        if (b->pack_id == id)
 634                                b->pack_id = MAX_PACK_ID;
 635        }
 636
 637        for (t = first_tag; t; t = t->next_tag)
 638                if (t->pack_id == id)
 639                        t->pack_id = MAX_PACK_ID;
 640}
 641
 642static unsigned int hc_str(const char *s, size_t len)
 643{
 644        unsigned int r = 0;
 645        while (len-- > 0)
 646                r = r * 31 + *s++;
 647        return r;
 648}
 649
 650static struct mp_block *mem_pool_alloc_block(struct mem_pool *mem_pool, size_t block_alloc)
 651{
 652        struct mp_block *p;
 653
 654        mem_pool->pool_alloc += sizeof(struct mp_block) + block_alloc;
 655        p = xmalloc(st_add(sizeof(struct mp_block), block_alloc));
 656        p->next_block = mem_pool->mp_block;
 657        p->next_free = (char *)p->space;
 658        p->end = p->next_free + block_alloc;
 659        mem_pool->mp_block = p;
 660
 661        return p;
 662}
 663
 664static void *mem_pool_alloc(struct mem_pool *mem_pool, size_t len)
 665{
 666        struct mp_block *p;
 667        void *r;
 668
 669        /* round up to a 'uintmax_t' alignment */
 670        if (len & (sizeof(uintmax_t) - 1))
 671                len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
 672
 673        for (p = mem_pool->mp_block; p; p = p->next_block)
 674                if (p->end - p->next_free >= len)
 675                        break;
 676
 677        if (!p) {
 678                if (len >= (mem_pool->block_alloc / 2)) {
 679                        mem_pool->pool_alloc += len;
 680                        return xmalloc(len);
 681                }
 682
 683                p = mem_pool_alloc_block(mem_pool, mem_pool->block_alloc);
 684        }
 685
 686        r = p->next_free;
 687        p->next_free += len;
 688        return r;
 689}
 690
 691static void *mem_pool_calloc(struct mem_pool *mem_pool, size_t count, size_t size)
 692{
 693        size_t len = st_mult(count, size);
 694        void *r = mem_pool_alloc(mem_pool, len);
 695        memset(r, 0, len);
 696        return r;
 697}
 698
 699static char *pool_strdup(const char *s)
 700{
 701        size_t len = strlen(s) + 1;
 702        char *r = mem_pool_alloc(&fi_mem_pool, len);
 703        memcpy(r, s, len);
 704        return r;
 705}
 706
 707static void insert_mark(uintmax_t idnum, struct object_entry *oe)
 708{
 709        struct mark_set *s = marks;
 710        while ((idnum >> s->shift) >= 1024) {
 711                s = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
 712                s->shift = marks->shift + 10;
 713                s->data.sets[0] = marks;
 714                marks = s;
 715        }
 716        while (s->shift) {
 717                uintmax_t i = idnum >> s->shift;
 718                idnum -= i << s->shift;
 719                if (!s->data.sets[i]) {
 720                        s->data.sets[i] = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
 721                        s->data.sets[i]->shift = s->shift - 10;
 722                }
 723                s = s->data.sets[i];
 724        }
 725        if (!s->data.marked[idnum])
 726                marks_set_count++;
 727        s->data.marked[idnum] = oe;
 728}
 729
 730static struct object_entry *find_mark(uintmax_t idnum)
 731{
 732        uintmax_t orig_idnum = idnum;
 733        struct mark_set *s = marks;
 734        struct object_entry *oe = NULL;
 735        if ((idnum >> s->shift) < 1024) {
 736                while (s && s->shift) {
 737                        uintmax_t i = idnum >> s->shift;
 738                        idnum -= i << s->shift;
 739                        s = s->data.sets[i];
 740                }
 741                if (s)
 742                        oe = s->data.marked[idnum];
 743        }
 744        if (!oe)
 745                die("mark :%" PRIuMAX " not declared", orig_idnum);
 746        return oe;
 747}
 748
 749static struct atom_str *to_atom(const char *s, unsigned short len)
 750{
 751        unsigned int hc = hc_str(s, len) % atom_table_sz;
 752        struct atom_str *c;
 753
 754        for (c = atom_table[hc]; c; c = c->next_atom)
 755                if (c->str_len == len && !strncmp(s, c->str_dat, len))
 756                        return c;
 757
 758        c = mem_pool_alloc(&fi_mem_pool, sizeof(struct atom_str) + len + 1);
 759        c->str_len = len;
 760        memcpy(c->str_dat, s, len);
 761        c->str_dat[len] = 0;
 762        c->next_atom = atom_table[hc];
 763        atom_table[hc] = c;
 764        atom_cnt++;
 765        return c;
 766}
 767
 768static struct branch *lookup_branch(const char *name)
 769{
 770        unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
 771        struct branch *b;
 772
 773        for (b = branch_table[hc]; b; b = b->table_next_branch)
 774                if (!strcmp(name, b->name))
 775                        return b;
 776        return NULL;
 777}
 778
 779static struct branch *new_branch(const char *name)
 780{
 781        unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
 782        struct branch *b = lookup_branch(name);
 783
 784        if (b)
 785                die("Invalid attempt to create duplicate branch: %s", name);
 786        if (check_refname_format(name, REFNAME_ALLOW_ONELEVEL))
 787                die("Branch name doesn't conform to GIT standards: %s", name);
 788
 789        b = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct branch));
 790        b->name = pool_strdup(name);
 791        b->table_next_branch = branch_table[hc];
 792        b->branch_tree.versions[0].mode = S_IFDIR;
 793        b->branch_tree.versions[1].mode = S_IFDIR;
 794        b->num_notes = 0;
 795        b->active = 0;
 796        b->pack_id = MAX_PACK_ID;
 797        branch_table[hc] = b;
 798        branch_count++;
 799        return b;
 800}
 801
 802static unsigned int hc_entries(unsigned int cnt)
 803{
 804        cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
 805        return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
 806}
 807
 808static struct tree_content *new_tree_content(unsigned int cnt)
 809{
 810        struct avail_tree_content *f, *l = NULL;
 811        struct tree_content *t;
 812        unsigned int hc = hc_entries(cnt);
 813
 814        for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
 815                if (f->entry_capacity >= cnt)
 816                        break;
 817
 818        if (f) {
 819                if (l)
 820                        l->next_avail = f->next_avail;
 821                else
 822                        avail_tree_table[hc] = f->next_avail;
 823        } else {
 824                cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
 825                f = mem_pool_alloc(&fi_mem_pool, sizeof(*t) + sizeof(t->entries[0]) * cnt);
 826                f->entry_capacity = cnt;
 827        }
 828
 829        t = (struct tree_content*)f;
 830        t->entry_count = 0;
 831        t->delta_depth = 0;
 832        return t;
 833}
 834
 835static void release_tree_entry(struct tree_entry *e);
 836static void release_tree_content(struct tree_content *t)
 837{
 838        struct avail_tree_content *f = (struct avail_tree_content*)t;
 839        unsigned int hc = hc_entries(f->entry_capacity);
 840        f->next_avail = avail_tree_table[hc];
 841        avail_tree_table[hc] = f;
 842}
 843
 844static void release_tree_content_recursive(struct tree_content *t)
 845{
 846        unsigned int i;
 847        for (i = 0; i < t->entry_count; i++)
 848                release_tree_entry(t->entries[i]);
 849        release_tree_content(t);
 850}
 851
 852static struct tree_content *grow_tree_content(
 853        struct tree_content *t,
 854        int amt)
 855{
 856        struct tree_content *r = new_tree_content(t->entry_count + amt);
 857        r->entry_count = t->entry_count;
 858        r->delta_depth = t->delta_depth;
 859        memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
 860        release_tree_content(t);
 861        return r;
 862}
 863
 864static struct tree_entry *new_tree_entry(void)
 865{
 866        struct tree_entry *e;
 867
 868        if (!avail_tree_entry) {
 869                unsigned int n = tree_entry_alloc;
 870                tree_entry_allocd += n * sizeof(struct tree_entry);
 871                ALLOC_ARRAY(e, n);
 872                avail_tree_entry = e;
 873                while (n-- > 1) {
 874                        *((void**)e) = e + 1;
 875                        e++;
 876                }
 877                *((void**)e) = NULL;
 878        }
 879
 880        e = avail_tree_entry;
 881        avail_tree_entry = *((void**)e);
 882        return e;
 883}
 884
 885static void release_tree_entry(struct tree_entry *e)
 886{
 887        if (e->tree)
 888                release_tree_content_recursive(e->tree);
 889        *((void**)e) = avail_tree_entry;
 890        avail_tree_entry = e;
 891}
 892
 893static struct tree_content *dup_tree_content(struct tree_content *s)
 894{
 895        struct tree_content *d;
 896        struct tree_entry *a, *b;
 897        unsigned int i;
 898
 899        if (!s)
 900                return NULL;
 901        d = new_tree_content(s->entry_count);
 902        for (i = 0; i < s->entry_count; i++) {
 903                a = s->entries[i];
 904                b = new_tree_entry();
 905                memcpy(b, a, sizeof(*a));
 906                if (a->tree && is_null_oid(&b->versions[1].oid))
 907                        b->tree = dup_tree_content(a->tree);
 908                else
 909                        b->tree = NULL;
 910                d->entries[i] = b;
 911        }
 912        d->entry_count = s->entry_count;
 913        d->delta_depth = s->delta_depth;
 914
 915        return d;
 916}
 917
 918static void start_packfile(void)
 919{
 920        struct strbuf tmp_file = STRBUF_INIT;
 921        struct packed_git *p;
 922        struct pack_header hdr;
 923        int pack_fd;
 924
 925        pack_fd = odb_mkstemp(&tmp_file, "pack/tmp_pack_XXXXXX");
 926        FLEX_ALLOC_STR(p, pack_name, tmp_file.buf);
 927        strbuf_release(&tmp_file);
 928
 929        p->pack_fd = pack_fd;
 930        p->do_not_close = 1;
 931        pack_file = hashfd(pack_fd, p->pack_name);
 932
 933        hdr.hdr_signature = htonl(PACK_SIGNATURE);
 934        hdr.hdr_version = htonl(2);
 935        hdr.hdr_entries = 0;
 936        hashwrite(pack_file, &hdr, sizeof(hdr));
 937
 938        pack_data = p;
 939        pack_size = sizeof(hdr);
 940        object_count = 0;
 941
 942        REALLOC_ARRAY(all_packs, pack_id + 1);
 943        all_packs[pack_id] = p;
 944}
 945
 946static const char *create_index(void)
 947{
 948        const char *tmpfile;
 949        struct pack_idx_entry **idx, **c, **last;
 950        struct object_entry *e;
 951        struct object_entry_pool *o;
 952
 953        /* Build the table of object IDs. */
 954        ALLOC_ARRAY(idx, object_count);
 955        c = idx;
 956        for (o = blocks; o; o = o->next_pool)
 957                for (e = o->next_free; e-- != o->entries;)
 958                        if (pack_id == e->pack_id)
 959                                *c++ = &e->idx;
 960        last = idx + object_count;
 961        if (c != last)
 962                die("internal consistency error creating the index");
 963
 964        tmpfile = write_idx_file(NULL, idx, object_count, &pack_idx_opts, pack_data->sha1);
 965        free(idx);
 966        return tmpfile;
 967}
 968
 969static char *keep_pack(const char *curr_index_name)
 970{
 971        static const char *keep_msg = "fast-import";
 972        struct strbuf name = STRBUF_INIT;
 973        int keep_fd;
 974
 975        odb_pack_name(&name, pack_data->sha1, "keep");
 976        keep_fd = odb_pack_keep(name.buf);
 977        if (keep_fd < 0)
 978                die_errno("cannot create keep file");
 979        write_or_die(keep_fd, keep_msg, strlen(keep_msg));
 980        if (close(keep_fd))
 981                die_errno("failed to write keep file");
 982
 983        odb_pack_name(&name, pack_data->sha1, "pack");
 984        if (finalize_object_file(pack_data->pack_name, name.buf))
 985                die("cannot store pack file");
 986
 987        odb_pack_name(&name, pack_data->sha1, "idx");
 988        if (finalize_object_file(curr_index_name, name.buf))
 989                die("cannot store index file");
 990        free((void *)curr_index_name);
 991        return strbuf_detach(&name, NULL);
 992}
 993
 994static void unkeep_all_packs(void)
 995{
 996        struct strbuf name = STRBUF_INIT;
 997        int k;
 998
 999        for (k = 0; k < pack_id; k++) {
1000                struct packed_git *p = all_packs[k];
1001                odb_pack_name(&name, p->sha1, "keep");
1002                unlink_or_warn(name.buf);
1003        }
1004        strbuf_release(&name);
1005}
1006
1007static int loosen_small_pack(const struct packed_git *p)
1008{
1009        struct child_process unpack = CHILD_PROCESS_INIT;
1010
1011        if (lseek(p->pack_fd, 0, SEEK_SET) < 0)
1012                die_errno("Failed seeking to start of '%s'", p->pack_name);
1013
1014        unpack.in = p->pack_fd;
1015        unpack.git_cmd = 1;
1016        unpack.stdout_to_stderr = 1;
1017        argv_array_push(&unpack.args, "unpack-objects");
1018        if (!show_stats)
1019                argv_array_push(&unpack.args, "-q");
1020
1021        return run_command(&unpack);
1022}
1023
1024static void end_packfile(void)
1025{
1026        static int running;
1027
1028        if (running || !pack_data)
1029                return;
1030
1031        running = 1;
1032        clear_delta_base_cache();
1033        if (object_count) {
1034                struct packed_git *new_p;
1035                struct object_id cur_pack_oid;
1036                char *idx_name;
1037                int i;
1038                struct branch *b;
1039                struct tag *t;
1040
1041                close_pack_windows(pack_data);
1042                hashclose(pack_file, cur_pack_oid.hash, 0);
1043                fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
1044                                    pack_data->pack_name, object_count,
1045                                    cur_pack_oid.hash, pack_size);
1046
1047                if (object_count <= unpack_limit) {
1048                        if (!loosen_small_pack(pack_data)) {
1049                                invalidate_pack_id(pack_id);
1050                                goto discard_pack;
1051                        }
1052                }
1053
1054                close(pack_data->pack_fd);
1055                idx_name = keep_pack(create_index());
1056
1057                /* Register the packfile with core git's machinery. */
1058                new_p = add_packed_git(idx_name, strlen(idx_name), 1);
1059                if (!new_p)
1060                        die("core git rejected index %s", idx_name);
1061                all_packs[pack_id] = new_p;
1062                install_packed_git(new_p);
1063                free(idx_name);
1064
1065                /* Print the boundary */
1066                if (pack_edges) {
1067                        fprintf(pack_edges, "%s:", new_p->pack_name);
1068                        for (i = 0; i < branch_table_sz; i++) {
1069                                for (b = branch_table[i]; b; b = b->table_next_branch) {
1070                                        if (b->pack_id == pack_id)
1071                                                fprintf(pack_edges, " %s",
1072                                                        oid_to_hex(&b->oid));
1073                                }
1074                        }
1075                        for (t = first_tag; t; t = t->next_tag) {
1076                                if (t->pack_id == pack_id)
1077                                        fprintf(pack_edges, " %s",
1078                                                oid_to_hex(&t->oid));
1079                        }
1080                        fputc('\n', pack_edges);
1081                        fflush(pack_edges);
1082                }
1083
1084                pack_id++;
1085        }
1086        else {
1087discard_pack:
1088                close(pack_data->pack_fd);
1089                unlink_or_warn(pack_data->pack_name);
1090        }
1091        FREE_AND_NULL(pack_data);
1092        running = 0;
1093
1094        /* We can't carry a delta across packfiles. */
1095        strbuf_release(&last_blob.data);
1096        last_blob.offset = 0;
1097        last_blob.depth = 0;
1098}
1099
1100static void cycle_packfile(void)
1101{
1102        end_packfile();
1103        start_packfile();
1104}
1105
1106static int store_object(
1107        enum object_type type,
1108        struct strbuf *dat,
1109        struct last_object *last,
1110        struct object_id *oidout,
1111        uintmax_t mark)
1112{
1113        void *out, *delta;
1114        struct object_entry *e;
1115        unsigned char hdr[96];
1116        struct object_id oid;
1117        unsigned long hdrlen, deltalen;
1118        git_hash_ctx c;
1119        git_zstream s;
1120
1121        hdrlen = xsnprintf((char *)hdr, sizeof(hdr), "%s %lu",
1122                           type_name(type), (unsigned long)dat->len) + 1;
1123        the_hash_algo->init_fn(&c);
1124        the_hash_algo->update_fn(&c, hdr, hdrlen);
1125        the_hash_algo->update_fn(&c, dat->buf, dat->len);
1126        the_hash_algo->final_fn(oid.hash, &c);
1127        if (oidout)
1128                oidcpy(oidout, &oid);
1129
1130        e = insert_object(&oid);
1131        if (mark)
1132                insert_mark(mark, e);
1133        if (e->idx.offset) {
1134                duplicate_count_by_type[type]++;
1135                return 1;
1136        } else if (find_sha1_pack(oid.hash, packed_git)) {
1137                e->type = type;
1138                e->pack_id = MAX_PACK_ID;
1139                e->idx.offset = 1; /* just not zero! */
1140                duplicate_count_by_type[type]++;
1141                return 1;
1142        }
1143
1144        if (last && last->data.buf && last->depth < max_depth
1145                && dat->len > the_hash_algo->rawsz) {
1146
1147                delta_count_attempts_by_type[type]++;
1148                delta = diff_delta(last->data.buf, last->data.len,
1149                        dat->buf, dat->len,
1150                        &deltalen, dat->len - the_hash_algo->rawsz);
1151        } else
1152                delta = NULL;
1153
1154        git_deflate_init(&s, pack_compression_level);
1155        if (delta) {
1156                s.next_in = delta;
1157                s.avail_in = deltalen;
1158        } else {
1159                s.next_in = (void *)dat->buf;
1160                s.avail_in = dat->len;
1161        }
1162        s.avail_out = git_deflate_bound(&s, s.avail_in);
1163        s.next_out = out = xmalloc(s.avail_out);
1164        while (git_deflate(&s, Z_FINISH) == Z_OK)
1165                ; /* nothing */
1166        git_deflate_end(&s);
1167
1168        /* Determine if we should auto-checkpoint. */
1169        if ((max_packsize && (pack_size + 60 + s.total_out) > max_packsize)
1170                || (pack_size + 60 + s.total_out) < pack_size) {
1171
1172                /* This new object needs to *not* have the current pack_id. */
1173                e->pack_id = pack_id + 1;
1174                cycle_packfile();
1175
1176                /* We cannot carry a delta into the new pack. */
1177                if (delta) {
1178                        FREE_AND_NULL(delta);
1179
1180                        git_deflate_init(&s, pack_compression_level);
1181                        s.next_in = (void *)dat->buf;
1182                        s.avail_in = dat->len;
1183                        s.avail_out = git_deflate_bound(&s, s.avail_in);
1184                        s.next_out = out = xrealloc(out, s.avail_out);
1185                        while (git_deflate(&s, Z_FINISH) == Z_OK)
1186                                ; /* nothing */
1187                        git_deflate_end(&s);
1188                }
1189        }
1190
1191        e->type = type;
1192        e->pack_id = pack_id;
1193        e->idx.offset = pack_size;
1194        object_count++;
1195        object_count_by_type[type]++;
1196
1197        crc32_begin(pack_file);
1198
1199        if (delta) {
1200                off_t ofs = e->idx.offset - last->offset;
1201                unsigned pos = sizeof(hdr) - 1;
1202
1203                delta_count_by_type[type]++;
1204                e->depth = last->depth + 1;
1205
1206                hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1207                                                      OBJ_OFS_DELTA, deltalen);
1208                hashwrite(pack_file, hdr, hdrlen);
1209                pack_size += hdrlen;
1210
1211                hdr[pos] = ofs & 127;
1212                while (ofs >>= 7)
1213                        hdr[--pos] = 128 | (--ofs & 127);
1214                hashwrite(pack_file, hdr + pos, sizeof(hdr) - pos);
1215                pack_size += sizeof(hdr) - pos;
1216        } else {
1217                e->depth = 0;
1218                hdrlen = encode_in_pack_object_header(hdr, sizeof(hdr),
1219                                                      type, dat->len);
1220                hashwrite(pack_file, hdr, hdrlen);
1221                pack_size += hdrlen;
1222        }
1223
1224        hashwrite(pack_file, out, s.total_out);
1225        pack_size += s.total_out;
1226
1227        e->idx.crc32 = crc32_end(pack_file);
1228
1229        free(out);
1230        free(delta);
1231        if (last) {
1232                if (last->no_swap) {
1233                        last->data = *dat;
1234                } else {
1235                        strbuf_swap(&last->data, dat);
1236                }
1237                last->offset = e->idx.offset;
1238                last->depth = e->depth;
1239        }
1240        return 0;
1241}
1242
1243static void truncate_pack(struct hashfile_checkpoint *checkpoint)
1244{
1245        if (hashfile_truncate(pack_file, checkpoint))
1246                die_errno("cannot truncate pack to skip duplicate");
1247        pack_size = checkpoint->offset;
1248}
1249
1250static void stream_blob(uintmax_t len, struct object_id *oidout, uintmax_t mark)
1251{
1252        size_t in_sz = 64 * 1024, out_sz = 64 * 1024;
1253        unsigned char *in_buf = xmalloc(in_sz);
1254        unsigned char *out_buf = xmalloc(out_sz);
1255        struct object_entry *e;
1256        struct object_id oid;
1257        unsigned long hdrlen;
1258        off_t offset;
1259        git_hash_ctx c;
1260        git_zstream s;
1261        struct hashfile_checkpoint checkpoint;
1262        int status = Z_OK;
1263
1264        /* Determine if we should auto-checkpoint. */
1265        if ((max_packsize && (pack_size + 60 + len) > max_packsize)
1266                || (pack_size + 60 + len) < pack_size)
1267                cycle_packfile();
1268
1269        hashfile_checkpoint(pack_file, &checkpoint);
1270        offset = checkpoint.offset;
1271
1272        hdrlen = xsnprintf((char *)out_buf, out_sz, "blob %" PRIuMAX, len) + 1;
1273
1274        the_hash_algo->init_fn(&c);
1275        the_hash_algo->update_fn(&c, out_buf, hdrlen);
1276
1277        crc32_begin(pack_file);
1278
1279        git_deflate_init(&s, pack_compression_level);
1280
1281        hdrlen = encode_in_pack_object_header(out_buf, out_sz, OBJ_BLOB, len);
1282
1283        s.next_out = out_buf + hdrlen;
1284        s.avail_out = out_sz - hdrlen;
1285
1286        while (status != Z_STREAM_END) {
1287                if (0 < len && !s.avail_in) {
1288                        size_t cnt = in_sz < len ? in_sz : (size_t)len;
1289                        size_t n = fread(in_buf, 1, cnt, stdin);
1290                        if (!n && feof(stdin))
1291                                die("EOF in data (%" PRIuMAX " bytes remaining)", len);
1292
1293                        the_hash_algo->update_fn(&c, in_buf, n);
1294                        s.next_in = in_buf;
1295                        s.avail_in = n;
1296                        len -= n;
1297                }
1298
1299                status = git_deflate(&s, len ? 0 : Z_FINISH);
1300
1301                if (!s.avail_out || status == Z_STREAM_END) {
1302                        size_t n = s.next_out - out_buf;
1303                        hashwrite(pack_file, out_buf, n);
1304                        pack_size += n;
1305                        s.next_out = out_buf;
1306                        s.avail_out = out_sz;
1307                }
1308
1309                switch (status) {
1310                case Z_OK:
1311                case Z_BUF_ERROR:
1312                case Z_STREAM_END:
1313                        continue;
1314                default:
1315                        die("unexpected deflate failure: %d", status);
1316                }
1317        }
1318        git_deflate_end(&s);
1319        the_hash_algo->final_fn(oid.hash, &c);
1320
1321        if (oidout)
1322                oidcpy(oidout, &oid);
1323
1324        e = insert_object(&oid);
1325
1326        if (mark)
1327                insert_mark(mark, e);
1328
1329        if (e->idx.offset) {
1330                duplicate_count_by_type[OBJ_BLOB]++;
1331                truncate_pack(&checkpoint);
1332
1333        } else if (find_sha1_pack(oid.hash, packed_git)) {
1334                e->type = OBJ_BLOB;
1335                e->pack_id = MAX_PACK_ID;
1336                e->idx.offset = 1; /* just not zero! */
1337                duplicate_count_by_type[OBJ_BLOB]++;
1338                truncate_pack(&checkpoint);
1339
1340        } else {
1341                e->depth = 0;
1342                e->type = OBJ_BLOB;
1343                e->pack_id = pack_id;
1344                e->idx.offset = offset;
1345                e->idx.crc32 = crc32_end(pack_file);
1346                object_count++;
1347                object_count_by_type[OBJ_BLOB]++;
1348        }
1349
1350        free(in_buf);
1351        free(out_buf);
1352}
1353
1354/* All calls must be guarded by find_object() or find_mark() to
1355 * ensure the 'struct object_entry' passed was written by this
1356 * process instance.  We unpack the entry by the offset, avoiding
1357 * the need for the corresponding .idx file.  This unpacking rule
1358 * works because we only use OBJ_REF_DELTA within the packfiles
1359 * created by fast-import.
1360 *
1361 * oe must not be NULL.  Such an oe usually comes from giving
1362 * an unknown SHA-1 to find_object() or an undefined mark to
1363 * find_mark().  Callers must test for this condition and use
1364 * the standard read_sha1_file() when it happens.
1365 *
1366 * oe->pack_id must not be MAX_PACK_ID.  Such an oe is usually from
1367 * find_mark(), where the mark was reloaded from an existing marks
1368 * file and is referencing an object that this fast-import process
1369 * instance did not write out to a packfile.  Callers must test for
1370 * this condition and use read_sha1_file() instead.
1371 */
1372static void *gfi_unpack_entry(
1373        struct object_entry *oe,
1374        unsigned long *sizep)
1375{
1376        enum object_type type;
1377        struct packed_git *p = all_packs[oe->pack_id];
1378        if (p == pack_data && p->pack_size < (pack_size + the_hash_algo->rawsz)) {
1379                /* The object is stored in the packfile we are writing to
1380                 * and we have modified it since the last time we scanned
1381                 * back to read a previously written object.  If an old
1382                 * window covered [p->pack_size, p->pack_size + rawsz) its
1383                 * data is stale and is not valid.  Closing all windows
1384                 * and updating the packfile length ensures we can read
1385                 * the newly written data.
1386                 */
1387                close_pack_windows(p);
1388                hashflush(pack_file);
1389
1390                /* We have to offer rawsz bytes additional on the end of
1391                 * the packfile as the core unpacker code assumes the
1392                 * footer is present at the file end and must promise
1393                 * at least rawsz bytes within any window it maps.  But
1394                 * we don't actually create the footer here.
1395                 */
1396                p->pack_size = pack_size + the_hash_algo->rawsz;
1397        }
1398        return unpack_entry(p, oe->idx.offset, &type, sizep);
1399}
1400
1401static const char *get_mode(const char *str, uint16_t *modep)
1402{
1403        unsigned char c;
1404        uint16_t mode = 0;
1405
1406        while ((c = *str++) != ' ') {
1407                if (c < '0' || c > '7')
1408                        return NULL;
1409                mode = (mode << 3) + (c - '0');
1410        }
1411        *modep = mode;
1412        return str;
1413}
1414
1415static void load_tree(struct tree_entry *root)
1416{
1417        struct object_id *oid = &root->versions[1].oid;
1418        struct object_entry *myoe;
1419        struct tree_content *t;
1420        unsigned long size;
1421        char *buf;
1422        const char *c;
1423
1424        root->tree = t = new_tree_content(8);
1425        if (is_null_oid(oid))
1426                return;
1427
1428        myoe = find_object(oid);
1429        if (myoe && myoe->pack_id != MAX_PACK_ID) {
1430                if (myoe->type != OBJ_TREE)
1431                        die("Not a tree: %s", oid_to_hex(oid));
1432                t->delta_depth = myoe->depth;
1433                buf = gfi_unpack_entry(myoe, &size);
1434                if (!buf)
1435                        die("Can't load tree %s", oid_to_hex(oid));
1436        } else {
1437                enum object_type type;
1438                buf = read_sha1_file(oid->hash, &type, &size);
1439                if (!buf || type != OBJ_TREE)
1440                        die("Can't load tree %s", oid_to_hex(oid));
1441        }
1442
1443        c = buf;
1444        while (c != (buf + size)) {
1445                struct tree_entry *e = new_tree_entry();
1446
1447                if (t->entry_count == t->entry_capacity)
1448                        root->tree = t = grow_tree_content(t, t->entry_count);
1449                t->entries[t->entry_count++] = e;
1450
1451                e->tree = NULL;
1452                c = get_mode(c, &e->versions[1].mode);
1453                if (!c)
1454                        die("Corrupt mode in %s", oid_to_hex(oid));
1455                e->versions[0].mode = e->versions[1].mode;
1456                e->name = to_atom(c, strlen(c));
1457                c += e->name->str_len + 1;
1458                hashcpy(e->versions[0].oid.hash, (unsigned char *)c);
1459                hashcpy(e->versions[1].oid.hash, (unsigned char *)c);
1460                c += GIT_SHA1_RAWSZ;
1461        }
1462        free(buf);
1463}
1464
1465static int tecmp0 (const void *_a, const void *_b)
1466{
1467        struct tree_entry *a = *((struct tree_entry**)_a);
1468        struct tree_entry *b = *((struct tree_entry**)_b);
1469        return base_name_compare(
1470                a->name->str_dat, a->name->str_len, a->versions[0].mode,
1471                b->name->str_dat, b->name->str_len, b->versions[0].mode);
1472}
1473
1474static int tecmp1 (const void *_a, const void *_b)
1475{
1476        struct tree_entry *a = *((struct tree_entry**)_a);
1477        struct tree_entry *b = *((struct tree_entry**)_b);
1478        return base_name_compare(
1479                a->name->str_dat, a->name->str_len, a->versions[1].mode,
1480                b->name->str_dat, b->name->str_len, b->versions[1].mode);
1481}
1482
1483static void mktree(struct tree_content *t, int v, struct strbuf *b)
1484{
1485        size_t maxlen = 0;
1486        unsigned int i;
1487
1488        if (!v)
1489                QSORT(t->entries, t->entry_count, tecmp0);
1490        else
1491                QSORT(t->entries, t->entry_count, tecmp1);
1492
1493        for (i = 0; i < t->entry_count; i++) {
1494                if (t->entries[i]->versions[v].mode)
1495                        maxlen += t->entries[i]->name->str_len + 34;
1496        }
1497
1498        strbuf_reset(b);
1499        strbuf_grow(b, maxlen);
1500        for (i = 0; i < t->entry_count; i++) {
1501                struct tree_entry *e = t->entries[i];
1502                if (!e->versions[v].mode)
1503                        continue;
1504                strbuf_addf(b, "%o %s%c",
1505                        (unsigned int)(e->versions[v].mode & ~NO_DELTA),
1506                        e->name->str_dat, '\0');
1507                strbuf_add(b, e->versions[v].oid.hash, GIT_SHA1_RAWSZ);
1508        }
1509}
1510
1511static void store_tree(struct tree_entry *root)
1512{
1513        struct tree_content *t;
1514        unsigned int i, j, del;
1515        struct last_object lo = { STRBUF_INIT, 0, 0, /* no_swap */ 1 };
1516        struct object_entry *le = NULL;
1517
1518        if (!is_null_oid(&root->versions[1].oid))
1519                return;
1520
1521        if (!root->tree)
1522                load_tree(root);
1523        t = root->tree;
1524
1525        for (i = 0; i < t->entry_count; i++) {
1526                if (t->entries[i]->tree)
1527                        store_tree(t->entries[i]);
1528        }
1529
1530        if (!(root->versions[0].mode & NO_DELTA))
1531                le = find_object(&root->versions[0].oid);
1532        if (S_ISDIR(root->versions[0].mode) && le && le->pack_id == pack_id) {
1533                mktree(t, 0, &old_tree);
1534                lo.data = old_tree;
1535                lo.offset = le->idx.offset;
1536                lo.depth = t->delta_depth;
1537        }
1538
1539        mktree(t, 1, &new_tree);
1540        store_object(OBJ_TREE, &new_tree, &lo, &root->versions[1].oid, 0);
1541
1542        t->delta_depth = lo.depth;
1543        for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1544                struct tree_entry *e = t->entries[i];
1545                if (e->versions[1].mode) {
1546                        e->versions[0].mode = e->versions[1].mode;
1547                        oidcpy(&e->versions[0].oid, &e->versions[1].oid);
1548                        t->entries[j++] = e;
1549                } else {
1550                        release_tree_entry(e);
1551                        del++;
1552                }
1553        }
1554        t->entry_count -= del;
1555}
1556
1557static void tree_content_replace(
1558        struct tree_entry *root,
1559        const struct object_id *oid,
1560        const uint16_t mode,
1561        struct tree_content *newtree)
1562{
1563        if (!S_ISDIR(mode))
1564                die("Root cannot be a non-directory");
1565        oidclr(&root->versions[0].oid);
1566        oidcpy(&root->versions[1].oid, oid);
1567        if (root->tree)
1568                release_tree_content_recursive(root->tree);
1569        root->tree = newtree;
1570}
1571
1572static int tree_content_set(
1573        struct tree_entry *root,
1574        const char *p,
1575        const struct object_id *oid,
1576        const uint16_t mode,
1577        struct tree_content *subtree)
1578{
1579        struct tree_content *t;
1580        const char *slash1;
1581        unsigned int i, n;
1582        struct tree_entry *e;
1583
1584        slash1 = strchrnul(p, '/');
1585        n = slash1 - p;
1586        if (!n)
1587                die("Empty path component found in input");
1588        if (!*slash1 && !S_ISDIR(mode) && subtree)
1589                die("Non-directories cannot have subtrees");
1590
1591        if (!root->tree)
1592                load_tree(root);
1593        t = root->tree;
1594        for (i = 0; i < t->entry_count; i++) {
1595                e = t->entries[i];
1596                if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1597                        if (!*slash1) {
1598                                if (!S_ISDIR(mode)
1599                                                && e->versions[1].mode == mode
1600                                                && !oidcmp(&e->versions[1].oid, oid))
1601                                        return 0;
1602                                e->versions[1].mode = mode;
1603                                oidcpy(&e->versions[1].oid, oid);
1604                                if (e->tree)
1605                                        release_tree_content_recursive(e->tree);
1606                                e->tree = subtree;
1607
1608                                /*
1609                                 * We need to leave e->versions[0].sha1 alone
1610                                 * to avoid modifying the preimage tree used
1611                                 * when writing out the parent directory.
1612                                 * But after replacing the subdir with a
1613                                 * completely different one, it's not a good
1614                                 * delta base any more, and besides, we've
1615                                 * thrown away the tree entries needed to
1616                                 * make a delta against it.
1617                                 *
1618                                 * So let's just explicitly disable deltas
1619                                 * for the subtree.
1620                                 */
1621                                if (S_ISDIR(e->versions[0].mode))
1622                                        e->versions[0].mode |= NO_DELTA;
1623
1624                                oidclr(&root->versions[1].oid);
1625                                return 1;
1626                        }
1627                        if (!S_ISDIR(e->versions[1].mode)) {
1628                                e->tree = new_tree_content(8);
1629                                e->versions[1].mode = S_IFDIR;
1630                        }
1631                        if (!e->tree)
1632                                load_tree(e);
1633                        if (tree_content_set(e, slash1 + 1, oid, mode, subtree)) {
1634                                oidclr(&root->versions[1].oid);
1635                                return 1;
1636                        }
1637                        return 0;
1638                }
1639        }
1640
1641        if (t->entry_count == t->entry_capacity)
1642                root->tree = t = grow_tree_content(t, t->entry_count);
1643        e = new_tree_entry();
1644        e->name = to_atom(p, n);
1645        e->versions[0].mode = 0;
1646        oidclr(&e->versions[0].oid);
1647        t->entries[t->entry_count++] = e;
1648        if (*slash1) {
1649                e->tree = new_tree_content(8);
1650                e->versions[1].mode = S_IFDIR;
1651                tree_content_set(e, slash1 + 1, oid, mode, subtree);
1652        } else {
1653                e->tree = subtree;
1654                e->versions[1].mode = mode;
1655                oidcpy(&e->versions[1].oid, oid);
1656        }
1657        oidclr(&root->versions[1].oid);
1658        return 1;
1659}
1660
1661static int tree_content_remove(
1662        struct tree_entry *root,
1663        const char *p,
1664        struct tree_entry *backup_leaf,
1665        int allow_root)
1666{
1667        struct tree_content *t;
1668        const char *slash1;
1669        unsigned int i, n;
1670        struct tree_entry *e;
1671
1672        slash1 = strchrnul(p, '/');
1673        n = slash1 - p;
1674
1675        if (!root->tree)
1676                load_tree(root);
1677
1678        if (!*p && allow_root) {
1679                e = root;
1680                goto del_entry;
1681        }
1682
1683        t = root->tree;
1684        for (i = 0; i < t->entry_count; i++) {
1685                e = t->entries[i];
1686                if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1687                        if (*slash1 && !S_ISDIR(e->versions[1].mode))
1688                                /*
1689                                 * If p names a file in some subdirectory, and a
1690                                 * file or symlink matching the name of the
1691                                 * parent directory of p exists, then p cannot
1692                                 * exist and need not be deleted.
1693                                 */
1694                                return 1;
1695                        if (!*slash1 || !S_ISDIR(e->versions[1].mode))
1696                                goto del_entry;
1697                        if (!e->tree)
1698                                load_tree(e);
1699                        if (tree_content_remove(e, slash1 + 1, backup_leaf, 0)) {
1700                                for (n = 0; n < e->tree->entry_count; n++) {
1701                                        if (e->tree->entries[n]->versions[1].mode) {
1702                                                oidclr(&root->versions[1].oid);
1703                                                return 1;
1704                                        }
1705                                }
1706                                backup_leaf = NULL;
1707                                goto del_entry;
1708                        }
1709                        return 0;
1710                }
1711        }
1712        return 0;
1713
1714del_entry:
1715        if (backup_leaf)
1716                memcpy(backup_leaf, e, sizeof(*backup_leaf));
1717        else if (e->tree)
1718                release_tree_content_recursive(e->tree);
1719        e->tree = NULL;
1720        e->versions[1].mode = 0;
1721        oidclr(&e->versions[1].oid);
1722        oidclr(&root->versions[1].oid);
1723        return 1;
1724}
1725
1726static int tree_content_get(
1727        struct tree_entry *root,
1728        const char *p,
1729        struct tree_entry *leaf,
1730        int allow_root)
1731{
1732        struct tree_content *t;
1733        const char *slash1;
1734        unsigned int i, n;
1735        struct tree_entry *e;
1736
1737        slash1 = strchrnul(p, '/');
1738        n = slash1 - p;
1739        if (!n && !allow_root)
1740                die("Empty path component found in input");
1741
1742        if (!root->tree)
1743                load_tree(root);
1744
1745        if (!n) {
1746                e = root;
1747                goto found_entry;
1748        }
1749
1750        t = root->tree;
1751        for (i = 0; i < t->entry_count; i++) {
1752                e = t->entries[i];
1753                if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
1754                        if (!*slash1)
1755                                goto found_entry;
1756                        if (!S_ISDIR(e->versions[1].mode))
1757                                return 0;
1758                        if (!e->tree)
1759                                load_tree(e);
1760                        return tree_content_get(e, slash1 + 1, leaf, 0);
1761                }
1762        }
1763        return 0;
1764
1765found_entry:
1766        memcpy(leaf, e, sizeof(*leaf));
1767        if (e->tree && is_null_oid(&e->versions[1].oid))
1768                leaf->tree = dup_tree_content(e->tree);
1769        else
1770                leaf->tree = NULL;
1771        return 1;
1772}
1773
1774static int update_branch(struct branch *b)
1775{
1776        static const char *msg = "fast-import";
1777        struct ref_transaction *transaction;
1778        struct object_id old_oid;
1779        struct strbuf err = STRBUF_INIT;
1780
1781        if (is_null_oid(&b->oid)) {
1782                if (b->delete)
1783                        delete_ref(NULL, b->name, NULL, 0);
1784                return 0;
1785        }
1786        if (read_ref(b->name, &old_oid))
1787                oidclr(&old_oid);
1788        if (!force_update && !is_null_oid(&old_oid)) {
1789                struct commit *old_cmit, *new_cmit;
1790
1791                old_cmit = lookup_commit_reference_gently(&old_oid, 0);
1792                new_cmit = lookup_commit_reference_gently(&b->oid, 0);
1793                if (!old_cmit || !new_cmit)
1794                        return error("Branch %s is missing commits.", b->name);
1795
1796                if (!in_merge_bases(old_cmit, new_cmit)) {
1797                        warning("Not updating %s"
1798                                " (new tip %s does not contain %s)",
1799                                b->name, oid_to_hex(&b->oid),
1800                                oid_to_hex(&old_oid));
1801                        return -1;
1802                }
1803        }
1804        transaction = ref_transaction_begin(&err);
1805        if (!transaction ||
1806            ref_transaction_update(transaction, b->name, &b->oid, &old_oid,
1807                                   0, msg, &err) ||
1808            ref_transaction_commit(transaction, &err)) {
1809                ref_transaction_free(transaction);
1810                error("%s", err.buf);
1811                strbuf_release(&err);
1812                return -1;
1813        }
1814        ref_transaction_free(transaction);
1815        strbuf_release(&err);
1816        return 0;
1817}
1818
1819static void dump_branches(void)
1820{
1821        unsigned int i;
1822        struct branch *b;
1823
1824        for (i = 0; i < branch_table_sz; i++) {
1825                for (b = branch_table[i]; b; b = b->table_next_branch)
1826                        failure |= update_branch(b);
1827        }
1828}
1829
1830static void dump_tags(void)
1831{
1832        static const char *msg = "fast-import";
1833        struct tag *t;
1834        struct strbuf ref_name = STRBUF_INIT;
1835        struct strbuf err = STRBUF_INIT;
1836        struct ref_transaction *transaction;
1837
1838        transaction = ref_transaction_begin(&err);
1839        if (!transaction) {
1840                failure |= error("%s", err.buf);
1841                goto cleanup;
1842        }
1843        for (t = first_tag; t; t = t->next_tag) {
1844                strbuf_reset(&ref_name);
1845                strbuf_addf(&ref_name, "refs/tags/%s", t->name);
1846
1847                if (ref_transaction_update(transaction, ref_name.buf,
1848                                           &t->oid, NULL, 0, msg, &err)) {
1849                        failure |= error("%s", err.buf);
1850                        goto cleanup;
1851                }
1852        }
1853        if (ref_transaction_commit(transaction, &err))
1854                failure |= error("%s", err.buf);
1855
1856 cleanup:
1857        ref_transaction_free(transaction);
1858        strbuf_release(&ref_name);
1859        strbuf_release(&err);
1860}
1861
1862static void dump_marks_helper(FILE *f,
1863        uintmax_t base,
1864        struct mark_set *m)
1865{
1866        uintmax_t k;
1867        if (m->shift) {
1868                for (k = 0; k < 1024; k++) {
1869                        if (m->data.sets[k])
1870                                dump_marks_helper(f, base + (k << m->shift),
1871                                        m->data.sets[k]);
1872                }
1873        } else {
1874                for (k = 0; k < 1024; k++) {
1875                        if (m->data.marked[k])
1876                                fprintf(f, ":%" PRIuMAX " %s\n", base + k,
1877                                        oid_to_hex(&m->data.marked[k]->idx.oid));
1878                }
1879        }
1880}
1881
1882static void dump_marks(void)
1883{
1884        static struct lock_file mark_lock;
1885        FILE *f;
1886
1887        if (!export_marks_file || (import_marks_file && !import_marks_file_done))
1888                return;
1889
1890        if (hold_lock_file_for_update(&mark_lock, export_marks_file, 0) < 0) {
1891                failure |= error_errno("Unable to write marks file %s",
1892                                       export_marks_file);
1893                return;
1894        }
1895
1896        f = fdopen_lock_file(&mark_lock, "w");
1897        if (!f) {
1898                int saved_errno = errno;
1899                rollback_lock_file(&mark_lock);
1900                failure |= error("Unable to write marks file %s: %s",
1901                        export_marks_file, strerror(saved_errno));
1902                return;
1903        }
1904
1905        dump_marks_helper(f, 0, marks);
1906        if (commit_lock_file(&mark_lock)) {
1907                failure |= error_errno("Unable to write file %s",
1908                                       export_marks_file);
1909                return;
1910        }
1911}
1912
1913static void read_marks(void)
1914{
1915        char line[512];
1916        FILE *f = fopen(import_marks_file, "r");
1917        if (f)
1918                ;
1919        else if (import_marks_file_ignore_missing && errno == ENOENT)
1920                goto done; /* Marks file does not exist */
1921        else
1922                die_errno("cannot read '%s'", import_marks_file);
1923        while (fgets(line, sizeof(line), f)) {
1924                uintmax_t mark;
1925                char *end;
1926                struct object_id oid;
1927                struct object_entry *e;
1928
1929                end = strchr(line, '\n');
1930                if (line[0] != ':' || !end)
1931                        die("corrupt mark line: %s", line);
1932                *end = 0;
1933                mark = strtoumax(line + 1, &end, 10);
1934                if (!mark || end == line + 1
1935                        || *end != ' ' || get_oid_hex(end + 1, &oid))
1936                        die("corrupt mark line: %s", line);
1937                e = find_object(&oid);
1938                if (!e) {
1939                        enum object_type type = sha1_object_info(oid.hash, NULL);
1940                        if (type < 0)
1941                                die("object not found: %s", oid_to_hex(&oid));
1942                        e = insert_object(&oid);
1943                        e->type = type;
1944                        e->pack_id = MAX_PACK_ID;
1945                        e->idx.offset = 1; /* just not zero! */
1946                }
1947                insert_mark(mark, e);
1948        }
1949        fclose(f);
1950done:
1951        import_marks_file_done = 1;
1952}
1953
1954
1955static int read_next_command(void)
1956{
1957        static int stdin_eof = 0;
1958
1959        if (stdin_eof) {
1960                unread_command_buf = 0;
1961                return EOF;
1962        }
1963
1964        for (;;) {
1965                const char *p;
1966
1967                if (unread_command_buf) {
1968                        unread_command_buf = 0;
1969                } else {
1970                        struct recent_command *rc;
1971
1972                        strbuf_detach(&command_buf, NULL);
1973                        stdin_eof = strbuf_getline_lf(&command_buf, stdin);
1974                        if (stdin_eof)
1975                                return EOF;
1976
1977                        if (!seen_data_command
1978                                && !starts_with(command_buf.buf, "feature ")
1979                                && !starts_with(command_buf.buf, "option ")) {
1980                                parse_argv();
1981                        }
1982
1983                        rc = rc_free;
1984                        if (rc)
1985                                rc_free = rc->next;
1986                        else {
1987                                rc = cmd_hist.next;
1988                                cmd_hist.next = rc->next;
1989                                cmd_hist.next->prev = &cmd_hist;
1990                                free(rc->buf);
1991                        }
1992
1993                        rc->buf = command_buf.buf;
1994                        rc->prev = cmd_tail;
1995                        rc->next = cmd_hist.prev;
1996                        rc->prev->next = rc;
1997                        cmd_tail = rc;
1998                }
1999                if (skip_prefix(command_buf.buf, "get-mark ", &p)) {
2000                        parse_get_mark(p);
2001                        continue;
2002                }
2003                if (skip_prefix(command_buf.buf, "cat-blob ", &p)) {
2004                        parse_cat_blob(p);
2005                        continue;
2006                }
2007                if (command_buf.buf[0] == '#')
2008                        continue;
2009                return 0;
2010        }
2011}
2012
2013static void skip_optional_lf(void)
2014{
2015        int term_char = fgetc(stdin);
2016        if (term_char != '\n' && term_char != EOF)
2017                ungetc(term_char, stdin);
2018}
2019
2020static void parse_mark(void)
2021{
2022        const char *v;
2023        if (skip_prefix(command_buf.buf, "mark :", &v)) {
2024                next_mark = strtoumax(v, NULL, 10);
2025                read_next_command();
2026        }
2027        else
2028                next_mark = 0;
2029}
2030
2031static int parse_data(struct strbuf *sb, uintmax_t limit, uintmax_t *len_res)
2032{
2033        const char *data;
2034        strbuf_reset(sb);
2035
2036        if (!skip_prefix(command_buf.buf, "data ", &data))
2037                die("Expected 'data n' command, found: %s", command_buf.buf);
2038
2039        if (skip_prefix(data, "<<", &data)) {
2040                char *term = xstrdup(data);
2041                size_t term_len = command_buf.len - (data - command_buf.buf);
2042
2043                strbuf_detach(&command_buf, NULL);
2044                for (;;) {
2045                        if (strbuf_getline_lf(&command_buf, stdin) == EOF)
2046                                die("EOF in data (terminator '%s' not found)", term);
2047                        if (term_len == command_buf.len
2048                                && !strcmp(term, command_buf.buf))
2049                                break;
2050                        strbuf_addbuf(sb, &command_buf);
2051                        strbuf_addch(sb, '\n');
2052                }
2053                free(term);
2054        }
2055        else {
2056                uintmax_t len = strtoumax(data, NULL, 10);
2057                size_t n = 0, length = (size_t)len;
2058
2059                if (limit && limit < len) {
2060                        *len_res = len;
2061                        return 0;
2062                }
2063                if (length < len)
2064                        die("data is too large to use in this context");
2065
2066                while (n < length) {
2067                        size_t s = strbuf_fread(sb, length - n, stdin);
2068                        if (!s && feof(stdin))
2069                                die("EOF in data (%lu bytes remaining)",
2070                                        (unsigned long)(length - n));
2071                        n += s;
2072                }
2073        }
2074
2075        skip_optional_lf();
2076        return 1;
2077}
2078
2079static int validate_raw_date(const char *src, struct strbuf *result)
2080{
2081        const char *orig_src = src;
2082        char *endp;
2083        unsigned long num;
2084
2085        errno = 0;
2086
2087        num = strtoul(src, &endp, 10);
2088        /* NEEDSWORK: perhaps check for reasonable values? */
2089        if (errno || endp == src || *endp != ' ')
2090                return -1;
2091
2092        src = endp + 1;
2093        if (*src != '-' && *src != '+')
2094                return -1;
2095
2096        num = strtoul(src + 1, &endp, 10);
2097        if (errno || endp == src + 1 || *endp || 1400 < num)
2098                return -1;
2099
2100        strbuf_addstr(result, orig_src);
2101        return 0;
2102}
2103
2104static char *parse_ident(const char *buf)
2105{
2106        const char *ltgt;
2107        size_t name_len;
2108        struct strbuf ident = STRBUF_INIT;
2109
2110        /* ensure there is a space delimiter even if there is no name */
2111        if (*buf == '<')
2112                --buf;
2113
2114        ltgt = buf + strcspn(buf, "<>");
2115        if (*ltgt != '<')
2116                die("Missing < in ident string: %s", buf);
2117        if (ltgt != buf && ltgt[-1] != ' ')
2118                die("Missing space before < in ident string: %s", buf);
2119        ltgt = ltgt + 1 + strcspn(ltgt + 1, "<>");
2120        if (*ltgt != '>')
2121                die("Missing > in ident string: %s", buf);
2122        ltgt++;
2123        if (*ltgt != ' ')
2124                die("Missing space after > in ident string: %s", buf);
2125        ltgt++;
2126        name_len = ltgt - buf;
2127        strbuf_add(&ident, buf, name_len);
2128
2129        switch (whenspec) {
2130        case WHENSPEC_RAW:
2131                if (validate_raw_date(ltgt, &ident) < 0)
2132                        die("Invalid raw date \"%s\" in ident: %s", ltgt, buf);
2133                break;
2134        case WHENSPEC_RFC2822:
2135                if (parse_date(ltgt, &ident) < 0)
2136                        die("Invalid rfc2822 date \"%s\" in ident: %s", ltgt, buf);
2137                break;
2138        case WHENSPEC_NOW:
2139                if (strcmp("now", ltgt))
2140                        die("Date in ident must be 'now': %s", buf);
2141                datestamp(&ident);
2142                break;
2143        }
2144
2145        return strbuf_detach(&ident, NULL);
2146}
2147
2148static void parse_and_store_blob(
2149        struct last_object *last,
2150        struct object_id *oidout,
2151        uintmax_t mark)
2152{
2153        static struct strbuf buf = STRBUF_INIT;
2154        uintmax_t len;
2155
2156        if (parse_data(&buf, big_file_threshold, &len))
2157                store_object(OBJ_BLOB, &buf, last, oidout, mark);
2158        else {
2159                if (last) {
2160                        strbuf_release(&last->data);
2161                        last->offset = 0;
2162                        last->depth = 0;
2163                }
2164                stream_blob(len, oidout, mark);
2165                skip_optional_lf();
2166        }
2167}
2168
2169static void parse_new_blob(void)
2170{
2171        read_next_command();
2172        parse_mark();
2173        parse_and_store_blob(&last_blob, NULL, next_mark);
2174}
2175
2176static void unload_one_branch(void)
2177{
2178        while (cur_active_branches
2179                && cur_active_branches >= max_active_branches) {
2180                uintmax_t min_commit = ULONG_MAX;
2181                struct branch *e, *l = NULL, *p = NULL;
2182
2183                for (e = active_branches; e; e = e->active_next_branch) {
2184                        if (e->last_commit < min_commit) {
2185                                p = l;
2186                                min_commit = e->last_commit;
2187                        }
2188                        l = e;
2189                }
2190
2191                if (p) {
2192                        e = p->active_next_branch;
2193                        p->active_next_branch = e->active_next_branch;
2194                } else {
2195                        e = active_branches;
2196                        active_branches = e->active_next_branch;
2197                }
2198                e->active = 0;
2199                e->active_next_branch = NULL;
2200                if (e->branch_tree.tree) {
2201                        release_tree_content_recursive(e->branch_tree.tree);
2202                        e->branch_tree.tree = NULL;
2203                }
2204                cur_active_branches--;
2205        }
2206}
2207
2208static void load_branch(struct branch *b)
2209{
2210        load_tree(&b->branch_tree);
2211        if (!b->active) {
2212                b->active = 1;
2213                b->active_next_branch = active_branches;
2214                active_branches = b;
2215                cur_active_branches++;
2216                branch_load_count++;
2217        }
2218}
2219
2220static unsigned char convert_num_notes_to_fanout(uintmax_t num_notes)
2221{
2222        unsigned char fanout = 0;
2223        while ((num_notes >>= 8))
2224                fanout++;
2225        return fanout;
2226}
2227
2228static void construct_path_with_fanout(const char *hex_sha1,
2229                unsigned char fanout, char *path)
2230{
2231        unsigned int i = 0, j = 0;
2232        if (fanout >= the_hash_algo->rawsz)
2233                die("Too large fanout (%u)", fanout);
2234        while (fanout) {
2235                path[i++] = hex_sha1[j++];
2236                path[i++] = hex_sha1[j++];
2237                path[i++] = '/';
2238                fanout--;
2239        }
2240        memcpy(path + i, hex_sha1 + j, the_hash_algo->hexsz - j);
2241        path[i + the_hash_algo->hexsz - j] = '\0';
2242}
2243
2244static uintmax_t do_change_note_fanout(
2245                struct tree_entry *orig_root, struct tree_entry *root,
2246                char *hex_oid, unsigned int hex_oid_len,
2247                char *fullpath, unsigned int fullpath_len,
2248                unsigned char fanout)
2249{
2250        struct tree_content *t;
2251        struct tree_entry *e, leaf;
2252        unsigned int i, tmp_hex_oid_len, tmp_fullpath_len;
2253        uintmax_t num_notes = 0;
2254        struct object_id oid;
2255        char realpath[60];
2256
2257        if (!root->tree)
2258                load_tree(root);
2259        t = root->tree;
2260
2261        for (i = 0; t && i < t->entry_count; i++) {
2262                e = t->entries[i];
2263                tmp_hex_oid_len = hex_oid_len + e->name->str_len;
2264                tmp_fullpath_len = fullpath_len;
2265
2266                /*
2267                 * We're interested in EITHER existing note entries (entries
2268                 * with exactly 40 hex chars in path, not including directory
2269                 * separators), OR directory entries that may contain note
2270                 * entries (with < 40 hex chars in path).
2271                 * Also, each path component in a note entry must be a multiple
2272                 * of 2 chars.
2273                 */
2274                if (!e->versions[1].mode ||
2275                    tmp_hex_oid_len > GIT_SHA1_HEXSZ ||
2276                    e->name->str_len % 2)
2277                        continue;
2278
2279                /* This _may_ be a note entry, or a subdir containing notes */
2280                memcpy(hex_oid + hex_oid_len, e->name->str_dat,
2281                       e->name->str_len);
2282                if (tmp_fullpath_len)
2283                        fullpath[tmp_fullpath_len++] = '/';
2284                memcpy(fullpath + tmp_fullpath_len, e->name->str_dat,
2285                       e->name->str_len);
2286                tmp_fullpath_len += e->name->str_len;
2287                fullpath[tmp_fullpath_len] = '\0';
2288
2289                if (tmp_hex_oid_len == GIT_SHA1_HEXSZ && !get_oid_hex(hex_oid, &oid)) {
2290                        /* This is a note entry */
2291                        if (fanout == 0xff) {
2292                                /* Counting mode, no rename */
2293                                num_notes++;
2294                                continue;
2295                        }
2296                        construct_path_with_fanout(hex_oid, fanout, realpath);
2297                        if (!strcmp(fullpath, realpath)) {
2298                                /* Note entry is in correct location */
2299                                num_notes++;
2300                                continue;
2301                        }
2302
2303                        /* Rename fullpath to realpath */
2304                        if (!tree_content_remove(orig_root, fullpath, &leaf, 0))
2305                                die("Failed to remove path %s", fullpath);
2306                        tree_content_set(orig_root, realpath,
2307                                &leaf.versions[1].oid,
2308                                leaf.versions[1].mode,
2309                                leaf.tree);
2310                } else if (S_ISDIR(e->versions[1].mode)) {
2311                        /* This is a subdir that may contain note entries */
2312                        num_notes += do_change_note_fanout(orig_root, e,
2313                                hex_oid, tmp_hex_oid_len,
2314                                fullpath, tmp_fullpath_len, fanout);
2315                }
2316
2317                /* The above may have reallocated the current tree_content */
2318                t = root->tree;
2319        }
2320        return num_notes;
2321}
2322
2323static uintmax_t change_note_fanout(struct tree_entry *root,
2324                unsigned char fanout)
2325{
2326        /*
2327         * The size of path is due to one slash between every two hex digits,
2328         * plus the terminating NUL.  Note that there is no slash at the end, so
2329         * the number of slashes is one less than half the number of hex
2330         * characters.
2331         */
2332        char hex_oid[GIT_MAX_HEXSZ], path[GIT_MAX_HEXSZ + (GIT_MAX_HEXSZ / 2) - 1 + 1];
2333        return do_change_note_fanout(root, root, hex_oid, 0, path, 0, fanout);
2334}
2335
2336/*
2337 * Given a pointer into a string, parse a mark reference:
2338 *
2339 *   idnum ::= ':' bigint;
2340 *
2341 * Return the first character after the value in *endptr.
2342 *
2343 * Complain if the following character is not what is expected,
2344 * either a space or end of the string.
2345 */
2346static uintmax_t parse_mark_ref(const char *p, char **endptr)
2347{
2348        uintmax_t mark;
2349
2350        assert(*p == ':');
2351        p++;
2352        mark = strtoumax(p, endptr, 10);
2353        if (*endptr == p)
2354                die("No value after ':' in mark: %s", command_buf.buf);
2355        return mark;
2356}
2357
2358/*
2359 * Parse the mark reference, and complain if this is not the end of
2360 * the string.
2361 */
2362static uintmax_t parse_mark_ref_eol(const char *p)
2363{
2364        char *end;
2365        uintmax_t mark;
2366
2367        mark = parse_mark_ref(p, &end);
2368        if (*end != '\0')
2369                die("Garbage after mark: %s", command_buf.buf);
2370        return mark;
2371}
2372
2373/*
2374 * Parse the mark reference, demanding a trailing space.  Return a
2375 * pointer to the space.
2376 */
2377static uintmax_t parse_mark_ref_space(const char **p)
2378{
2379        uintmax_t mark;
2380        char *end;
2381
2382        mark = parse_mark_ref(*p, &end);
2383        if (*end++ != ' ')
2384                die("Missing space after mark: %s", command_buf.buf);
2385        *p = end;
2386        return mark;
2387}
2388
2389static void file_change_m(const char *p, struct branch *b)
2390{
2391        static struct strbuf uq = STRBUF_INIT;
2392        const char *endp;
2393        struct object_entry *oe;
2394        struct object_id oid;
2395        uint16_t mode, inline_data = 0;
2396
2397        p = get_mode(p, &mode);
2398        if (!p)
2399                die("Corrupt mode: %s", command_buf.buf);
2400        switch (mode) {
2401        case 0644:
2402        case 0755:
2403                mode |= S_IFREG;
2404        case S_IFREG | 0644:
2405        case S_IFREG | 0755:
2406        case S_IFLNK:
2407        case S_IFDIR:
2408        case S_IFGITLINK:
2409                /* ok */
2410                break;
2411        default:
2412                die("Corrupt mode: %s", command_buf.buf);
2413        }
2414
2415        if (*p == ':') {
2416                oe = find_mark(parse_mark_ref_space(&p));
2417                oidcpy(&oid, &oe->idx.oid);
2418        } else if (skip_prefix(p, "inline ", &p)) {
2419                inline_data = 1;
2420                oe = NULL; /* not used with inline_data, but makes gcc happy */
2421        } else {
2422                if (parse_oid_hex(p, &oid, &p))
2423                        die("Invalid dataref: %s", command_buf.buf);
2424                oe = find_object(&oid);
2425                if (*p++ != ' ')
2426                        die("Missing space after SHA1: %s", command_buf.buf);
2427        }
2428
2429        strbuf_reset(&uq);
2430        if (!unquote_c_style(&uq, p, &endp)) {
2431                if (*endp)
2432                        die("Garbage after path in: %s", command_buf.buf);
2433                p = uq.buf;
2434        }
2435
2436        /* Git does not track empty, non-toplevel directories. */
2437        if (S_ISDIR(mode) && is_empty_tree_oid(&oid) && *p) {
2438                tree_content_remove(&b->branch_tree, p, NULL, 0);
2439                return;
2440        }
2441
2442        if (S_ISGITLINK(mode)) {
2443                if (inline_data)
2444                        die("Git links cannot be specified 'inline': %s",
2445                                command_buf.buf);
2446                else if (oe) {
2447                        if (oe->type != OBJ_COMMIT)
2448                                die("Not a commit (actually a %s): %s",
2449                                        type_name(oe->type), command_buf.buf);
2450                }
2451                /*
2452                 * Accept the sha1 without checking; it expected to be in
2453                 * another repository.
2454                 */
2455        } else if (inline_data) {
2456                if (S_ISDIR(mode))
2457                        die("Directories cannot be specified 'inline': %s",
2458                                command_buf.buf);
2459                if (p != uq.buf) {
2460                        strbuf_addstr(&uq, p);
2461                        p = uq.buf;
2462                }
2463                read_next_command();
2464                parse_and_store_blob(&last_blob, &oid, 0);
2465        } else {
2466                enum object_type expected = S_ISDIR(mode) ?
2467                                                OBJ_TREE: OBJ_BLOB;
2468                enum object_type type = oe ? oe->type :
2469                                        sha1_object_info(oid.hash, NULL);
2470                if (type < 0)
2471                        die("%s not found: %s",
2472                                        S_ISDIR(mode) ?  "Tree" : "Blob",
2473                                        command_buf.buf);
2474                if (type != expected)
2475                        die("Not a %s (actually a %s): %s",
2476                                type_name(expected), type_name(type),
2477                                command_buf.buf);
2478        }
2479
2480        if (!*p) {
2481                tree_content_replace(&b->branch_tree, &oid, mode, NULL);
2482                return;
2483        }
2484        tree_content_set(&b->branch_tree, p, &oid, mode, NULL);
2485}
2486
2487static void file_change_d(const char *p, struct branch *b)
2488{
2489        static struct strbuf uq = STRBUF_INIT;
2490        const char *endp;
2491
2492        strbuf_reset(&uq);
2493        if (!unquote_c_style(&uq, p, &endp)) {
2494                if (*endp)
2495                        die("Garbage after path in: %s", command_buf.buf);
2496                p = uq.buf;
2497        }
2498        tree_content_remove(&b->branch_tree, p, NULL, 1);
2499}
2500
2501static void file_change_cr(const char *s, struct branch *b, int rename)
2502{
2503        const char *d;
2504        static struct strbuf s_uq = STRBUF_INIT;
2505        static struct strbuf d_uq = STRBUF_INIT;
2506        const char *endp;
2507        struct tree_entry leaf;
2508
2509        strbuf_reset(&s_uq);
2510        if (!unquote_c_style(&s_uq, s, &endp)) {
2511                if (*endp != ' ')
2512                        die("Missing space after source: %s", command_buf.buf);
2513        } else {
2514                endp = strchr(s, ' ');
2515                if (!endp)
2516                        die("Missing space after source: %s", command_buf.buf);
2517                strbuf_add(&s_uq, s, endp - s);
2518        }
2519        s = s_uq.buf;
2520
2521        endp++;
2522        if (!*endp)
2523                die("Missing dest: %s", command_buf.buf);
2524
2525        d = endp;
2526        strbuf_reset(&d_uq);
2527        if (!unquote_c_style(&d_uq, d, &endp)) {
2528                if (*endp)
2529                        die("Garbage after dest in: %s", command_buf.buf);
2530                d = d_uq.buf;
2531        }
2532
2533        memset(&leaf, 0, sizeof(leaf));
2534        if (rename)
2535                tree_content_remove(&b->branch_tree, s, &leaf, 1);
2536        else
2537                tree_content_get(&b->branch_tree, s, &leaf, 1);
2538        if (!leaf.versions[1].mode)
2539                die("Path %s not in branch", s);
2540        if (!*d) {      /* C "path/to/subdir" "" */
2541                tree_content_replace(&b->branch_tree,
2542                        &leaf.versions[1].oid,
2543                        leaf.versions[1].mode,
2544                        leaf.tree);
2545                return;
2546        }
2547        tree_content_set(&b->branch_tree, d,
2548                &leaf.versions[1].oid,
2549                leaf.versions[1].mode,
2550                leaf.tree);
2551}
2552
2553static void note_change_n(const char *p, struct branch *b, unsigned char *old_fanout)
2554{
2555        static struct strbuf uq = STRBUF_INIT;
2556        struct object_entry *oe;
2557        struct branch *s;
2558        struct object_id oid, commit_oid;
2559        char path[60];
2560        uint16_t inline_data = 0;
2561        unsigned char new_fanout;
2562
2563        /*
2564         * When loading a branch, we don't traverse its tree to count the real
2565         * number of notes (too expensive to do this for all non-note refs).
2566         * This means that recently loaded notes refs might incorrectly have
2567         * b->num_notes == 0, and consequently, old_fanout might be wrong.
2568         *
2569         * Fix this by traversing the tree and counting the number of notes
2570         * when b->num_notes == 0. If the notes tree is truly empty, the
2571         * calculation should not take long.
2572         */
2573        if (b->num_notes == 0 && *old_fanout == 0) {
2574                /* Invoke change_note_fanout() in "counting mode". */
2575                b->num_notes = change_note_fanout(&b->branch_tree, 0xff);
2576                *old_fanout = convert_num_notes_to_fanout(b->num_notes);
2577        }
2578
2579        /* Now parse the notemodify command. */
2580        /* <dataref> or 'inline' */
2581        if (*p == ':') {
2582                oe = find_mark(parse_mark_ref_space(&p));
2583                oidcpy(&oid, &oe->idx.oid);
2584        } else if (skip_prefix(p, "inline ", &p)) {
2585                inline_data = 1;
2586                oe = NULL; /* not used with inline_data, but makes gcc happy */
2587        } else {
2588                if (parse_oid_hex(p, &oid, &p))
2589                        die("Invalid dataref: %s", command_buf.buf);
2590                oe = find_object(&oid);
2591                if (*p++ != ' ')
2592                        die("Missing space after SHA1: %s", command_buf.buf);
2593        }
2594
2595        /* <commit-ish> */
2596        s = lookup_branch(p);
2597        if (s) {
2598                if (is_null_oid(&s->oid))
2599                        die("Can't add a note on empty branch.");
2600                oidcpy(&commit_oid, &s->oid);
2601        } else if (*p == ':') {
2602                uintmax_t commit_mark = parse_mark_ref_eol(p);
2603                struct object_entry *commit_oe = find_mark(commit_mark);
2604                if (commit_oe->type != OBJ_COMMIT)
2605                        die("Mark :%" PRIuMAX " not a commit", commit_mark);
2606                oidcpy(&commit_oid, &commit_oe->idx.oid);
2607        } else if (!get_oid(p, &commit_oid)) {
2608                unsigned long size;
2609                char *buf = read_object_with_reference(commit_oid.hash,
2610                        commit_type, &size, commit_oid.hash);
2611                if (!buf || size < 46)
2612                        die("Not a valid commit: %s", p);
2613                free(buf);
2614        } else
2615                die("Invalid ref name or SHA1 expression: %s", p);
2616
2617        if (inline_data) {
2618                if (p != uq.buf) {
2619                        strbuf_addstr(&uq, p);
2620                        p = uq.buf;
2621                }
2622                read_next_command();
2623                parse_and_store_blob(&last_blob, &oid, 0);
2624        } else if (oe) {
2625                if (oe->type != OBJ_BLOB)
2626                        die("Not a blob (actually a %s): %s",
2627                                type_name(oe->type), command_buf.buf);
2628        } else if (!is_null_oid(&oid)) {
2629                enum object_type type = sha1_object_info(oid.hash, NULL);
2630                if (type < 0)
2631                        die("Blob not found: %s", command_buf.buf);
2632                if (type != OBJ_BLOB)
2633                        die("Not a blob (actually a %s): %s",
2634                            type_name(type), command_buf.buf);
2635        }
2636
2637        construct_path_with_fanout(oid_to_hex(&commit_oid), *old_fanout, path);
2638        if (tree_content_remove(&b->branch_tree, path, NULL, 0))
2639                b->num_notes--;
2640
2641        if (is_null_oid(&oid))
2642                return; /* nothing to insert */
2643
2644        b->num_notes++;
2645        new_fanout = convert_num_notes_to_fanout(b->num_notes);
2646        construct_path_with_fanout(oid_to_hex(&commit_oid), new_fanout, path);
2647        tree_content_set(&b->branch_tree, path, &oid, S_IFREG | 0644, NULL);
2648}
2649
2650static void file_change_deleteall(struct branch *b)
2651{
2652        release_tree_content_recursive(b->branch_tree.tree);
2653        oidclr(&b->branch_tree.versions[0].oid);
2654        oidclr(&b->branch_tree.versions[1].oid);
2655        load_tree(&b->branch_tree);
2656        b->num_notes = 0;
2657}
2658
2659static void parse_from_commit(struct branch *b, char *buf, unsigned long size)
2660{
2661        if (!buf || size < GIT_SHA1_HEXSZ + 6)
2662                die("Not a valid commit: %s", oid_to_hex(&b->oid));
2663        if (memcmp("tree ", buf, 5)
2664                || get_oid_hex(buf + 5, &b->branch_tree.versions[1].oid))
2665                die("The commit %s is corrupt", oid_to_hex(&b->oid));
2666        oidcpy(&b->branch_tree.versions[0].oid,
2667               &b->branch_tree.versions[1].oid);
2668}
2669
2670static void parse_from_existing(struct branch *b)
2671{
2672        if (is_null_oid(&b->oid)) {
2673                oidclr(&b->branch_tree.versions[0].oid);
2674                oidclr(&b->branch_tree.versions[1].oid);
2675        } else {
2676                unsigned long size;
2677                char *buf;
2678
2679                buf = read_object_with_reference(b->oid.hash,
2680                                                 commit_type, &size,
2681                                                 b->oid.hash);
2682                parse_from_commit(b, buf, size);
2683                free(buf);
2684        }
2685}
2686
2687static int parse_from(struct branch *b)
2688{
2689        const char *from;
2690        struct branch *s;
2691        struct object_id oid;
2692
2693        if (!skip_prefix(command_buf.buf, "from ", &from))
2694                return 0;
2695
2696        oidcpy(&oid, &b->branch_tree.versions[1].oid);
2697
2698        s = lookup_branch(from);
2699        if (b == s)
2700                die("Can't create a branch from itself: %s", b->name);
2701        else if (s) {
2702                struct object_id *t = &s->branch_tree.versions[1].oid;
2703                oidcpy(&b->oid, &s->oid);
2704                oidcpy(&b->branch_tree.versions[0].oid, t);
2705                oidcpy(&b->branch_tree.versions[1].oid, t);
2706        } else if (*from == ':') {
2707                uintmax_t idnum = parse_mark_ref_eol(from);
2708                struct object_entry *oe = find_mark(idnum);
2709                if (oe->type != OBJ_COMMIT)
2710                        die("Mark :%" PRIuMAX " not a commit", idnum);
2711                if (oidcmp(&b->oid, &oe->idx.oid)) {
2712                        oidcpy(&b->oid, &oe->idx.oid);
2713                        if (oe->pack_id != MAX_PACK_ID) {
2714                                unsigned long size;
2715                                char *buf = gfi_unpack_entry(oe, &size);
2716                                parse_from_commit(b, buf, size);
2717                                free(buf);
2718                        } else
2719                                parse_from_existing(b);
2720                }
2721        } else if (!get_oid(from, &b->oid)) {
2722                parse_from_existing(b);
2723                if (is_null_oid(&b->oid))
2724                        b->delete = 1;
2725        }
2726        else
2727                die("Invalid ref name or SHA1 expression: %s", from);
2728
2729        if (b->branch_tree.tree && oidcmp(&oid, &b->branch_tree.versions[1].oid)) {
2730                release_tree_content_recursive(b->branch_tree.tree);
2731                b->branch_tree.tree = NULL;
2732        }
2733
2734        read_next_command();
2735        return 1;
2736}
2737
2738static struct hash_list *parse_merge(unsigned int *count)
2739{
2740        struct hash_list *list = NULL, **tail = &list, *n;
2741        const char *from;
2742        struct branch *s;
2743
2744        *count = 0;
2745        while (skip_prefix(command_buf.buf, "merge ", &from)) {
2746                n = xmalloc(sizeof(*n));
2747                s = lookup_branch(from);
2748                if (s)
2749                        oidcpy(&n->oid, &s->oid);
2750                else if (*from == ':') {
2751                        uintmax_t idnum = parse_mark_ref_eol(from);
2752                        struct object_entry *oe = find_mark(idnum);
2753                        if (oe->type != OBJ_COMMIT)
2754                                die("Mark :%" PRIuMAX " not a commit", idnum);
2755                        oidcpy(&n->oid, &oe->idx.oid);
2756                } else if (!get_oid(from, &n->oid)) {
2757                        unsigned long size;
2758                        char *buf = read_object_with_reference(n->oid.hash,
2759                                commit_type, &size, n->oid.hash);
2760                        if (!buf || size < 46)
2761                                die("Not a valid commit: %s", from);
2762                        free(buf);
2763                } else
2764                        die("Invalid ref name or SHA1 expression: %s", from);
2765
2766                n->next = NULL;
2767                *tail = n;
2768                tail = &n->next;
2769
2770                (*count)++;
2771                read_next_command();
2772        }
2773        return list;
2774}
2775
2776static void parse_new_commit(const char *arg)
2777{
2778        static struct strbuf msg = STRBUF_INIT;
2779        struct branch *b;
2780        char *author = NULL;
2781        char *committer = NULL;
2782        struct hash_list *merge_list = NULL;
2783        unsigned int merge_count;
2784        unsigned char prev_fanout, new_fanout;
2785        const char *v;
2786
2787        b = lookup_branch(arg);
2788        if (!b)
2789                b = new_branch(arg);
2790
2791        read_next_command();
2792        parse_mark();
2793        if (skip_prefix(command_buf.buf, "author ", &v)) {
2794                author = parse_ident(v);
2795                read_next_command();
2796        }
2797        if (skip_prefix(command_buf.buf, "committer ", &v)) {
2798                committer = parse_ident(v);
2799                read_next_command();
2800        }
2801        if (!committer)
2802                die("Expected committer but didn't get one");
2803        parse_data(&msg, 0, NULL);
2804        read_next_command();
2805        parse_from(b);
2806        merge_list = parse_merge(&merge_count);
2807
2808        /* ensure the branch is active/loaded */
2809        if (!b->branch_tree.tree || !max_active_branches) {
2810                unload_one_branch();
2811                load_branch(b);
2812        }
2813
2814        prev_fanout = convert_num_notes_to_fanout(b->num_notes);
2815
2816        /* file_change* */
2817        while (command_buf.len > 0) {
2818                if (skip_prefix(command_buf.buf, "M ", &v))
2819                        file_change_m(v, b);
2820                else if (skip_prefix(command_buf.buf, "D ", &v))
2821                        file_change_d(v, b);
2822                else if (skip_prefix(command_buf.buf, "R ", &v))
2823                        file_change_cr(v, b, 1);
2824                else if (skip_prefix(command_buf.buf, "C ", &v))
2825                        file_change_cr(v, b, 0);
2826                else if (skip_prefix(command_buf.buf, "N ", &v))
2827                        note_change_n(v, b, &prev_fanout);
2828                else if (!strcmp("deleteall", command_buf.buf))
2829                        file_change_deleteall(b);
2830                else if (skip_prefix(command_buf.buf, "ls ", &v))
2831                        parse_ls(v, b);
2832                else {
2833                        unread_command_buf = 1;
2834                        break;
2835                }
2836                if (read_next_command() == EOF)
2837                        break;
2838        }
2839
2840        new_fanout = convert_num_notes_to_fanout(b->num_notes);
2841        if (new_fanout != prev_fanout)
2842                b->num_notes = change_note_fanout(&b->branch_tree, new_fanout);
2843
2844        /* build the tree and the commit */
2845        store_tree(&b->branch_tree);
2846        oidcpy(&b->branch_tree.versions[0].oid,
2847               &b->branch_tree.versions[1].oid);
2848
2849        strbuf_reset(&new_data);
2850        strbuf_addf(&new_data, "tree %s\n",
2851                oid_to_hex(&b->branch_tree.versions[1].oid));
2852        if (!is_null_oid(&b->oid))
2853                strbuf_addf(&new_data, "parent %s\n",
2854                            oid_to_hex(&b->oid));
2855        while (merge_list) {
2856                struct hash_list *next = merge_list->next;
2857                strbuf_addf(&new_data, "parent %s\n",
2858                            oid_to_hex(&merge_list->oid));
2859                free(merge_list);
2860                merge_list = next;
2861        }
2862        strbuf_addf(&new_data,
2863                "author %s\n"
2864                "committer %s\n"
2865                "\n",
2866                author ? author : committer, committer);
2867        strbuf_addbuf(&new_data, &msg);
2868        free(author);
2869        free(committer);
2870
2871        if (!store_object(OBJ_COMMIT, &new_data, NULL, &b->oid, next_mark))
2872                b->pack_id = pack_id;
2873        b->last_commit = object_count_by_type[OBJ_COMMIT];
2874}
2875
2876static void parse_new_tag(const char *arg)
2877{
2878        static struct strbuf msg = STRBUF_INIT;
2879        const char *from;
2880        char *tagger;
2881        struct branch *s;
2882        struct tag *t;
2883        uintmax_t from_mark = 0;
2884        struct object_id oid;
2885        enum object_type type;
2886        const char *v;
2887
2888        t = mem_pool_alloc(&fi_mem_pool, sizeof(struct tag));
2889        memset(t, 0, sizeof(struct tag));
2890        t->name = pool_strdup(arg);
2891        if (last_tag)
2892                last_tag->next_tag = t;
2893        else
2894                first_tag = t;
2895        last_tag = t;
2896        read_next_command();
2897
2898        /* from ... */
2899        if (!skip_prefix(command_buf.buf, "from ", &from))
2900                die("Expected from command, got %s", command_buf.buf);
2901        s = lookup_branch(from);
2902        if (s) {
2903                if (is_null_oid(&s->oid))
2904                        die("Can't tag an empty branch.");
2905                oidcpy(&oid, &s->oid);
2906                type = OBJ_COMMIT;
2907        } else if (*from == ':') {
2908                struct object_entry *oe;
2909                from_mark = parse_mark_ref_eol(from);
2910                oe = find_mark(from_mark);
2911                type = oe->type;
2912                oidcpy(&oid, &oe->idx.oid);
2913        } else if (!get_oid(from, &oid)) {
2914                struct object_entry *oe = find_object(&oid);
2915                if (!oe) {
2916                        type = sha1_object_info(oid.hash, NULL);
2917                        if (type < 0)
2918                                die("Not a valid object: %s", from);
2919                } else
2920                        type = oe->type;
2921        } else
2922                die("Invalid ref name or SHA1 expression: %s", from);
2923        read_next_command();
2924
2925        /* tagger ... */
2926        if (skip_prefix(command_buf.buf, "tagger ", &v)) {
2927                tagger = parse_ident(v);
2928                read_next_command();
2929        } else
2930                tagger = NULL;
2931
2932        /* tag payload/message */
2933        parse_data(&msg, 0, NULL);
2934
2935        /* build the tag object */
2936        strbuf_reset(&new_data);
2937
2938        strbuf_addf(&new_data,
2939                    "object %s\n"
2940                    "type %s\n"
2941                    "tag %s\n",
2942                    oid_to_hex(&oid), type_name(type), t->name);
2943        if (tagger)
2944                strbuf_addf(&new_data,
2945                            "tagger %s\n", tagger);
2946        strbuf_addch(&new_data, '\n');
2947        strbuf_addbuf(&new_data, &msg);
2948        free(tagger);
2949
2950        if (store_object(OBJ_TAG, &new_data, NULL, &t->oid, 0))
2951                t->pack_id = MAX_PACK_ID;
2952        else
2953                t->pack_id = pack_id;
2954}
2955
2956static void parse_reset_branch(const char *arg)
2957{
2958        struct branch *b;
2959
2960        b = lookup_branch(arg);
2961        if (b) {
2962                oidclr(&b->oid);
2963                oidclr(&b->branch_tree.versions[0].oid);
2964                oidclr(&b->branch_tree.versions[1].oid);
2965                if (b->branch_tree.tree) {
2966                        release_tree_content_recursive(b->branch_tree.tree);
2967                        b->branch_tree.tree = NULL;
2968                }
2969        }
2970        else
2971                b = new_branch(arg);
2972        read_next_command();
2973        parse_from(b);
2974        if (command_buf.len > 0)
2975                unread_command_buf = 1;
2976}
2977
2978static void cat_blob_write(const char *buf, unsigned long size)
2979{
2980        if (write_in_full(cat_blob_fd, buf, size) < 0)
2981                die_errno("Write to frontend failed");
2982}
2983
2984static void cat_blob(struct object_entry *oe, struct object_id *oid)
2985{
2986        struct strbuf line = STRBUF_INIT;
2987        unsigned long size;
2988        enum object_type type = 0;
2989        char *buf;
2990
2991        if (!oe || oe->pack_id == MAX_PACK_ID) {
2992                buf = read_sha1_file(oid->hash, &type, &size);
2993        } else {
2994                type = oe->type;
2995                buf = gfi_unpack_entry(oe, &size);
2996        }
2997
2998        /*
2999         * Output based on batch_one_object() from cat-file.c.
3000         */
3001        if (type <= 0) {
3002                strbuf_reset(&line);
3003                strbuf_addf(&line, "%s missing\n", oid_to_hex(oid));
3004                cat_blob_write(line.buf, line.len);
3005                strbuf_release(&line);
3006                free(buf);
3007                return;
3008        }
3009        if (!buf)
3010                die("Can't read object %s", oid_to_hex(oid));
3011        if (type != OBJ_BLOB)
3012                die("Object %s is a %s but a blob was expected.",
3013                    oid_to_hex(oid), type_name(type));
3014        strbuf_reset(&line);
3015        strbuf_addf(&line, "%s %s %lu\n", oid_to_hex(oid),
3016                                                type_name(type), size);
3017        cat_blob_write(line.buf, line.len);
3018        strbuf_release(&line);
3019        cat_blob_write(buf, size);
3020        cat_blob_write("\n", 1);
3021        if (oe && oe->pack_id == pack_id) {
3022                last_blob.offset = oe->idx.offset;
3023                strbuf_attach(&last_blob.data, buf, size, size);
3024                last_blob.depth = oe->depth;
3025        } else
3026                free(buf);
3027}
3028
3029static void parse_get_mark(const char *p)
3030{
3031        struct object_entry *oe;
3032        char output[GIT_MAX_HEXSZ + 2];
3033
3034        /* get-mark SP <object> LF */
3035        if (*p != ':')
3036                die("Not a mark: %s", p);
3037
3038        oe = find_mark(parse_mark_ref_eol(p));
3039        if (!oe)
3040                die("Unknown mark: %s", command_buf.buf);
3041
3042        xsnprintf(output, sizeof(output), "%s\n", oid_to_hex(&oe->idx.oid));
3043        cat_blob_write(output, GIT_SHA1_HEXSZ + 1);
3044}
3045
3046static void parse_cat_blob(const char *p)
3047{
3048        struct object_entry *oe;
3049        struct object_id oid;
3050
3051        /* cat-blob SP <object> LF */
3052        if (*p == ':') {
3053                oe = find_mark(parse_mark_ref_eol(p));
3054                if (!oe)
3055                        die("Unknown mark: %s", command_buf.buf);
3056                oidcpy(&oid, &oe->idx.oid);
3057        } else {
3058                if (parse_oid_hex(p, &oid, &p))
3059                        die("Invalid dataref: %s", command_buf.buf);
3060                if (*p)
3061                        die("Garbage after SHA1: %s", command_buf.buf);
3062                oe = find_object(&oid);
3063        }
3064
3065        cat_blob(oe, &oid);
3066}
3067
3068static struct object_entry *dereference(struct object_entry *oe,
3069                                        struct object_id *oid)
3070{
3071        unsigned long size;
3072        char *buf = NULL;
3073        if (!oe) {
3074                enum object_type type = sha1_object_info(oid->hash, NULL);
3075                if (type < 0)
3076                        die("object not found: %s", oid_to_hex(oid));
3077                /* cache it! */
3078                oe = insert_object(oid);
3079                oe->type = type;
3080                oe->pack_id = MAX_PACK_ID;
3081                oe->idx.offset = 1;
3082        }
3083        switch (oe->type) {
3084        case OBJ_TREE:  /* easy case. */
3085                return oe;
3086        case OBJ_COMMIT:
3087        case OBJ_TAG:
3088                break;
3089        default:
3090                die("Not a tree-ish: %s", command_buf.buf);
3091        }
3092
3093        if (oe->pack_id != MAX_PACK_ID) {       /* in a pack being written */
3094                buf = gfi_unpack_entry(oe, &size);
3095        } else {
3096                enum object_type unused;
3097                buf = read_sha1_file(oid->hash, &unused, &size);
3098        }
3099        if (!buf)
3100                die("Can't load object %s", oid_to_hex(oid));
3101
3102        /* Peel one layer. */
3103        switch (oe->type) {
3104        case OBJ_TAG:
3105                if (size < GIT_SHA1_HEXSZ + strlen("object ") ||
3106                    get_oid_hex(buf + strlen("object "), oid))
3107                        die("Invalid SHA1 in tag: %s", command_buf.buf);
3108                break;
3109        case OBJ_COMMIT:
3110                if (size < GIT_SHA1_HEXSZ + strlen("tree ") ||
3111                    get_oid_hex(buf + strlen("tree "), oid))
3112                        die("Invalid SHA1 in commit: %s", command_buf.buf);
3113        }
3114
3115        free(buf);
3116        return find_object(oid);
3117}
3118
3119static struct object_entry *parse_treeish_dataref(const char **p)
3120{
3121        struct object_id oid;
3122        struct object_entry *e;
3123
3124        if (**p == ':') {       /* <mark> */
3125                e = find_mark(parse_mark_ref_space(p));
3126                if (!e)
3127                        die("Unknown mark: %s", command_buf.buf);
3128                oidcpy(&oid, &e->idx.oid);
3129        } else {        /* <sha1> */
3130                if (parse_oid_hex(*p, &oid, p))
3131                        die("Invalid dataref: %s", command_buf.buf);
3132                e = find_object(&oid);
3133                if (*(*p)++ != ' ')
3134                        die("Missing space after tree-ish: %s", command_buf.buf);
3135        }
3136
3137        while (!e || e->type != OBJ_TREE)
3138                e = dereference(e, &oid);
3139        return e;
3140}
3141
3142static void print_ls(int mode, const unsigned char *sha1, const char *path)
3143{
3144        static struct strbuf line = STRBUF_INIT;
3145
3146        /* See show_tree(). */
3147        const char *type =
3148                S_ISGITLINK(mode) ? commit_type :
3149                S_ISDIR(mode) ? tree_type :
3150                blob_type;
3151
3152        if (!mode) {
3153                /* missing SP path LF */
3154                strbuf_reset(&line);
3155                strbuf_addstr(&line, "missing ");
3156                quote_c_style(path, &line, NULL, 0);
3157                strbuf_addch(&line, '\n');
3158        } else {
3159                /* mode SP type SP object_name TAB path LF */
3160                strbuf_reset(&line);
3161                strbuf_addf(&line, "%06o %s %s\t",
3162                                mode & ~NO_DELTA, type, sha1_to_hex(sha1));
3163                quote_c_style(path, &line, NULL, 0);
3164                strbuf_addch(&line, '\n');
3165        }
3166        cat_blob_write(line.buf, line.len);
3167}
3168
3169static void parse_ls(const char *p, struct branch *b)
3170{
3171        struct tree_entry *root = NULL;
3172        struct tree_entry leaf = {NULL};
3173
3174        /* ls SP (<tree-ish> SP)? <path> */
3175        if (*p == '"') {
3176                if (!b)
3177                        die("Not in a commit: %s", command_buf.buf);
3178                root = &b->branch_tree;
3179        } else {
3180                struct object_entry *e = parse_treeish_dataref(&p);
3181                root = new_tree_entry();
3182                oidcpy(&root->versions[1].oid, &e->idx.oid);
3183                if (!is_null_oid(&root->versions[1].oid))
3184                        root->versions[1].mode = S_IFDIR;
3185                load_tree(root);
3186        }
3187        if (*p == '"') {
3188                static struct strbuf uq = STRBUF_INIT;
3189                const char *endp;
3190                strbuf_reset(&uq);
3191                if (unquote_c_style(&uq, p, &endp))
3192                        die("Invalid path: %s", command_buf.buf);
3193                if (*endp)
3194                        die("Garbage after path in: %s", command_buf.buf);
3195                p = uq.buf;
3196        }
3197        tree_content_get(root, p, &leaf, 1);
3198        /*
3199         * A directory in preparation would have a sha1 of zero
3200         * until it is saved.  Save, for simplicity.
3201         */
3202        if (S_ISDIR(leaf.versions[1].mode))
3203                store_tree(&leaf);
3204
3205        print_ls(leaf.versions[1].mode, leaf.versions[1].oid.hash, p);
3206        if (leaf.tree)
3207                release_tree_content_recursive(leaf.tree);
3208        if (!b || root != &b->branch_tree)
3209                release_tree_entry(root);
3210}
3211
3212static void checkpoint(void)
3213{
3214        checkpoint_requested = 0;
3215        if (object_count) {
3216                cycle_packfile();
3217        }
3218        dump_branches();
3219        dump_tags();
3220        dump_marks();
3221}
3222
3223static void parse_checkpoint(void)
3224{
3225        checkpoint_requested = 1;
3226        skip_optional_lf();
3227}
3228
3229static void parse_progress(void)
3230{
3231        fwrite(command_buf.buf, 1, command_buf.len, stdout);
3232        fputc('\n', stdout);
3233        fflush(stdout);
3234        skip_optional_lf();
3235}
3236
3237static char* make_fast_import_path(const char *path)
3238{
3239        if (!relative_marks_paths || is_absolute_path(path))
3240                return xstrdup(path);
3241        return git_pathdup("info/fast-import/%s", path);
3242}
3243
3244static void option_import_marks(const char *marks,
3245                                        int from_stream, int ignore_missing)
3246{
3247        if (import_marks_file) {
3248                if (from_stream)
3249                        die("Only one import-marks command allowed per stream");
3250
3251                /* read previous mark file */
3252                if(!import_marks_file_from_stream)
3253                        read_marks();
3254        }
3255
3256        import_marks_file = make_fast_import_path(marks);
3257        safe_create_leading_directories_const(import_marks_file);
3258        import_marks_file_from_stream = from_stream;
3259        import_marks_file_ignore_missing = ignore_missing;
3260}
3261
3262static void option_date_format(const char *fmt)
3263{
3264        if (!strcmp(fmt, "raw"))
3265                whenspec = WHENSPEC_RAW;
3266        else if (!strcmp(fmt, "rfc2822"))
3267                whenspec = WHENSPEC_RFC2822;
3268        else if (!strcmp(fmt, "now"))
3269                whenspec = WHENSPEC_NOW;
3270        else
3271                die("unknown --date-format argument %s", fmt);
3272}
3273
3274static unsigned long ulong_arg(const char *option, const char *arg)
3275{
3276        char *endptr;
3277        unsigned long rv = strtoul(arg, &endptr, 0);
3278        if (strchr(arg, '-') || endptr == arg || *endptr)
3279                die("%s: argument must be a non-negative integer", option);
3280        return rv;
3281}
3282
3283static void option_depth(const char *depth)
3284{
3285        max_depth = ulong_arg("--depth", depth);
3286        if (max_depth > MAX_DEPTH)
3287                die("--depth cannot exceed %u", MAX_DEPTH);
3288}
3289
3290static void option_active_branches(const char *branches)
3291{
3292        max_active_branches = ulong_arg("--active-branches", branches);
3293}
3294
3295static void option_export_marks(const char *marks)
3296{
3297        export_marks_file = make_fast_import_path(marks);
3298        safe_create_leading_directories_const(export_marks_file);
3299}
3300
3301static void option_cat_blob_fd(const char *fd)
3302{
3303        unsigned long n = ulong_arg("--cat-blob-fd", fd);
3304        if (n > (unsigned long) INT_MAX)
3305                die("--cat-blob-fd cannot exceed %d", INT_MAX);
3306        cat_blob_fd = (int) n;
3307}
3308
3309static void option_export_pack_edges(const char *edges)
3310{
3311        if (pack_edges)
3312                fclose(pack_edges);
3313        pack_edges = xfopen(edges, "a");
3314}
3315
3316static int parse_one_option(const char *option)
3317{
3318        if (skip_prefix(option, "max-pack-size=", &option)) {
3319                unsigned long v;
3320                if (!git_parse_ulong(option, &v))
3321                        return 0;
3322                if (v < 8192) {
3323                        warning("max-pack-size is now in bytes, assuming --max-pack-size=%lum", v);
3324                        v *= 1024 * 1024;
3325                } else if (v < 1024 * 1024) {
3326                        warning("minimum max-pack-size is 1 MiB");
3327                        v = 1024 * 1024;
3328                }
3329                max_packsize = v;
3330        } else if (skip_prefix(option, "big-file-threshold=", &option)) {
3331                unsigned long v;
3332                if (!git_parse_ulong(option, &v))
3333                        return 0;
3334                big_file_threshold = v;
3335        } else if (skip_prefix(option, "depth=", &option)) {
3336                option_depth(option);
3337        } else if (skip_prefix(option, "active-branches=", &option)) {
3338                option_active_branches(option);
3339        } else if (skip_prefix(option, "export-pack-edges=", &option)) {
3340                option_export_pack_edges(option);
3341        } else if (starts_with(option, "quiet")) {
3342                show_stats = 0;
3343        } else if (starts_with(option, "stats")) {
3344                show_stats = 1;
3345        } else {
3346                return 0;
3347        }
3348
3349        return 1;
3350}
3351
3352static int parse_one_feature(const char *feature, int from_stream)
3353{
3354        const char *arg;
3355
3356        if (skip_prefix(feature, "date-format=", &arg)) {
3357                option_date_format(arg);
3358        } else if (skip_prefix(feature, "import-marks=", &arg)) {
3359                option_import_marks(arg, from_stream, 0);
3360        } else if (skip_prefix(feature, "import-marks-if-exists=", &arg)) {
3361                option_import_marks(arg, from_stream, 1);
3362        } else if (skip_prefix(feature, "export-marks=", &arg)) {
3363                option_export_marks(arg);
3364        } else if (!strcmp(feature, "get-mark")) {
3365                ; /* Don't die - this feature is supported */
3366        } else if (!strcmp(feature, "cat-blob")) {
3367                ; /* Don't die - this feature is supported */
3368        } else if (!strcmp(feature, "relative-marks")) {
3369                relative_marks_paths = 1;
3370        } else if (!strcmp(feature, "no-relative-marks")) {
3371                relative_marks_paths = 0;
3372        } else if (!strcmp(feature, "done")) {
3373                require_explicit_termination = 1;
3374        } else if (!strcmp(feature, "force")) {
3375                force_update = 1;
3376        } else if (!strcmp(feature, "notes") || !strcmp(feature, "ls")) {
3377                ; /* do nothing; we have the feature */
3378        } else {
3379                return 0;
3380        }
3381
3382        return 1;
3383}
3384
3385static void parse_feature(const char *feature)
3386{
3387        if (seen_data_command)
3388                die("Got feature command '%s' after data command", feature);
3389
3390        if (parse_one_feature(feature, 1))
3391                return;
3392
3393        die("This version of fast-import does not support feature %s.", feature);
3394}
3395
3396static void parse_option(const char *option)
3397{
3398        if (seen_data_command)
3399                die("Got option command '%s' after data command", option);
3400
3401        if (parse_one_option(option))
3402                return;
3403
3404        die("This version of fast-import does not support option: %s", option);
3405}
3406
3407static void git_pack_config(void)
3408{
3409        int indexversion_value;
3410        int limit;
3411        unsigned long packsizelimit_value;
3412
3413        if (!git_config_get_ulong("pack.depth", &max_depth)) {
3414                if (max_depth > MAX_DEPTH)
3415                        max_depth = MAX_DEPTH;
3416        }
3417        if (!git_config_get_int("pack.indexversion", &indexversion_value)) {
3418                pack_idx_opts.version = indexversion_value;
3419                if (pack_idx_opts.version > 2)
3420                        git_die_config("pack.indexversion",
3421                                        "bad pack.indexversion=%"PRIu32, pack_idx_opts.version);
3422        }
3423        if (!git_config_get_ulong("pack.packsizelimit", &packsizelimit_value))
3424                max_packsize = packsizelimit_value;
3425
3426        if (!git_config_get_int("fastimport.unpacklimit", &limit))
3427                unpack_limit = limit;
3428        else if (!git_config_get_int("transfer.unpacklimit", &limit))
3429                unpack_limit = limit;
3430
3431        git_config(git_default_config, NULL);
3432}
3433
3434static const char fast_import_usage[] =
3435"git fast-import [--date-format=<f>] [--max-pack-size=<n>] [--big-file-threshold=<n>] [--depth=<n>] [--active-branches=<n>] [--export-marks=<marks.file>]";
3436
3437static void parse_argv(void)
3438{
3439        unsigned int i;
3440
3441        for (i = 1; i < global_argc; i++) {
3442                const char *a = global_argv[i];
3443
3444                if (*a != '-' || !strcmp(a, "--"))
3445                        break;
3446
3447                if (!skip_prefix(a, "--", &a))
3448                        die("unknown option %s", a);
3449
3450                if (parse_one_option(a))
3451                        continue;
3452
3453                if (parse_one_feature(a, 0))
3454                        continue;
3455
3456                if (skip_prefix(a, "cat-blob-fd=", &a)) {
3457                        option_cat_blob_fd(a);
3458                        continue;
3459                }
3460
3461                die("unknown option --%s", a);
3462        }
3463        if (i != global_argc)
3464                usage(fast_import_usage);
3465
3466        seen_data_command = 1;
3467        if (import_marks_file)
3468                read_marks();
3469}
3470
3471int cmd_main(int argc, const char **argv)
3472{
3473        unsigned int i;
3474
3475        if (argc == 2 && !strcmp(argv[1], "-h"))
3476                usage(fast_import_usage);
3477
3478        setup_git_directory();
3479        reset_pack_idx_option(&pack_idx_opts);
3480        git_pack_config();
3481
3482        alloc_objects(object_entry_alloc);
3483        strbuf_init(&command_buf, 0);
3484        atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
3485        branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
3486        avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
3487        marks = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
3488
3489        global_argc = argc;
3490        global_argv = argv;
3491
3492        rc_free = mem_pool_alloc(&fi_mem_pool, cmd_save * sizeof(*rc_free));
3493        for (i = 0; i < (cmd_save - 1); i++)
3494                rc_free[i].next = &rc_free[i + 1];
3495        rc_free[cmd_save - 1].next = NULL;
3496
3497        prepare_packed_git();
3498        start_packfile();
3499        set_die_routine(die_nicely);
3500        set_checkpoint_signal();
3501        while (read_next_command() != EOF) {
3502                const char *v;
3503                if (!strcmp("blob", command_buf.buf))
3504                        parse_new_blob();
3505                else if (skip_prefix(command_buf.buf, "ls ", &v))
3506                        parse_ls(v, NULL);
3507                else if (skip_prefix(command_buf.buf, "commit ", &v))
3508                        parse_new_commit(v);
3509                else if (skip_prefix(command_buf.buf, "tag ", &v))
3510                        parse_new_tag(v);
3511                else if (skip_prefix(command_buf.buf, "reset ", &v))
3512                        parse_reset_branch(v);
3513                else if (!strcmp("checkpoint", command_buf.buf))
3514                        parse_checkpoint();
3515                else if (!strcmp("done", command_buf.buf))
3516                        break;
3517                else if (starts_with(command_buf.buf, "progress "))
3518                        parse_progress();
3519                else if (skip_prefix(command_buf.buf, "feature ", &v))
3520                        parse_feature(v);
3521                else if (skip_prefix(command_buf.buf, "option git ", &v))
3522                        parse_option(v);
3523                else if (starts_with(command_buf.buf, "option "))
3524                        /* ignore non-git options*/;
3525                else
3526                        die("Unsupported command: %s", command_buf.buf);
3527
3528                if (checkpoint_requested)
3529                        checkpoint();
3530        }
3531
3532        /* argv hasn't been parsed yet, do so */
3533        if (!seen_data_command)
3534                parse_argv();
3535
3536        if (require_explicit_termination && feof(stdin))
3537                die("stream ends early");
3538
3539        end_packfile();
3540
3541        dump_branches();
3542        dump_tags();
3543        unkeep_all_packs();
3544        dump_marks();
3545
3546        if (pack_edges)
3547                fclose(pack_edges);
3548
3549        if (show_stats) {
3550                uintmax_t total_count = 0, duplicate_count = 0;
3551                for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
3552                        total_count += object_count_by_type[i];
3553                for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
3554                        duplicate_count += duplicate_count_by_type[i];
3555
3556                fprintf(stderr, "%s statistics:\n", argv[0]);
3557                fprintf(stderr, "---------------------------------------------------------------------\n");
3558                fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
3559                fprintf(stderr, "Total objects:   %10" PRIuMAX " (%10" PRIuMAX " duplicates                  )\n", total_count, duplicate_count);
3560                fprintf(stderr, "      blobs  :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB], delta_count_attempts_by_type[OBJ_BLOB]);
3561                fprintf(stderr, "      trees  :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE], delta_count_attempts_by_type[OBJ_TREE]);
3562                fprintf(stderr, "      commits:   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT], delta_count_attempts_by_type[OBJ_COMMIT]);
3563                fprintf(stderr, "      tags   :   %10" PRIuMAX " (%10" PRIuMAX " duplicates %10" PRIuMAX " deltas of %10" PRIuMAX" attempts)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG], delta_count_attempts_by_type[OBJ_TAG]);
3564                fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
3565                fprintf(stderr, "      marks:     %10" PRIuMAX " (%10" PRIuMAX " unique    )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
3566                fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
3567                fprintf(stderr, "Memory total:    %10" PRIuMAX " KiB\n", (tree_entry_allocd + fi_mem_pool.pool_alloc + alloc_count*sizeof(struct object_entry))/1024);
3568                fprintf(stderr, "       pools:    %10lu KiB\n", (unsigned long)((tree_entry_allocd + fi_mem_pool.pool_alloc) /1024));
3569                fprintf(stderr, "     objects:    %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
3570                fprintf(stderr, "---------------------------------------------------------------------\n");
3571                pack_report();
3572                fprintf(stderr, "---------------------------------------------------------------------\n");
3573                fprintf(stderr, "\n");
3574        }
3575
3576        return failure ? 1 : 0;
3577}