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