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