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