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