apply: get rid of --index-info in favor of --build-fake-ancestor
[gitweb.git] / fast-import.c
index 207acb3230f1c3a8b7843e82da282729ad4be37a..078079d404d8245d73ea8ef36d764f2bb311d0a9 100644 (file)
@@ -7,81 +7,111 @@ Format of STDIN stream:
         | new_commit
         | new_tag
         | reset_branch
+        | checkpoint
+        | progress
         ;
 
   new_blob ::= 'blob' lf
-       mark?
+    mark?
     file_content;
   file_content ::= data;
 
   new_commit ::= 'commit' sp ref_str lf
     mark?
-    ('author' sp name '<' email '>' ts tz lf)?
-    'committer' sp name '<' email '>' ts tz lf
+    ('author' sp name '<' email '>' when lf)?
+    'committer' sp name '<' email '>' when lf
     commit_msg
     ('from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf)?
     ('merge' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf)*
     file_change*
-    lf;
+    lf?;
   commit_msg ::= data;
 
-  file_change ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf
-                | 'D' sp path_str lf
-                ;
-  mode ::= '644' | '755';
+  file_change ::= file_clr
+    | file_del
+    | file_rnm
+    | file_cpy
+    | file_obm
+    | file_inm;
+  file_clr ::= 'deleteall' lf;
+  file_del ::= 'D' sp path_str lf;
+  file_rnm ::= 'R' sp path_str sp path_str lf;
+  file_cpy ::= 'C' sp path_str sp path_str lf;
+  file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf;
+  file_inm ::= 'M' sp mode sp 'inline' sp path_str lf
+    data;
 
   new_tag ::= 'tag' sp tag_str lf
     'from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf
-       'tagger' sp name '<' email '>' ts tz lf
+    'tagger' sp name '<' email '>' when lf
     tag_msg;
   tag_msg ::= data;
 
   reset_branch ::= 'reset' sp ref_str lf
     ('from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf)?
-    lf;
+    lf?;
 
   checkpoint ::= 'checkpoint' lf
-    lf;
+    lf?;
+
+  progress ::= 'progress' sp not_lf* lf
+    lf?;
 
      # note: the first idnum in a stream should be 1 and subsequent
      # idnums should not have gaps between values as this will cause
      # the stream parser to reserve space for the gapped values.  An
-        # idnum can be updated in the future to a new object by issuing
+     # idnum can be updated in the future to a new object by issuing
      # a new mark directive with the old idnum.
-        #
+     #
   mark ::= 'mark' sp idnum lf;
+  data ::= (delimited_data | exact_data)
+    lf?;
+
+    # note: delim may be any string but must not contain lf.
+    # data_line may contain any data but must not be exactly
+    # delim.
+  delimited_data ::= 'data' sp '<<' delim lf
+    (data_line lf)*
+    delim lf;
 
      # note: declen indicates the length of binary_data in bytes.
-     # declen does not include the lf preceeding or trailing the
-     # binary data.
+     # declen does not include the lf preceeding the binary data.
      #
-  data ::= 'data' sp declen lf
-    binary_data
-       lf;
+  exact_data ::= 'data' sp declen lf
+    binary_data;
 
      # note: quoted strings are C-style quoting supporting \c for
      # common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn
-        # is the signed byte value in octal.  Note that the only
+     # is the signed byte value in octal.  Note that the only
      # characters which must actually be escaped to protect the
      # stream formatting is: \, " and LF.  Otherwise these values
-        # are UTF8.
+     # are UTF8.
      #
-  ref_str     ::= ref     | '"' quoted(ref)     '"' ;
-  sha1exp_str ::= sha1exp | '"' quoted(sha1exp) '"' ;
-  tag_str     ::= tag     | '"' quoted(tag)     '"' ;
+  ref_str     ::= ref;
+  sha1exp_str ::= sha1exp;
+  tag_str     ::= tag;
   path_str    ::= path    | '"' quoted(path)    '"' ;
+  mode        ::= '100644' | '644'
+                | '100755' | '755'
+                | '120000'
+                ;
 
   declen ::= # unsigned 32 bit value, ascii base10 notation;
+  bigint ::= # unsigned integer value, ascii base10 notation;
   binary_data ::= # file content, not interpreted;
 
+  when         ::= raw_when | rfc2822_when;
+  raw_when     ::= ts sp tz;
+  rfc2822_when ::= # Valid RFC 2822 date and time;
+
   sp ::= # ASCII space character;
   lf ::= # ASCII newline (LF) character;
 
      # note: a colon (':') must precede the numerical value assigned to
-        # an idnum.  This is to distinguish it from a ref or tag name as
+     # an idnum.  This is to distinguish it from a ref or tag name as
      # GIT does not permit ':' in ref or tag strings.
-        #
-  idnum   ::= ':' declen;
+     #
+  idnum   ::= ':' bigint;
   path    ::= # GIT style file path, e.g. "a/b/c";
   ref     ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT";
   tag     ::= # GIT tag name, e.g. "FIREFOX_1_5";
@@ -89,13 +119,24 @@ Format of STDIN stream:
   hexsha1 ::= # SHA1 in hexadecimal format;
 
      # note: name and email are UTF8 strings, however name must not
-        # contain '<' or lf and email must not contain any of the
+     # contain '<' or lf and email must not contain any of the
      # following: '<', '>', lf.
-        #
+     #
   name  ::= # valid GIT author/committer name;
   email ::= # valid GIT author/committer email;
   ts    ::= # time since the epoch in seconds, ascii base10 notation;
   tz    ::= # GIT style timezone;
+
+     # note: comments may appear anywhere in the input, except
+     # within a data command.  Any form of the data command
+     # always escapes the related input from comment processing.
+     #
+     # In case it is not clear, the '#' that starts the comment
+     # must be the first character on that the line (an lf have
+     # preceeded it).
+     #
+  comment ::= '#' not_lf* lf;
+  not_lf  ::= # Any byte that is not ASCII newline (LF);
 */
 
 #include "builtin.h"
@@ -103,6 +144,7 @@ Format of STDIN stream:
 #include "object.h"
 #include "blob.h"
 #include "tree.h"
+#include "commit.h"
 #include "delta.h"
 #include "pack.h"
 #include "refs.h"
@@ -110,12 +152,15 @@ Format of STDIN stream:
 #include "strbuf.h"
 #include "quote.h"
 
+#define PACK_ID_BITS 16
+#define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
+
 struct object_entry
 {
        struct object_entry *next;
-       unsigned long offset;
+       uint32_t offset;
        unsigned type : TYPE_BITS;
-       unsigned pack_id : 16;
+       unsigned pack_id : PACK_ID_BITS;
        unsigned char sha1[20];
 };
 
@@ -129,18 +174,18 @@ struct object_entry_pool
 
 struct mark_set
 {
-       int shift;
        union {
                struct object_entry *marked[1024];
                struct mark_set *sets[1024];
        } data;
+       unsigned int shift;
 };
 
 struct last_object
 {
        void *data;
        unsigned long len;
-       unsigned long offset;
+       uint32_t offset;
        unsigned int depth;
        unsigned no_free:1;
 };
@@ -156,7 +201,7 @@ struct mem_pool
 struct atom_str
 {
        struct atom_str *next_atom;
-       int str_len;
+       unsigned short str_len;
        char str_dat[FLEX_ARRAY]; /* more */
 };
 
@@ -167,7 +212,7 @@ struct tree_entry
        struct atom_str* name;
        struct tree_entry_ms
        {
-               unsigned int mode;
+               uint16_t mode;
                unsigned char sha1[20];
        } versions[2];
 };
@@ -191,8 +236,10 @@ struct branch
        struct branch *table_next_branch;
        struct branch *active_next_branch;
        const char *name;
-       unsigned long last_commit;
        struct tree_entry branch_tree;
+       uintmax_t last_commit;
+       unsigned active : 1;
+       unsigned pack_id : PACK_ID_BITS;
        unsigned char sha1[20];
 };
 
@@ -200,6 +247,7 @@ struct tag
 {
        struct tag *next_tag;
        const char *name;
+       unsigned int pack_id;
        unsigned char sha1[20];
 };
 
@@ -215,16 +263,35 @@ struct hash_list
        unsigned char sha1[20];
 };
 
-/* Stats and misc. counters */
+typedef enum {
+       WHENSPEC_RAW = 1,
+       WHENSPEC_RFC2822,
+       WHENSPEC_NOW,
+} whenspec_type;
+
+struct recent_command
+{
+       struct recent_command *prev;
+       struct recent_command *next;
+       char *buf;
+};
+
+/* Configured limits on output */
 static unsigned long max_depth = 10;
-static unsigned long alloc_count;
+static off_t max_packsize = (1LL << 32) - 1;
+static int force_update;
+
+/* Stats and misc. counters */
+static uintmax_t alloc_count;
+static uintmax_t marks_set_count;
+static uintmax_t object_count_by_type[1 << TYPE_BITS];
+static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
+static uintmax_t delta_count_by_type[1 << TYPE_BITS];
+static unsigned long object_count;
 static unsigned long branch_count;
 static unsigned long branch_load_count;
-static unsigned long object_count;
-static unsigned long marks_set_count;
-static unsigned long object_count_by_type[1 << TYPE_BITS];
-static unsigned long duplicate_count_by_type[1 << TYPE_BITS];
-static unsigned long delta_count_by_type[1 << TYPE_BITS];
+static int failure;
+static FILE *pack_edges;
 
 /* Memory pools */
 static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
@@ -237,14 +304,10 @@ static unsigned int atom_cnt;
 static struct atom_str **atom_table;
 
 /* The .pack file being generated */
-static const char *base_name;
 static unsigned int pack_id;
-static char *idx_name;
 static struct packed_git *pack_data;
 static struct packed_git **all_packs;
-static int pack_fd;
 static unsigned long pack_size;
-static unsigned char pack_sha1[20];
 
 /* Table of objects we've written. */
 static unsigned int object_entry_alloc = 5000;
@@ -276,11 +339,122 @@ static struct tag *first_tag;
 static struct tag *last_tag;
 
 /* Input stream parsing */
+static whenspec_type whenspec = WHENSPEC_RAW;
 static struct strbuf command_buf;
-static unsigned long next_mark;
+static int unread_command_buf;
+static struct recent_command cmd_hist = {&cmd_hist, &cmd_hist, NULL};
+static struct recent_command *cmd_tail = &cmd_hist;
+static struct recent_command *rc_free;
+static unsigned int cmd_save = 100;
+static uintmax_t next_mark;
 static struct dbuf new_data;
-static FILE* branch_log;
 
+static void write_branch_report(FILE *rpt, struct branch *b)
+{
+       fprintf(rpt, "%s:\n", b->name);
+
+       fprintf(rpt, "  status      :");
+       if (b->active)
+               fputs(" active", rpt);
+       if (b->branch_tree.tree)
+               fputs(" loaded", rpt);
+       if (is_null_sha1(b->branch_tree.versions[1].sha1))
+               fputs(" dirty", rpt);
+       fputc('\n', rpt);
+
+       fprintf(rpt, "  tip commit  : %s\n", sha1_to_hex(b->sha1));
+       fprintf(rpt, "  old tree    : %s\n", sha1_to_hex(b->branch_tree.versions[0].sha1));
+       fprintf(rpt, "  cur tree    : %s\n", sha1_to_hex(b->branch_tree.versions[1].sha1));
+       fprintf(rpt, "  commit clock: %" PRIuMAX "\n", b->last_commit);
+
+       fputs("  last pack   : ", rpt);
+       if (b->pack_id < MAX_PACK_ID)
+               fprintf(rpt, "%u", b->pack_id);
+       fputc('\n', rpt);
+
+       fputc('\n', rpt);
+}
+
+static void write_crash_report(const char *err)
+{
+       char *loc = git_path("fast_import_crash_%d", getpid());
+       FILE *rpt = fopen(loc, "w");
+       struct branch *b;
+       unsigned long lu;
+       struct recent_command *rc;
+
+       if (!rpt) {
+               error("can't write crash report %s: %s", loc, strerror(errno));
+               return;
+       }
+
+       fprintf(stderr, "fast-import: dumping crash report to %s\n", loc);
+
+       fprintf(rpt, "fast-import crash report:\n");
+       fprintf(rpt, "    fast-import process: %d\n", getpid());
+       fprintf(rpt, "    parent process     : %d\n", getppid());
+       fprintf(rpt, "    at %s\n", show_date(time(NULL), 0, DATE_LOCAL));
+       fputc('\n', rpt);
+
+       fputs("fatal: ", rpt);
+       fputs(err, rpt);
+       fputc('\n', rpt);
+
+       fputc('\n', rpt);
+       fputs("Most Recent Commands Before Crash\n", rpt);
+       fputs("---------------------------------\n", rpt);
+       for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
+               if (rc->next == &cmd_hist)
+                       fputs("* ", rpt);
+               else
+                       fputs("  ", rpt);
+               fputs(rc->buf, rpt);
+               fputc('\n', rpt);
+       }
+
+       fputc('\n', rpt);
+       fputs("Active Branch LRU\n", rpt);
+       fputs("-----------------\n", rpt);
+       fprintf(rpt, "    active_branches = %lu cur, %lu max\n",
+               cur_active_branches,
+               max_active_branches);
+       fputc('\n', rpt);
+       fputs("  pos  clock name\n", rpt);
+       fputs("  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", rpt);
+       for (b = active_branches, lu = 0; b; b = b->active_next_branch)
+               fprintf(rpt, "  %2lu) %6" PRIuMAX" %s\n",
+                       ++lu, b->last_commit, b->name);
+
+       fputc('\n', rpt);
+       fputs("Inactive Branches\n", rpt);
+       fputs("-----------------\n", rpt);
+       for (lu = 0; lu < branch_table_sz; lu++) {
+               for (b = branch_table[lu]; b; b = b->table_next_branch)
+                       write_branch_report(rpt, b);
+       }
+
+       fputc('\n', rpt);
+       fputs("-------------------\n", rpt);
+       fputs("END OF CRASH REPORT\n", rpt);
+       fclose(rpt);
+}
+
+static NORETURN void die_nicely(const char *err, va_list params)
+{
+       static int zombie;
+       char message[2 * PATH_MAX];
+
+       vsnprintf(message, sizeof(message), err, params);
+       fputs("fatal: ", stderr);
+       fputs(message, stderr);
+       fputc('\n', stderr);
+
+       if (!zombie) {
+               zombie = 1;
+               write_crash_report(message);
+       }
+       exit(128);
+}
 
 static void alloc_objects(unsigned int cnt)
 {
@@ -295,7 +469,7 @@ static void alloc_objects(unsigned int cnt)
        alloc_count += cnt;
 }
 
-static struct object_entrynew_object(unsigned char *sha1)
+static struct object_entry *new_object(unsigned char *sha1)
 {
        struct object_entry *e;
 
@@ -303,12 +477,11 @@ static struct object_entry* new_object(unsigned char *sha1)
                alloc_objects(object_entry_alloc);
 
        e = blocks->next_free++;
-       e->pack_id = pack_id;
        hashcpy(e->sha1, sha1);
        return e;
 }
 
-static struct object_entryfind_object(unsigned char *sha1)
+static struct object_entry *find_object(unsigned char *sha1)
 {
        unsigned int h = sha1[0] << 8 | sha1[1];
        struct object_entry *e;
@@ -318,7 +491,7 @@ static struct object_entry* find_object(unsigned char *sha1)
        return NULL;
 }
 
-static struct object_entryinsert_object(unsigned char *sha1)
+static struct object_entry *insert_object(unsigned char *sha1)
 {
        unsigned int h = sha1[0] << 8 | sha1[1];
        struct object_entry *e = object_table[h];
@@ -349,7 +522,7 @@ static unsigned int hc_str(const char *s, size_t len)
        return r;
 }
 
-static voidpool_alloc(size_t len)
+static void *pool_alloc(size_t len)
 {
        struct mem_pool *p;
        void *r;
@@ -379,7 +552,7 @@ static void* pool_alloc(size_t len)
        return r;
 }
 
-static voidpool_calloc(size_t count, size_t size)
+static void *pool_calloc(size_t count, size_t size)
 {
        size_t len = count * size;
        void *r = pool_alloc(len);
@@ -387,7 +560,7 @@ static void* pool_calloc(size_t count, size_t size)
        return r;
 }
 
-static charpool_strdup(const char *s)
+static char *pool_strdup(const char *s)
 {
        char *r = pool_alloc(strlen(s) + 1);
        strcpy(r, s);
@@ -405,7 +578,7 @@ static void size_dbuf(struct dbuf *b, size_t maxlen)
        b->buffer = xmalloc(b->capacity);
 }
 
-static void insert_mark(unsigned long idnum, struct object_entry *oe)
+static void insert_mark(uintmax_t idnum, struct object_entry *oe)
 {
        struct mark_set *s = marks;
        while ((idnum >> s->shift) >= 1024) {
@@ -415,7 +588,7 @@ static void insert_mark(unsigned long idnum, struct object_entry *oe)
                marks = s;
        }
        while (s->shift) {
-               unsigned long i = idnum >> s->shift;
+               uintmax_t i = idnum >> s->shift;
                idnum -= i << s->shift;
                if (!s->data.sets[i]) {
                        s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
@@ -428,14 +601,14 @@ static void insert_mark(unsigned long idnum, struct object_entry *oe)
        s->data.marked[idnum] = oe;
 }
 
-static struct object_entry* find_mark(unsigned long idnum)
+static struct object_entry *find_mark(uintmax_t idnum)
 {
-       unsigned long orig_idnum = idnum;
+       uintmax_t orig_idnum = idnum;
        struct mark_set *s = marks;
        struct object_entry *oe = NULL;
        if ((idnum >> s->shift) < 1024) {
                while (s && s->shift) {
-                       unsigned long i = idnum >> s->shift;
+                       uintmax_t i = idnum >> s->shift;
                        idnum -= i << s->shift;
                        s = s->data.sets[i];
                }
@@ -443,11 +616,11 @@ static struct object_entry* find_mark(unsigned long idnum)
                        oe = s->data.marked[idnum];
        }
        if (!oe)
-               die("mark :%lu not declared", orig_idnum);
+               die("mark :%" PRIuMAX " not declared", orig_idnum);
        return oe;
 }
 
-static struct atom_str* to_atom(const char *s, size_t len)
+static struct atom_str *to_atom(const char *s, unsigned short len)
 {
        unsigned int hc = hc_str(s, len) % atom_table_sz;
        struct atom_str *c;
@@ -466,7 +639,7 @@ static struct atom_str* to_atom(const char *s, size_t len)
        return c;
 }
 
-static struct branchlookup_branch(const char *name)
+static struct branch *lookup_branch(const char *name)
 {
        unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
        struct branch *b;
@@ -477,21 +650,27 @@ static struct branch* lookup_branch(const char *name)
        return NULL;
 }
 
-static struct branchnew_branch(const char *name)
+static struct branch *new_branch(const char *name)
 {
        unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
        struct branch* b = lookup_branch(name);
 
        if (b)
                die("Invalid attempt to create duplicate branch: %s", name);
-       if (check_ref_format(name))
+       switch (check_ref_format(name)) {
+       case  0: break; /* its valid */
+       case -2: break; /* valid, but too few '/', allow anyway */
+       default:
                die("Branch name doesn't conform to GIT standards: %s", name);
+       }
 
        b = pool_calloc(1, sizeof(struct branch));
        b->name = pool_strdup(name);
        b->table_next_branch = branch_table[hc];
        b->branch_tree.versions[0].mode = S_IFDIR;
        b->branch_tree.versions[1].mode = S_IFDIR;
+       b->active = 0;
+       b->pack_id = MAX_PACK_ID;
        branch_table[hc] = b;
        branch_count++;
        return b;
@@ -503,7 +682,7 @@ static unsigned int hc_entries(unsigned int cnt)
        return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
 }
 
-static struct tree_contentnew_tree_content(unsigned int cnt)
+static struct tree_content *new_tree_content(unsigned int cnt)
 {
        struct avail_tree_content *f, *l = NULL;
        struct tree_content *t;
@@ -547,7 +726,7 @@ static void release_tree_content_recursive(struct tree_content *t)
        release_tree_content(t);
 }
 
-static struct tree_contentgrow_tree_content(
+static struct tree_content *grow_tree_content(
        struct tree_content *t,
        int amt)
 {
@@ -559,7 +738,7 @@ static struct tree_content* grow_tree_content(
        return r;
 }
 
-static struct tree_entry* new_tree_entry()
+static struct tree_entry *new_tree_entry(void)
 {
        struct tree_entry *e;
 
@@ -587,38 +766,49 @@ static void release_tree_entry(struct tree_entry *e)
        avail_tree_entry = e;
 }
 
-static void yread(int fd, void *buffer, size_t length)
+static struct tree_content *dup_tree_content(struct tree_content *s)
 {
-       ssize_t ret = 0;
-       while (ret < length) {
-               ssize_t size = xread(fd, (char *) buffer + ret, length - ret);
-               if (!size)
-                       die("Read from descriptor %i: end of stream", fd);
-               if (size < 0)
-                       die("Read from descriptor %i: %s", fd, strerror(errno));
-               ret += size;
+       struct tree_content *d;
+       struct tree_entry *a, *b;
+       unsigned int i;
+
+       if (!s)
+               return NULL;
+       d = new_tree_content(s->entry_count);
+       for (i = 0; i < s->entry_count; i++) {
+               a = s->entries[i];
+               b = new_tree_entry();
+               memcpy(b, a, sizeof(*a));
+               if (a->tree && is_null_sha1(b->versions[1].sha1))
+                       b->tree = dup_tree_content(a->tree);
+               else
+                       b->tree = NULL;
+               d->entries[i] = b;
        }
+       d->entry_count = s->entry_count;
+       d->delta_depth = s->delta_depth;
+
+       return d;
 }
 
-static void start_packfile()
+static void start_packfile(void)
 {
+       static char tmpfile[PATH_MAX];
        struct packed_git *p;
        struct pack_header hdr;
+       int pack_fd;
 
-       idx_name = xmalloc(strlen(base_name) + 11);
-       p = xcalloc(1, sizeof(*p) + strlen(base_name) + 13);
-       sprintf(p->pack_name, "%s%5.5i.pack", base_name, pack_id + 1);
-       sprintf(idx_name, "%s%5.5i.idx", base_name, pack_id + 1);
-
-       pack_fd = open(p->pack_name, O_RDWR|O_CREAT|O_EXCL, 0666);
-       if (pack_fd < 0)
-               die("Can't create %s: %s", p->pack_name, strerror(errno));
+       snprintf(tmpfile, sizeof(tmpfile),
+               "%s/tmp_pack_XXXXXX", get_object_directory());
+       pack_fd = xmkstemp(tmpfile);
+       p = xcalloc(1, sizeof(*p) + strlen(tmpfile) + 2);
+       strcpy(p->pack_name, tmpfile);
        p->pack_fd = pack_fd;
 
        hdr.hdr_signature = htonl(PACK_SIGNATURE);
        hdr.hdr_version = htonl(2);
        hdr.hdr_entries = 0;
-       write_or_die(pack_fd, &hdr, sizeof(hdr));
+       write_or_die(p->pack_fd, &hdr, sizeof(hdr));
 
        pack_data = p;
        pack_size = sizeof(hdr);
@@ -628,37 +818,6 @@ static void start_packfile()
        all_packs[pack_id] = p;
 }
 
-static void fixup_header_footer()
-{
-       SHA_CTX c;
-       char hdr[8];
-       unsigned long cnt;
-       char *buf;
-
-       if (lseek(pack_fd, 0, SEEK_SET) != 0)
-               die("Failed seeking to start: %s", strerror(errno));
-
-       SHA1_Init(&c);
-       yread(pack_fd, hdr, 8);
-       SHA1_Update(&c, hdr, 8);
-
-       cnt = htonl(object_count);
-       SHA1_Update(&c, &cnt, 4);
-       write_or_die(pack_fd, &cnt, 4);
-
-       buf = xmalloc(128 * 1024);
-       for (;;) {
-               size_t n = xread(pack_fd, buf, 128 * 1024);
-               if (n <= 0)
-                       break;
-               SHA1_Update(&c, buf, n);
-       }
-       free(buf);
-
-       SHA1_Final(pack_sha1, &c);
-       write_or_die(pack_fd, pack_sha1, sizeof(pack_sha1));
-}
-
 static int oecmp (const void *a_, const void *b_)
 {
        struct object_entry *a = *((struct object_entry**)a_);
@@ -666,22 +825,26 @@ static int oecmp (const void *a_, const void *b_)
        return hashcmp(a->sha1, b->sha1);
 }
 
-static void write_index(const char *idx_name)
+static char *create_index(void)
 {
+       static char tmpfile[PATH_MAX];
+       SHA_CTX ctx;
        struct sha1file *f;
        struct object_entry **idx, **c, **last, *e;
        struct object_entry_pool *o;
-       unsigned int array[256];
-       int i;
+       uint32_t array[256];
+       int i, idx_fd;
 
        /* Build the sorted table of object IDs. */
        idx = xmalloc(object_count * sizeof(struct object_entry*));
        c = idx;
        for (o = blocks; o; o = o->next_pool)
-               for (e = o->entries; e != o->next_free; e++)
+               for (e = o->next_free; e-- != o->entries;)
                        if (pack_id == e->pack_id)
                                *c++ = e;
        last = idx + object_count;
+       if (c != last)
+               die("internal consistency error creating the index");
        qsort(idx, object_count, sizeof(struct object_entry*), oecmp);
 
        /* Generate the fan-out array. */
@@ -697,41 +860,112 @@ static void write_index(const char *idx_name)
                c = next;
        }
 
-       f = sha1create("%s", idx_name);
+       snprintf(tmpfile, sizeof(tmpfile),
+               "%s/tmp_idx_XXXXXX", get_object_directory());
+       idx_fd = xmkstemp(tmpfile);
+       f = sha1fd(idx_fd, tmpfile);
        sha1write(f, array, 256 * sizeof(int));
+       SHA1_Init(&ctx);
        for (c = idx; c != last; c++) {
-               unsigned int offset = htonl((*c)->offset);
+               uint32_t offset = htonl((*c)->offset);
                sha1write(f, &offset, 4);
                sha1write(f, (*c)->sha1, sizeof((*c)->sha1));
+               SHA1_Update(&ctx, (*c)->sha1, 20);
        }
-       sha1write(f, pack_sha1, sizeof(pack_sha1));
+       sha1write(f, pack_data->sha1, sizeof(pack_data->sha1));
        sha1close(f, NULL, 1);
        free(idx);
+       SHA1_Final(pack_data->sha1, &ctx);
+       return tmpfile;
 }
 
-static void end_packfile()
+static char *keep_pack(char *curr_index_name)
+{
+       static char name[PATH_MAX];
+       static const char *keep_msg = "fast-import";
+       int keep_fd;
+
+       chmod(pack_data->pack_name, 0444);
+       chmod(curr_index_name, 0444);
+
+       snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
+                get_object_directory(), sha1_to_hex(pack_data->sha1));
+       keep_fd = open(name, O_RDWR|O_CREAT|O_EXCL, 0600);
+       if (keep_fd < 0)
+               die("cannot create keep file");
+       write(keep_fd, keep_msg, strlen(keep_msg));
+       close(keep_fd);
+
+       snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
+                get_object_directory(), sha1_to_hex(pack_data->sha1));
+       if (move_temp_to_file(pack_data->pack_name, name))
+               die("cannot store pack file");
+
+       snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
+                get_object_directory(), sha1_to_hex(pack_data->sha1));
+       if (move_temp_to_file(curr_index_name, name))
+               die("cannot store index file");
+       return name;
+}
+
+static void unkeep_all_packs(void)
+{
+       static char name[PATH_MAX];
+       int k;
+
+       for (k = 0; k < pack_id; k++) {
+               struct packed_git *p = all_packs[k];
+               snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
+                        get_object_directory(), sha1_to_hex(p->sha1));
+               unlink(name);
+       }
+}
+
+static void end_packfile(void)
 {
        struct packed_git *old_p = pack_data, *new_p;
 
        if (object_count) {
-               fixup_header_footer();
-               write_index(idx_name);
+               char *idx_name;
+               int i;
+               struct branch *b;
+               struct tag *t;
+
+               fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
+                                   pack_data->pack_name, object_count);
+               close(pack_data->pack_fd);
+               idx_name = keep_pack(create_index());
 
                /* Register the packfile with core git's machinary. */
                new_p = add_packed_git(idx_name, strlen(idx_name), 1);
                if (!new_p)
                        die("core git rejected index %s", idx_name);
                new_p->windows = old_p->windows;
-               new_p->pack_fd = old_p->pack_fd;
-               all_packs[pack_id++] = new_p;
+               all_packs[pack_id] = new_p;
                install_packed_git(new_p);
+
+               /* Print the boundary */
+               if (pack_edges) {
+                       fprintf(pack_edges, "%s:", new_p->pack_name);
+                       for (i = 0; i < branch_table_sz; i++) {
+                               for (b = branch_table[i]; b; b = b->table_next_branch) {
+                                       if (b->pack_id == pack_id)
+                                               fprintf(pack_edges, " %s", sha1_to_hex(b->sha1));
+                               }
+                       }
+                       for (t = first_tag; t; t = t->next_tag) {
+                               if (t->pack_id == pack_id)
+                                       fprintf(pack_edges, " %s", sha1_to_hex(t->sha1));
+                       }
+                       fputc('\n', pack_edges);
+                       fflush(pack_edges);
+               }
+
+               pack_id++;
        }
-       else {
-               close(pack_fd);
+       else
                unlink(old_p->pack_name);
-       }
        free(old_p);
-       free(idx_name);
 
        /* We can't carry a delta across packfiles. */
        free(last_blob.data);
@@ -741,6 +975,12 @@ static void end_packfile()
        last_blob.depth = 0;
 }
 
+static void cycle_packfile(void)
+{
+       end_packfile();
+       start_packfile();
+}
+
 static size_t encode_header(
        enum object_type type,
        size_t size,
@@ -770,7 +1010,7 @@ static int store_object(
        size_t datlen,
        struct last_object *last,
        unsigned char *sha1out,
-       unsigned long mark)
+       uintmax_t mark)
 {
        void *out, *delta;
        struct object_entry *e;
@@ -780,7 +1020,8 @@ static int store_object(
        SHA_CTX c;
        z_stream s;
 
-       hdrlen = sprintf((char*)hdr,"%s %lu",type_names[type],datlen) + 1;
+       hdrlen = sprintf((char*)hdr,"%s %lu", typename(type),
+               (unsigned long)datlen) + 1;
        SHA1_Init(&c);
        SHA1_Update(&c, hdr, hdrlen);
        SHA1_Update(&c, dat, datlen);
@@ -794,21 +1035,70 @@ static int store_object(
        if (e->offset) {
                duplicate_count_by_type[type]++;
                return 1;
+       } else if (find_sha1_pack(sha1, packed_git)) {
+               e->type = type;
+               e->pack_id = MAX_PACK_ID;
+               e->offset = 1; /* just not zero! */
+               duplicate_count_by_type[type]++;
+               return 1;
        }
-       e->type = type;
-       e->offset = pack_size;
-       object_count++;
-       object_count_by_type[type]++;
 
-       if (last && last->data && last->depth < max_depth)
+       if (last && last->data && last->depth < max_depth) {
                delta = diff_delta(last->data, last->len,
                        dat, datlen,
                        &deltalen, 0);
-       else
-               delta = 0;
+               if (delta && deltalen >= datlen) {
+                       free(delta);
+                       delta = NULL;
+               }
+       } else
+               delta = NULL;
 
        memset(&s, 0, sizeof(s));
        deflateInit(&s, zlib_compression_level);
+       if (delta) {
+               s.next_in = delta;
+               s.avail_in = deltalen;
+       } else {
+               s.next_in = dat;
+               s.avail_in = datlen;
+       }
+       s.avail_out = deflateBound(&s, s.avail_in);
+       s.next_out = out = xmalloc(s.avail_out);
+       while (deflate(&s, Z_FINISH) == Z_OK)
+               /* nothing */;
+       deflateEnd(&s);
+
+       /* Determine if we should auto-checkpoint. */
+       if ((pack_size + 60 + s.total_out) > max_packsize
+               || (pack_size + 60 + s.total_out) < pack_size) {
+
+               /* This new object needs to *not* have the current pack_id. */
+               e->pack_id = pack_id + 1;
+               cycle_packfile();
+
+               /* We cannot carry a delta into the new pack. */
+               if (delta) {
+                       free(delta);
+                       delta = NULL;
+
+                       memset(&s, 0, sizeof(s));
+                       deflateInit(&s, zlib_compression_level);
+                       s.next_in = dat;
+                       s.avail_in = datlen;
+                       s.avail_out = deflateBound(&s, s.avail_in);
+                       s.next_out = out = xrealloc(out, s.avail_out);
+                       while (deflate(&s, Z_FINISH) == Z_OK)
+                               /* nothing */;
+                       deflateEnd(&s);
+               }
+       }
+
+       e->type = type;
+       e->pack_id = pack_id;
+       e->offset = pack_size;
+       object_count++;
+       object_count_by_type[type]++;
 
        if (delta) {
                unsigned long ofs = e->offset - last->offset;
@@ -816,42 +1106,31 @@ static int store_object(
 
                delta_count_by_type[type]++;
                last->depth++;
-               s.next_in = delta;
-               s.avail_in = deltalen;
 
                hdrlen = encode_header(OBJ_OFS_DELTA, deltalen, hdr);
-               write_or_die(pack_fd, hdr, hdrlen);
+               write_or_die(pack_data->pack_fd, hdr, hdrlen);
                pack_size += hdrlen;
 
                hdr[pos] = ofs & 127;
                while (ofs >>= 7)
                        hdr[--pos] = 128 | (--ofs & 127);
-               write_or_die(pack_fd, hdr + pos, sizeof(hdr) - pos);
+               write_or_die(pack_data->pack_fd, hdr + pos, sizeof(hdr) - pos);
                pack_size += sizeof(hdr) - pos;
        } else {
                if (last)
                        last->depth = 0;
-               s.next_in = dat;
-               s.avail_in = datlen;
                hdrlen = encode_header(type, datlen, hdr);
-               write_or_die(pack_fd, hdr, hdrlen);
+               write_or_die(pack_data->pack_fd, hdr, hdrlen);
                pack_size += hdrlen;
        }
 
-       s.avail_out = deflateBound(&s, s.avail_in);
-       s.next_out = out = xmalloc(s.avail_out);
-       while (deflate(&s, Z_FINISH) == Z_OK)
-               /* nothing */;
-       deflateEnd(&s);
-
-       write_or_die(pack_fd, out, s.total_out);
+       write_or_die(pack_data->pack_fd, out, s.total_out);
        pack_size += s.total_out;
 
        free(out);
-       if (delta)
-               free(delta);
+       free(delta);
        if (last) {
-               if (last->data && !last->no_free)
+               if (!last->no_free)
                        free(last->data);
                last->data = dat;
                last->offset = e->offset;
@@ -864,17 +1143,17 @@ static void *gfi_unpack_entry(
        struct object_entry *oe,
        unsigned long *sizep)
 {
-       static char type[20];
+       enum object_type type;
        struct packed_git *p = all_packs[oe->pack_id];
        if (p == pack_data)
                p->pack_size = pack_size + 20;
-       return unpack_entry(p, oe->offset, type, sizep);
+       return unpack_entry(p, oe->offset, &type, sizep);
 }
 
-static const char *get_mode(const char *str, unsigned int *modep)
+static const char *get_mode(const char *str, uint16_t *modep)
 {
        unsigned char c;
-       unsigned int mode = 0;
+       uint16_t mode = 0;
 
        while ((c = *str++) != ' ') {
                if (c < '0' || c > '7')
@@ -899,15 +1178,15 @@ static void load_tree(struct tree_entry *root)
                return;
 
        myoe = find_object(sha1);
-       if (myoe) {
+       if (myoe && myoe->pack_id != MAX_PACK_ID) {
                if (myoe->type != OBJ_TREE)
                        die("Not a tree: %s", sha1_to_hex(sha1));
                t->delta_depth = 0;
                buf = gfi_unpack_entry(myoe, &size);
        } else {
-               char type[20];
-               buf = read_sha1_file(sha1, type, &size);
-               if (!buf || strcmp(type, tree_type))
+               enum object_type type;
+               buf = read_sha1_file(sha1, &type, &size);
+               if (!buf || type != OBJ_TREE)
                        die("Can't load tree %s", sha1_to_hex(sha1));
        }
 
@@ -916,7 +1195,7 @@ static void load_tree(struct tree_entry *root)
                struct tree_entry *e = new_tree_entry();
 
                if (t->entry_count == t->entry_capacity)
-                       root->tree = t = grow_tree_content(t, 8);
+                       root->tree = t = grow_tree_content(t, t->entry_count);
                t->entries[t->entry_count++] = e;
 
                e->tree = NULL;
@@ -976,7 +1255,7 @@ static void mktree(struct tree_content *t,
                struct tree_entry *e = t->entries[i];
                if (!e->versions[v].mode)
                        continue;
-               c += sprintf(c, "%o", e->versions[v].mode);
+               c += sprintf(c, "%o", (unsigned int)e->versions[v].mode);
                *c++ = ' ';
                strcpy(c, e->name->str_dat);
                c += e->name->str_len + 1;
@@ -1008,6 +1287,7 @@ static void store_tree(struct tree_entry *root)
                || le->pack_id != pack_id) {
                lo.data = NULL;
                lo.depth = 0;
+               lo.no_free = 0;
        } else {
                mktree(t, 0, &lo.len, &old_tree);
                lo.data = old_tree.buffer;
@@ -1039,7 +1319,8 @@ static int tree_content_set(
        struct tree_entry *root,
        const char *p,
        const unsigned char *sha1,
-       const unsigned int mode)
+       const uint16_t mode,
+       struct tree_content *subtree)
 {
        struct tree_content *t = root->tree;
        const char *slash1;
@@ -1051,20 +1332,24 @@ static int tree_content_set(
                n = slash1 - p;
        else
                n = strlen(p);
+       if (!n)
+               die("Empty path component found in input");
+       if (!slash1 && !S_ISDIR(mode) && subtree)
+               die("Non-directories cannot have subtrees");
 
        for (i = 0; i < t->entry_count; i++) {
                e = t->entries[i];
                if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
                        if (!slash1) {
-                               if (e->versions[1].mode == mode
+                               if (!S_ISDIR(mode)
+                                               && e->versions[1].mode == mode
                                                && !hashcmp(e->versions[1].sha1, sha1))
                                        return 0;
                                e->versions[1].mode = mode;
                                hashcpy(e->versions[1].sha1, sha1);
-                               if (e->tree) {
+                               if (e->tree)
                                        release_tree_content_recursive(e->tree);
-                                       e->tree = NULL;
-                               }
+                               e->tree = subtree;
                                hashclr(root->versions[1].sha1);
                                return 1;
                        }
@@ -1074,7 +1359,7 @@ static int tree_content_set(
                        }
                        if (!e->tree)
                                load_tree(e);
-                       if (tree_content_set(e, slash1 + 1, sha1, mode)) {
+                       if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) {
                                hashclr(root->versions[1].sha1);
                                return 1;
                        }
@@ -1083,7 +1368,7 @@ static int tree_content_set(
        }
 
        if (t->entry_count == t->entry_capacity)
-               root->tree = t = grow_tree_content(t, 8);
+               root->tree = t = grow_tree_content(t, t->entry_count);
        e = new_tree_entry();
        e->name = to_atom(p, n);
        e->versions[0].mode = 0;
@@ -1092,9 +1377,9 @@ static int tree_content_set(
        if (slash1) {
                e->tree = new_tree_content(8);
                e->versions[1].mode = S_IFDIR;
-               tree_content_set(e, slash1 + 1, sha1, mode);
+               tree_content_set(e, slash1 + 1, sha1, mode, subtree);
        } else {
-               e->tree = NULL;
+               e->tree = subtree;
                e->versions[1].mode = mode;
                hashcpy(e->versions[1].sha1, sha1);
        }
@@ -1102,7 +1387,10 @@ static int tree_content_set(
        return 1;
 }
 
-static int tree_content_remove(struct tree_entry *root, const char *p)
+static int tree_content_remove(
+       struct tree_entry *root,
+       const char *p,
+       struct tree_entry *backup_leaf)
 {
        struct tree_content *t = root->tree;
        const char *slash1;
@@ -1122,13 +1410,14 @@ static int tree_content_remove(struct tree_entry *root, const char *p)
                                goto del_entry;
                        if (!e->tree)
                                load_tree(e);
-                       if (tree_content_remove(e, slash1 + 1)) {
+                       if (tree_content_remove(e, slash1 + 1, backup_leaf)) {
                                for (n = 0; n < e->tree->entry_count; n++) {
                                        if (e->tree->entries[n]->versions[1].mode) {
                                                hashclr(root->versions[1].sha1);
                                                return 1;
                                        }
                                }
+                               backup_leaf = NULL;
                                goto del_entry;
                        }
                        return 0;
@@ -1137,52 +1426,119 @@ static int tree_content_remove(struct tree_entry *root, const char *p)
        return 0;
 
 del_entry:
-       if (e->tree) {
+       if (backup_leaf)
+               memcpy(backup_leaf, e, sizeof(*backup_leaf));
+       else if (e->tree)
                release_tree_content_recursive(e->tree);
-               e->tree = NULL;
-       }
+       e->tree = NULL;
        e->versions[1].mode = 0;
        hashclr(e->versions[1].sha1);
        hashclr(root->versions[1].sha1);
        return 1;
 }
 
-static void dump_branches()
+static int tree_content_get(
+       struct tree_entry *root,
+       const char *p,
+       struct tree_entry *leaf)
+{
+       struct tree_content *t = root->tree;
+       const char *slash1;
+       unsigned int i, n;
+       struct tree_entry *e;
+
+       slash1 = strchr(p, '/');
+       if (slash1)
+               n = slash1 - p;
+       else
+               n = strlen(p);
+
+       for (i = 0; i < t->entry_count; i++) {
+               e = t->entries[i];
+               if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
+                       if (!slash1) {
+                               memcpy(leaf, e, sizeof(*leaf));
+                               if (e->tree && is_null_sha1(e->versions[1].sha1))
+                                       leaf->tree = dup_tree_content(e->tree);
+                               else
+                                       leaf->tree = NULL;
+                               return 1;
+                       }
+                       if (!S_ISDIR(e->versions[1].mode))
+                               return 0;
+                       if (!e->tree)
+                               load_tree(e);
+                       return tree_content_get(e, slash1 + 1, leaf);
+               }
+       }
+       return 0;
+}
+
+static int update_branch(struct branch *b)
 {
        static const char *msg = "fast-import";
+       struct ref_lock *lock;
+       unsigned char old_sha1[20];
+
+       if (read_ref(b->name, old_sha1))
+               hashclr(old_sha1);
+       lock = lock_any_ref_for_update(b->name, old_sha1, 0);
+       if (!lock)
+               return error("Unable to lock %s", b->name);
+       if (!force_update && !is_null_sha1(old_sha1)) {
+               struct commit *old_cmit, *new_cmit;
+
+               old_cmit = lookup_commit_reference_gently(old_sha1, 0);
+               new_cmit = lookup_commit_reference_gently(b->sha1, 0);
+               if (!old_cmit || !new_cmit) {
+                       unlock_ref(lock);
+                       return error("Branch %s is missing commits.", b->name);
+               }
+
+               if (!in_merge_bases(old_cmit, &new_cmit, 1)) {
+                       unlock_ref(lock);
+                       warning("Not updating %s"
+                               " (new tip %s does not contain %s)",
+                               b->name, sha1_to_hex(b->sha1), sha1_to_hex(old_sha1));
+                       return -1;
+               }
+       }
+       if (write_ref_sha1(lock, b->sha1, msg) < 0)
+               return error("Unable to update %s", b->name);
+       return 0;
+}
+
+static void dump_branches(void)
+{
        unsigned int i;
        struct branch *b;
-       struct ref_lock *lock;
 
        for (i = 0; i < branch_table_sz; i++) {
-               for (b = branch_table[i]; b; b = b->table_next_branch) {
-                       lock = lock_any_ref_for_update(b->name, NULL);
-                       if (!lock || write_ref_sha1(lock, b->sha1, msg) < 0)
-                               die("Can't write %s", b->name);
-               }
+               for (b = branch_table[i]; b; b = b->table_next_branch)
+                       failure |= update_branch(b);
        }
 }
 
-static void dump_tags()
+static void dump_tags(void)
 {
        static const char *msg = "fast-import";
        struct tag *t;
        struct ref_lock *lock;
-       char path[PATH_MAX];
+       char ref_name[PATH_MAX];
 
        for (t = first_tag; t; t = t->next_tag) {
-               sprintf(path, "refs/tags/%s", t->name);
-               lock = lock_any_ref_for_update(path, NULL);
+               sprintf(ref_name, "tags/%s", t->name);
+               lock = lock_ref_sha1(ref_name, NULL);
                if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
-                       die("Can't write %s", path);
+                       failure |= error("Unable to update %s", ref_name);
        }
 }
 
 static void dump_marks_helper(FILE *f,
-       unsigned long base,
+       uintmax_t base,
        struct mark_set *m)
 {
-       int k;
+       uintmax_t k;
        if (m->shift) {
                for (k = 0; k < 1024; k++) {
                        if (m->data.sets[k])
@@ -1192,64 +1548,201 @@ static void dump_marks_helper(FILE *f,
        } else {
                for (k = 0; k < 1024; k++) {
                        if (m->data.marked[k])
-                               fprintf(f, ":%lu %s\n", base + k,
+                               fprintf(f, ":%" PRIuMAX " %s\n", base + k,
                                        sha1_to_hex(m->data.marked[k]->sha1));
                }
        }
 }
 
-static void dump_marks()
+static void dump_marks(void)
 {
-       if (mark_file)
-       {
-               FILE *f = fopen(mark_file, "w");
-               dump_marks_helper(f, 0, marks);
-               fclose(f);
+       static struct lock_file mark_lock;
+       int mark_fd;
+       FILE *f;
+
+       if (!mark_file)
+               return;
+
+       mark_fd = hold_lock_file_for_update(&mark_lock, mark_file, 0);
+       if (mark_fd < 0) {
+               failure |= error("Unable to write marks file %s: %s",
+                       mark_file, strerror(errno));
+               return;
+       }
+
+       f = fdopen(mark_fd, "w");
+       if (!f) {
+               rollback_lock_file(&mark_lock);
+               failure |= error("Unable to write marks file %s: %s",
+                       mark_file, strerror(errno));
+               return;
        }
+
+       dump_marks_helper(f, 0, marks);
+       fclose(f);
+       if (commit_lock_file(&mark_lock))
+               failure |= error("Unable to write marks file %s: %s",
+                       mark_file, strerror(errno));
 }
 
-static void read_next_command()
+static void read_next_command(void)
 {
-       read_line(&command_buf, stdin, '\n');
+       do {
+               if (unread_command_buf) {
+                       unread_command_buf = 0;
+                       if (command_buf.eof)
+                               return;
+               } else {
+                       struct recent_command *rc;
+
+                       command_buf.buf = NULL;
+                       read_line(&command_buf, stdin, '\n');
+                       if (command_buf.eof)
+                               return;
+
+                       rc = rc_free;
+                       if (rc)
+                               rc_free = rc->next;
+                       else {
+                               rc = cmd_hist.next;
+                               cmd_hist.next = rc->next;
+                               cmd_hist.next->prev = &cmd_hist;
+                               free(rc->buf);
+                       }
+
+                       rc->buf = command_buf.buf;
+                       rc->prev = cmd_tail;
+                       rc->next = cmd_hist.prev;
+                       rc->prev->next = rc;
+                       cmd_tail = rc;
+               }
+       } while (command_buf.buf[0] == '#');
 }
 
-static void cmd_mark()
+static void skip_optional_lf(void)
 {
-       if (!strncmp("mark :", command_buf.buf, 6)) {
-               next_mark = strtoul(command_buf.buf + 6, NULL, 10);
+       int term_char = fgetc(stdin);
+       if (term_char != '\n' && term_char != EOF)
+               ungetc(term_char, stdin);
+}
+
+static void cmd_mark(void)
+{
+       if (!prefixcmp(command_buf.buf, "mark :")) {
+               next_mark = strtoumax(command_buf.buf + 6, NULL, 10);
                read_next_command();
        }
        else
                next_mark = 0;
 }
 
-static voidcmd_data (size_t *size)
+static void *cmd_data (size_t *size)
 {
-       size_t n = 0;
-       void *buffer;
        size_t length;
+       char *buffer;
 
-       if (strncmp("data ", command_buf.buf, 5))
+       if (prefixcmp(command_buf.buf, "data "))
                die("Expected 'data n' command, found: %s", command_buf.buf);
 
-       length = strtoul(command_buf.buf + 5, NULL, 10);
-       buffer = xmalloc(length);
-
-       while (n < length) {
-               size_t s = fread((char*)buffer + n, 1, length - n, stdin);
-               if (!s && feof(stdin))
-                       die("EOF in data (%lu bytes remaining)", length - n);
-               n += s;
+       if (!prefixcmp(command_buf.buf + 5, "<<")) {
+               char *term = xstrdup(command_buf.buf + 5 + 2);
+               size_t sz = 8192, term_len = command_buf.len - 5 - 2;
+               length = 0;
+               buffer = xmalloc(sz);
+               command_buf.buf = NULL;
+               for (;;) {
+                       read_line(&command_buf, stdin, '\n');
+                       if (command_buf.eof)
+                               die("EOF in data (terminator '%s' not found)", term);
+                       if (term_len == command_buf.len
+                               && !strcmp(term, command_buf.buf))
+                               break;
+                       ALLOC_GROW(buffer, length + command_buf.len, sz);
+                       memcpy(buffer + length,
+                               command_buf.buf,
+                               command_buf.len - 1);
+                       length += command_buf.len - 1;
+                       buffer[length++] = '\n';
+               }
+               free(term);
+       }
+       else {
+               size_t n = 0;
+               length = strtoul(command_buf.buf + 5, NULL, 10);
+               buffer = xmalloc(length);
+               while (n < length) {
+                       size_t s = fread(buffer + n, 1, length - n, stdin);
+                       if (!s && feof(stdin))
+                               die("EOF in data (%lu bytes remaining)",
+                                       (unsigned long)(length - n));
+                       n += s;
+               }
        }
 
-       if (fgetc(stdin) != '\n')
-               die("An lf did not trail the binary data as expected.");
-
+       skip_optional_lf();
        *size = length;
        return buffer;
 }
 
-static void cmd_new_blob()
+static int validate_raw_date(const char *src, char *result, int maxlen)
+{
+       const char *orig_src = src;
+       char *endp, sign;
+
+       strtoul(src, &endp, 10);
+       if (endp == src || *endp != ' ')
+               return -1;
+
+       src = endp + 1;
+       if (*src != '-' && *src != '+')
+               return -1;
+       sign = *src;
+
+       strtoul(src + 1, &endp, 10);
+       if (endp == src || *endp || (endp - orig_src) >= maxlen)
+               return -1;
+
+       strcpy(result, orig_src);
+       return 0;
+}
+
+static char *parse_ident(const char *buf)
+{
+       const char *gt;
+       size_t name_len;
+       char *ident;
+
+       gt = strrchr(buf, '>');
+       if (!gt)
+               die("Missing > in ident string: %s", buf);
+       gt++;
+       if (*gt != ' ')
+               die("Missing space after > in ident string: %s", buf);
+       gt++;
+       name_len = gt - buf;
+       ident = xmalloc(name_len + 24);
+       strncpy(ident, buf, name_len);
+
+       switch (whenspec) {
+       case WHENSPEC_RAW:
+               if (validate_raw_date(gt, ident + name_len, 24) < 0)
+                       die("Invalid raw date \"%s\" in ident: %s", gt, buf);
+               break;
+       case WHENSPEC_RFC2822:
+               if (parse_date(gt, ident + name_len, 24) < 0)
+                       die("Invalid rfc2822 date \"%s\" in ident: %s", gt, buf);
+               break;
+       case WHENSPEC_NOW:
+               if (strcmp("now", gt))
+                       die("Date in ident must be 'now': %s", buf);
+               datestamp(ident + name_len, 24);
+               break;
+       }
+
+       return ident;
+}
+
+static void cmd_new_blob(void)
 {
        size_t l;
        void *d;
@@ -1262,11 +1755,11 @@ static void cmd_new_blob()
                free(d);
 }
 
-static void unload_one_branch()
+static void unload_one_branch(void)
 {
        while (cur_active_branches
                && cur_active_branches >= max_active_branches) {
-               unsigned long min_commit = ULONG_MAX;
+               uintmax_t min_commit = ULONG_MAX;
                struct branch *e, *l = NULL, *p = NULL;
 
                for (e = active_branches; e; e = e->active_next_branch) {
@@ -1284,6 +1777,7 @@ static void unload_one_branch()
                        e = active_branches;
                        active_branches = e->active_next_branch;
                }
+               e->active = 0;
                e->active_next_branch = NULL;
                if (e->branch_tree.tree) {
                        release_tree_content_recursive(e->branch_tree.tree);
@@ -1296,10 +1790,13 @@ static void unload_one_branch()
 static void load_branch(struct branch *b)
 {
        load_tree(&b->branch_tree);
-       b->active_next_branch = active_branches;
-       active_branches = b;
-       cur_active_branches++;
-       branch_load_count++;
+       if (!b->active) {
+               b->active = 1;
+               b->active_next_branch = active_branches;
+               active_branches = b;
+               cur_active_branches++;
+               branch_load_count++;
+       }
 }
 
 static void file_change_m(struct branch *b)
@@ -1307,10 +1804,9 @@ static void file_change_m(struct branch *b)
        const char *p = command_buf.buf + 2;
        char *p_uq;
        const char *endp;
-       struct object_entry *oe;
+       struct object_entry *oe = oe;
        unsigned char sha1[20];
-       unsigned int mode;
-       char type[20];
+       uint16_t mode, inline_data = 0;
 
        p = get_mode(p, &mode);
        if (!p)
@@ -1329,9 +1825,12 @@ static void file_change_m(struct branch *b)
 
        if (*p == ':') {
                char *x;
-               oe = find_mark(strtoul(p + 1, &x, 10));
+               oe = find_mark(strtoumax(p + 1, &x, 10));
                hashcpy(sha1, oe->sha1);
                p = x;
+       } else if (!prefixcmp(p, "inline")) {
+               inline_data = 1;
+               p += 6;
        } else {
                if (get_sha1_hex(p, sha1))
                        die("Invalid SHA1: %s", command_buf.buf);
@@ -1348,22 +1847,30 @@ static void file_change_m(struct branch *b)
                p = p_uq;
        }
 
-       if (oe) {
+       if (inline_data) {
+               size_t l;
+               void *d;
+               if (!p_uq)
+                       p = p_uq = xstrdup(p);
+               read_next_command();
+               d = cmd_data(&l);
+               if (store_object(OBJ_BLOB, d, l, &last_blob, sha1, 0))
+                       free(d);
+       } else if (oe) {
                if (oe->type != OBJ_BLOB)
                        die("Not a blob (actually a %s): %s",
-                               command_buf.buf, type_names[oe->type]);
+                               command_buf.buf, typename(oe->type));
        } else {
-               if (sha1_object_info(sha1, type, NULL))
+               enum object_type type = sha1_object_info(sha1, NULL);
+               if (type < 0)
                        die("Blob not found: %s", command_buf.buf);
-               if (strcmp(blob_type, type))
+               if (type != OBJ_BLOB)
                        die("Not a blob (actually a %s): %s",
-                               command_buf.buf, type);
+                           typename(type), command_buf.buf);
        }
 
-       tree_content_set(&b->branch_tree, p, sha1, S_IFREG | mode);
-
-       if (p_uq)
-               free(p_uq);
+       tree_content_set(&b->branch_tree, p, sha1, S_IFREG | mode, NULL);
+       free(p_uq);
 }
 
 static void file_change_d(struct branch *b)
@@ -1378,31 +1885,110 @@ static void file_change_d(struct branch *b)
                        die("Garbage after path in: %s", command_buf.buf);
                p = p_uq;
        }
-       tree_content_remove(&b->branch_tree, p);
-       if (p_uq)
-               free(p_uq);
+       tree_content_remove(&b->branch_tree, p, NULL);
+       free(p_uq);
 }
 
-static void cmd_from(struct branch *b)
+static void file_change_cr(struct branch *b, int rename)
 {
-       const char *from, *endp;
-       char *str_uq;
-       struct branch *s;
+       const char *s, *d;
+       char *s_uq, *d_uq;
+       const char *endp;
+       struct tree_entry leaf;
 
-       if (strncmp("from ", command_buf.buf, 5))
-               return;
+       s = command_buf.buf + 2;
+       s_uq = unquote_c_style(s, &endp);
+       if (s_uq) {
+               if (*endp != ' ')
+                       die("Missing space after source: %s", command_buf.buf);
+       }
+       else {
+               endp = strchr(s, ' ');
+               if (!endp)
+                       die("Missing space after source: %s", command_buf.buf);
+               s_uq = xmalloc(endp - s + 1);
+               memcpy(s_uq, s, endp - s);
+               s_uq[endp - s] = 0;
+       }
+       s = s_uq;
 
-       if (b->last_commit)
-               die("Can't reinitailize branch %s", b->name);
+       endp++;
+       if (!*endp)
+               die("Missing dest: %s", command_buf.buf);
 
-       from = strchr(command_buf.buf, ' ') + 1;
-       str_uq = unquote_c_style(from, &endp);
-       if (str_uq) {
+       d = endp;
+       d_uq = unquote_c_style(d, &endp);
+       if (d_uq) {
                if (*endp)
-                       die("Garbage after string in: %s", command_buf.buf);
-               from = str_uq;
+                       die("Garbage after dest in: %s", command_buf.buf);
+               d = d_uq;
+       }
+
+       memset(&leaf, 0, sizeof(leaf));
+       if (rename)
+               tree_content_remove(&b->branch_tree, s, &leaf);
+       else
+               tree_content_get(&b->branch_tree, s, &leaf);
+       if (!leaf.versions[1].mode)
+               die("Path %s not in branch", s);
+       tree_content_set(&b->branch_tree, d,
+               leaf.versions[1].sha1,
+               leaf.versions[1].mode,
+               leaf.tree);
+
+       free(s_uq);
+       free(d_uq);
+}
+
+static void file_change_deleteall(struct branch *b)
+{
+       release_tree_content_recursive(b->branch_tree.tree);
+       hashclr(b->branch_tree.versions[0].sha1);
+       hashclr(b->branch_tree.versions[1].sha1);
+       load_tree(&b->branch_tree);
+}
+
+static void cmd_from_commit(struct branch *b, char *buf, unsigned long size)
+{
+       if (!buf || size < 46)
+               die("Not a valid commit: %s", sha1_to_hex(b->sha1));
+       if (memcmp("tree ", buf, 5)
+               || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
+               die("The commit %s is corrupt", sha1_to_hex(b->sha1));
+       hashcpy(b->branch_tree.versions[0].sha1,
+               b->branch_tree.versions[1].sha1);
+}
+
+static void cmd_from_existing(struct branch *b)
+{
+       if (is_null_sha1(b->sha1)) {
+               hashclr(b->branch_tree.versions[0].sha1);
+               hashclr(b->branch_tree.versions[1].sha1);
+       } else {
+               unsigned long size;
+               char *buf;
+
+               buf = read_object_with_reference(b->sha1,
+                       commit_type, &size, b->sha1);
+               cmd_from_commit(b, buf, size);
+               free(buf);
+       }
+}
+
+static int cmd_from(struct branch *b)
+{
+       const char *from;
+       struct branch *s;
+
+       if (prefixcmp(command_buf.buf, "from "))
+               return 0;
+
+       if (b->branch_tree.tree) {
+               release_tree_content_recursive(b->branch_tree.tree);
+               b->branch_tree.tree = NULL;
        }
 
+       from = strchr(command_buf.buf, ' ') + 1;
        s = lookup_branch(from);
        if (b == s)
                die("Can't create a branch from itself: %s", b->name);
@@ -1412,75 +1998,54 @@ static void cmd_from(struct branch *b)
                hashcpy(b->branch_tree.versions[0].sha1, t);
                hashcpy(b->branch_tree.versions[1].sha1, t);
        } else if (*from == ':') {
-               unsigned long idnum = strtoul(from + 1, NULL, 10);
+               uintmax_t idnum = strtoumax(from + 1, NULL, 10);
                struct object_entry *oe = find_mark(idnum);
-               unsigned long size;
-               char *buf;
                if (oe->type != OBJ_COMMIT)
-                       die("Mark :%lu not a commit", idnum);
+                       die("Mark :%" PRIuMAX " not a commit", idnum);
                hashcpy(b->sha1, oe->sha1);
-               buf = gfi_unpack_entry(oe, &size);
-               if (!buf || size < 46)
-                       die("Not a valid commit: %s", from);
-               if (memcmp("tree ", buf, 5)
-                       || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
-                       die("The commit %s is corrupt", sha1_to_hex(b->sha1));
-               free(buf);
-               hashcpy(b->branch_tree.versions[0].sha1,
-                       b->branch_tree.versions[1].sha1);
-       } else if (!get_sha1(from, b->sha1)) {
-               if (is_null_sha1(b->sha1)) {
-                       hashclr(b->branch_tree.versions[0].sha1);
-                       hashclr(b->branch_tree.versions[1].sha1);
-               } else {
+               if (oe->pack_id != MAX_PACK_ID) {
                        unsigned long size;
-                       char *buf;
-
-                       buf = read_object_with_reference(b->sha1,
-                               type_names[OBJ_COMMIT], &size, b->sha1);
-                       if (!buf || size < 46)
-                               die("Not a valid commit: %s", from);
-                       if (memcmp("tree ", buf, 5)
-                               || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
-                               die("The commit %s is corrupt", sha1_to_hex(b->sha1));
+                       char *buf = gfi_unpack_entry(oe, &size);
+                       cmd_from_commit(b, buf, size);
                        free(buf);
-                       hashcpy(b->branch_tree.versions[0].sha1,
-                               b->branch_tree.versions[1].sha1);
-               }
-       } else
+               } else
+                       cmd_from_existing(b);
+       } else if (!get_sha1(from, b->sha1))
+               cmd_from_existing(b);
+       else
                die("Invalid ref name or SHA1 expression: %s", from);
 
        read_next_command();
+       return 1;
 }
 
-static struct hash_listcmd_merge(unsigned int *count)
+static struct hash_list *cmd_merge(unsigned int *count)
 {
-       struct hash_list *list = NULL, *n, *e;
-       const char *from, *endp;
-       char *str_uq;
+       struct hash_list *list = NULL, *n, *e = e;
+       const char *from;
        struct branch *s;
 
        *count = 0;
-       while (!strncmp("merge ", command_buf.buf, 6)) {
+       while (!prefixcmp(command_buf.buf, "merge ")) {
                from = strchr(command_buf.buf, ' ') + 1;
-               str_uq = unquote_c_style(from, &endp);
-               if (str_uq) {
-                       if (*endp)
-                               die("Garbage after string in: %s", command_buf.buf);
-                       from = str_uq;
-               }
-
                n = xmalloc(sizeof(*n));
                s = lookup_branch(from);
                if (s)
                        hashcpy(n->sha1, s->sha1);
                else if (*from == ':') {
-                       unsigned long idnum = strtoul(from + 1, NULL, 10);
+                       uintmax_t idnum = strtoumax(from + 1, NULL, 10);
                        struct object_entry *oe = find_mark(idnum);
                        if (oe->type != OBJ_COMMIT)
-                               die("Mark :%lu not a commit", idnum);
+                               die("Mark :%" PRIuMAX " not a commit", idnum);
                        hashcpy(n->sha1, oe->sha1);
-               } else if (get_sha1(from, n->sha1))
+               } else if (!get_sha1(from, n->sha1)) {
+                       unsigned long size;
+                       char *buf = read_object_with_reference(n->sha1,
+                               commit_type, &size, n->sha1);
+                       if (!buf || size < 46)
+                               die("Not a valid commit: %s", from);
+                       free(buf);
+               } else
                        die("Invalid ref name or SHA1 expression: %s", from);
 
                n->next = NULL;
@@ -1489,19 +2054,17 @@ static struct hash_list* cmd_merge(unsigned int *count)
                else
                        list = n;
                e = n;
-               *count++;
+               (*count)++;
                read_next_command();
        }
        return list;
 }
 
-static void cmd_new_commit()
+static void cmd_new_commit(void)
 {
        struct branch *b;
        void *msg;
        size_t msglen;
-       char *str_uq;
-       const char *endp;
        char *sp;
        char *author = NULL;
        char *committer = NULL;
@@ -1510,26 +2073,18 @@ static void cmd_new_commit()
 
        /* Obtain the branch name from the rest of our command */
        sp = strchr(command_buf.buf, ' ') + 1;
-       str_uq = unquote_c_style(sp, &endp);
-       if (str_uq) {
-               if (*endp)
-                       die("Garbage after ref in: %s", command_buf.buf);
-               sp = str_uq;
-       }
        b = lookup_branch(sp);
        if (!b)
                b = new_branch(sp);
-       if (str_uq)
-               free(str_uq);
 
        read_next_command();
        cmd_mark();
-       if (!strncmp("author ", command_buf.buf, 7)) {
-               author = strdup(command_buf.buf);
+       if (!prefixcmp(command_buf.buf, "author ")) {
+               author = parse_ident(command_buf.buf + 7);
                read_next_command();
        }
-       if (!strncmp("committer ", command_buf.buf, 10)) {
-               committer = strdup(command_buf.buf);
+       if (!prefixcmp(command_buf.buf, "committer ")) {
+               committer = parse_ident(command_buf.buf + 10);
                read_next_command();
        }
        if (!committer)
@@ -1546,15 +2101,21 @@ static void cmd_new_commit()
        }
 
        /* file_change* */
-       for (;;) {
-               if (1 == command_buf.len)
-                       break;
-               else if (!strncmp("M ", command_buf.buf, 2))
+       while (!command_buf.eof && command_buf.len > 1) {
+               if (!prefixcmp(command_buf.buf, "M "))
                        file_change_m(b);
-               else if (!strncmp("D ", command_buf.buf, 2))
+               else if (!prefixcmp(command_buf.buf, "D "))
                        file_change_d(b);
-               else
-                       die("Unsupported file_change: %s", command_buf.buf);
+               else if (!prefixcmp(command_buf.buf, "R "))
+                       file_change_cr(b, 1);
+               else if (!prefixcmp(command_buf.buf, "C "))
+                       file_change_cr(b, 0);
+               else if (!strcmp("deleteall", command_buf.buf))
+                       file_change_deleteall(b);
+               else {
+                       unread_command_buf = 1;
+                       break;
+               }
                read_next_command();
        }
 
@@ -1562,7 +2123,7 @@ static void cmd_new_commit()
        store_tree(&b->branch_tree);
        hashcpy(b->branch_tree.versions[0].sha1,
                b->branch_tree.versions[1].sha1);
-       size_dbuf(&new_data, 97 + msglen
+       size_dbuf(&new_data, 114 + msglen
                + merge_count * 49
                + (author
                        ? strlen(author) + strlen(committer)
@@ -1578,40 +2139,24 @@ static void cmd_new_commit()
                free(merge_list);
                merge_list = next;
        }
-       if (author)
-               sp += sprintf(sp, "%s\n", author);
-       else
-               sp += sprintf(sp, "author %s\n", committer + 10);
-       sp += sprintf(sp, "%s\n\n", committer);
+       sp += sprintf(sp, "author %s\n", author ? author : committer);
+       sp += sprintf(sp, "committer %s\n", committer);
+       *sp++ = '\n';
        memcpy(sp, msg, msglen);
        sp += msglen;
-       if (author)
-               free(author);
+       free(author);
        free(committer);
        free(msg);
 
-       store_object(OBJ_COMMIT,
+       if (!store_object(OBJ_COMMIT,
                new_data.buffer, sp - (char*)new_data.buffer,
-               NULL, b->sha1, next_mark);
+               NULL, b->sha1, next_mark))
+               b->pack_id = pack_id;
        b->last_commit = object_count_by_type[OBJ_COMMIT];
-
-       if (branch_log) {
-               int need_dq = quote_c_style(b->name, NULL, NULL, 0);
-               fprintf(branch_log, "commit ");
-               if (need_dq) {
-                       fputc('"', branch_log);
-                       quote_c_style(b->name, NULL, branch_log, 0);
-                       fputc('"', branch_log);
-               } else
-                       fprintf(branch_log, "%s", b->name);
-               fprintf(branch_log," :%lu %s\n",next_mark,sha1_to_hex(b->sha1));
-       }
 }
 
-static void cmd_new_tag()
+static void cmd_new_tag(void)
 {
-       char *str_uq;
-       const char *endp;
        char *sp;
        const char *from;
        char *tagger;
@@ -1619,17 +2164,11 @@ static void cmd_new_tag()
        void *msg;
        size_t msglen;
        struct tag *t;
-       unsigned long from_mark = 0;
+       uintmax_t from_mark = 0;
        unsigned char sha1[20];
 
        /* Obtain the new tag name from the rest of our command */
        sp = strchr(command_buf.buf, ' ') + 1;
-       str_uq = unquote_c_style(sp, &endp);
-       if (str_uq) {
-               if (*endp)
-                       die("Garbage after tag name in: %s", command_buf.buf);
-               sp = str_uq;
-       }
        t = pool_alloc(sizeof(struct tag));
        t->next_tag = NULL;
        t->name = pool_strdup(sp);
@@ -1638,51 +2177,39 @@ static void cmd_new_tag()
        else
                first_tag = t;
        last_tag = t;
-       if (str_uq)
-               free(str_uq);
        read_next_command();
 
        /* from ... */
-       if (strncmp("from ", command_buf.buf, 5))
+       if (prefixcmp(command_buf.buf, "from "))
                die("Expected from command, got %s", command_buf.buf);
-
        from = strchr(command_buf.buf, ' ') + 1;
-       str_uq = unquote_c_style(from, &endp);
-       if (str_uq) {
-               if (*endp)
-                       die("Garbage after string in: %s", command_buf.buf);
-               from = str_uq;
-       }
-
        s = lookup_branch(from);
        if (s) {
                hashcpy(sha1, s->sha1);
        } else if (*from == ':') {
-               from_mark = strtoul(from + 1, NULL, 10);
-               struct object_entry *oe = find_mark(from_mark);
+               struct object_entry *oe;
+               from_mark = strtoumax(from + 1, NULL, 10);
+               oe = find_mark(from_mark);
                if (oe->type != OBJ_COMMIT)
-                       die("Mark :%lu not a commit", from_mark);
+                       die("Mark :%" PRIuMAX " not a commit", from_mark);
                hashcpy(sha1, oe->sha1);
        } else if (!get_sha1(from, sha1)) {
                unsigned long size;
                char *buf;
 
                buf = read_object_with_reference(sha1,
-                       type_names[OBJ_COMMIT], &size, sha1);
+                       commit_type, &size, sha1);
                if (!buf || size < 46)
                        die("Not a valid commit: %s", from);
                free(buf);
        } else
                die("Invalid ref name or SHA1 expression: %s", from);
-
-       if (str_uq)
-               free(str_uq);
        read_next_command();
 
        /* tagger ... */
-       if (strncmp("tagger ", command_buf.buf, 7))
+       if (prefixcmp(command_buf.buf, "tagger "))
                die("Expected tagger command, got %s", command_buf.buf);
-       tagger = strdup(command_buf.buf);
+       tagger = parse_ident(command_buf.buf + 7);
 
        /* tag payload/message */
        read_next_command();
@@ -1692,48 +2219,35 @@ static void cmd_new_tag()
        size_dbuf(&new_data, 67+strlen(t->name)+strlen(tagger)+msglen);
        sp = new_data.buffer;
        sp += sprintf(sp, "object %s\n", sha1_to_hex(sha1));
-       sp += sprintf(sp, "type %s\n", type_names[OBJ_COMMIT]);
+       sp += sprintf(sp, "type %s\n", commit_type);
        sp += sprintf(sp, "tag %s\n", t->name);
-       sp += sprintf(sp, "%s\n\n", tagger);
+       sp += sprintf(sp, "tagger %s\n", tagger);
+       *sp++ = '\n';
        memcpy(sp, msg, msglen);
        sp += msglen;
        free(tagger);
        free(msg);
 
-       store_object(OBJ_TAG, new_data.buffer, sp - (char*)new_data.buffer,
-               NULL, t->sha1, 0);
-
-       if (branch_log) {
-               int need_dq = quote_c_style(t->name, NULL, NULL, 0);
-               fprintf(branch_log, "tag ");
-               if (need_dq) {
-                       fputc('"', branch_log);
-                       quote_c_style(t->name, NULL, branch_log, 0);
-                       fputc('"', branch_log);
-               } else
-                       fprintf(branch_log, "%s", t->name);
-               fprintf(branch_log," :%lu %s\n",from_mark,sha1_to_hex(t->sha1));
-       }
+       if (store_object(OBJ_TAG, new_data.buffer,
+               sp - (char*)new_data.buffer,
+               NULL, t->sha1, 0))
+               t->pack_id = MAX_PACK_ID;
+       else
+               t->pack_id = pack_id;
 }
 
-static void cmd_reset_branch()
+static void cmd_reset_branch(void)
 {
        struct branch *b;
-       char *str_uq;
-       const char *endp;
        char *sp;
 
        /* Obtain the branch name from the rest of our command */
        sp = strchr(command_buf.buf, ' ') + 1;
-       str_uq = unquote_c_style(sp, &endp);
-       if (str_uq) {
-               if (*endp)
-                       die("Garbage after ref in: %s", command_buf.buf);
-               sp = str_uq;
-       }
        b = lookup_branch(sp);
        if (b) {
-               b->last_commit = 0;
+               hashclr(b->sha1);
+               hashclr(b->branch_tree.versions[0].sha1);
+               hashclr(b->branch_tree.versions[1].sha1);
                if (b->branch_tree.tree) {
                        release_tree_content_recursive(b->branch_tree.tree);
                        b->branch_tree.tree = NULL;
@@ -1741,81 +2255,148 @@ static void cmd_reset_branch()
        }
        else
                b = new_branch(sp);
-       if (str_uq)
-               free(str_uq);
        read_next_command();
-       cmd_from(b);
+       if (!cmd_from(b) && command_buf.len > 1)
+               unread_command_buf = 1;
 }
 
-static void cmd_checkpoint()
+static void cmd_checkpoint(void)
 {
        if (object_count) {
-               end_packfile();
-               start_packfile();
+               cycle_packfile();
+               dump_branches();
+               dump_tags();
+               dump_marks();
        }
-       read_next_command();
+       skip_optional_lf();
+}
+
+static void cmd_progress(void)
+{
+       fwrite(command_buf.buf, 1, command_buf.len - 1, stdout);
+       fputc('\n', stdout);
+       fflush(stdout);
+       skip_optional_lf();
+}
+
+static void import_marks(const char *input_file)
+{
+       char line[512];
+       FILE *f = fopen(input_file, "r");
+       if (!f)
+               die("cannot read %s: %s", input_file, strerror(errno));
+       while (fgets(line, sizeof(line), f)) {
+               uintmax_t mark;
+               char *end;
+               unsigned char sha1[20];
+               struct object_entry *e;
+
+               end = strchr(line, '\n');
+               if (line[0] != ':' || !end)
+                       die("corrupt mark line: %s", line);
+               *end = 0;
+               mark = strtoumax(line + 1, &end, 10);
+               if (!mark || end == line + 1
+                       || *end != ' ' || get_sha1(end + 1, sha1))
+                       die("corrupt mark line: %s", line);
+               e = find_object(sha1);
+               if (!e) {
+                       enum object_type type = sha1_object_info(sha1, NULL);
+                       if (type < 0)
+                               die("object not found: %s", sha1_to_hex(sha1));
+                       e = insert_object(sha1);
+                       e->type = type;
+                       e->pack_id = MAX_PACK_ID;
+                       e->offset = 1; /* just not zero! */
+               }
+               insert_mark(mark, e);
+       }
+       fclose(f);
 }
 
 static const char fast_import_usage[] =
-"git-fast-import [--objects=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file] [--branch-log=log] temp.pack";
+"git-fast-import [--date-format=f] [--max-pack-size=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file]";
 
 int main(int argc, const char **argv)
 {
-       int i;
-       unsigned long est_obj_cnt = object_entry_alloc;
-       unsigned long duplicate_count;
+       unsigned int i, show_stats = 1;
 
-       setup_ident();
        git_config(git_default_config);
+       alloc_objects(object_entry_alloc);
+       strbuf_init(&command_buf);
+       atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
+       branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
+       avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
+       marks = pool_calloc(1, sizeof(struct mark_set));
 
        for (i = 1; i < argc; i++) {
                const char *a = argv[i];
 
                if (*a != '-' || !strcmp(a, "--"))
                        break;
-               else if (!strncmp(a, "--objects=", 10))
-                       est_obj_cnt = strtoul(a + 10, NULL, 0);
-               else if (!strncmp(a, "--depth=", 8))
+               else if (!prefixcmp(a, "--date-format=")) {
+                       const char *fmt = a + 14;
+                       if (!strcmp(fmt, "raw"))
+                               whenspec = WHENSPEC_RAW;
+                       else if (!strcmp(fmt, "rfc2822"))
+                               whenspec = WHENSPEC_RFC2822;
+                       else if (!strcmp(fmt, "now"))
+                               whenspec = WHENSPEC_NOW;
+                       else
+                               die("unknown --date-format argument %s", fmt);
+               }
+               else if (!prefixcmp(a, "--max-pack-size="))
+                       max_packsize = strtoumax(a + 16, NULL, 0) * 1024 * 1024;
+               else if (!prefixcmp(a, "--depth="))
                        max_depth = strtoul(a + 8, NULL, 0);
-               else if (!strncmp(a, "--active-branches=", 18))
+               else if (!prefixcmp(a, "--active-branches="))
                        max_active_branches = strtoul(a + 18, NULL, 0);
-               else if (!strncmp(a, "--export-marks=", 15))
+               else if (!prefixcmp(a, "--import-marks="))
+                       import_marks(a + 15);
+               else if (!prefixcmp(a, "--export-marks="))
                        mark_file = a + 15;
-               else if (!strncmp(a, "--branch-log=", 13)) {
-                       branch_log = fopen(a + 13, "w");
-                       if (!branch_log)
-                               die("Can't create %s: %s", a + 13, strerror(errno));
-               }
+               else if (!prefixcmp(a, "--export-pack-edges=")) {
+                       if (pack_edges)
+                               fclose(pack_edges);
+                       pack_edges = fopen(a + 20, "a");
+                       if (!pack_edges)
+                               die("Cannot open %s: %s", a + 20, strerror(errno));
+               } else if (!strcmp(a, "--force"))
+                       force_update = 1;
+               else if (!strcmp(a, "--quiet"))
+                       show_stats = 0;
+               else if (!strcmp(a, "--stats"))
+                       show_stats = 1;
                else
                        die("unknown option %s", a);
        }
-       if ((i+1) != argc)
+       if (i != argc)
                usage(fast_import_usage);
-       base_name = argv[i];
-
-       alloc_objects(est_obj_cnt);
-       strbuf_init(&command_buf);
 
-       atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
-       branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
-       avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
-       marks = pool_calloc(1, sizeof(struct mark_set));
+       rc_free = pool_alloc(cmd_save * sizeof(*rc_free));
+       for (i = 0; i < (cmd_save - 1); i++)
+               rc_free[i].next = &rc_free[i + 1];
+       rc_free[cmd_save - 1].next = NULL;
 
+       prepare_packed_git();
        start_packfile();
+       set_die_routine(die_nicely);
        for (;;) {
                read_next_command();
                if (command_buf.eof)
                        break;
                else if (!strcmp("blob", command_buf.buf))
                        cmd_new_blob();
-               else if (!strncmp("commit ", command_buf.buf, 7))
+               else if (!prefixcmp(command_buf.buf, "commit "))
                        cmd_new_commit();
-               else if (!strncmp("tag ", command_buf.buf, 4))
+               else if (!prefixcmp(command_buf.buf, "tag "))
                        cmd_new_tag();
-               else if (!strncmp("reset ", command_buf.buf, 6))
+               else if (!prefixcmp(command_buf.buf, "reset "))
                        cmd_reset_branch();
                else if (!strcmp("checkpoint", command_buf.buf))
                        cmd_checkpoint();
+               else if (!prefixcmp(command_buf.buf, "progress "))
+                       cmd_progress();
                else
                        die("Unsupported command: %s", command_buf.buf);
        }
@@ -1823,31 +2404,38 @@ int main(int argc, const char **argv)
 
        dump_branches();
        dump_tags();
+       unkeep_all_packs();
        dump_marks();
-       if (branch_log)
-               fclose(branch_log);
-
-       for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
-               duplicate_count += duplicate_count_by_type[i];
-
-       fprintf(stderr, "%s statistics:\n", argv[0]);
-       fprintf(stderr, "---------------------------------------------------------------------\n");
-       fprintf(stderr, "Alloc'd objects: %10lu (%10lu overflow  )\n", alloc_count, alloc_count - est_obj_cnt);
-       fprintf(stderr, "Total objects:   %10lu (%10lu duplicates                  )\n", object_count, duplicate_count);
-       fprintf(stderr, "      blobs  :   %10lu (%10lu duplicates %10lu deltas)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB]);
-       fprintf(stderr, "      trees  :   %10lu (%10lu duplicates %10lu deltas)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE]);
-       fprintf(stderr, "      commits:   %10lu (%10lu duplicates %10lu deltas)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT]);
-       fprintf(stderr, "      tags   :   %10lu (%10lu duplicates %10lu deltas)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG]);
-       fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
-       fprintf(stderr, "      marks:     %10u (%10lu unique    )\n", (1 << marks->shift) * 1024, marks_set_count);
-       fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
-       fprintf(stderr, "Memory total:    %10lu KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
-       fprintf(stderr, "       pools:    %10lu KiB\n", total_allocd/1024);
-       fprintf(stderr, "     objects:    %10lu KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
-       fprintf(stderr, "---------------------------------------------------------------------\n");
-       pack_report();
-       fprintf(stderr, "---------------------------------------------------------------------\n");
-       fprintf(stderr, "\n");
 
-       return 0;
+       if (pack_edges)
+               fclose(pack_edges);
+
+       if (show_stats) {
+               uintmax_t total_count = 0, duplicate_count = 0;
+               for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
+                       total_count += object_count_by_type[i];
+               for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
+                       duplicate_count += duplicate_count_by_type[i];
+
+               fprintf(stderr, "%s statistics:\n", argv[0]);
+               fprintf(stderr, "---------------------------------------------------------------------\n");
+               fprintf(stderr, "Alloc'd objects: %10" PRIuMAX "\n", alloc_count);
+               fprintf(stderr, "Total objects:   %10" PRIuMAX " (%10" PRIuMAX " duplicates                  )\n", total_count, duplicate_count);
+               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]);
+               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]);
+               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]);
+               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]);
+               fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
+               fprintf(stderr, "      marks:     %10" PRIuMAX " (%10" PRIuMAX " unique    )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
+               fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
+               fprintf(stderr, "Memory total:    %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
+               fprintf(stderr, "       pools:    %10lu KiB\n", (unsigned long)(total_allocd/1024));
+               fprintf(stderr, "     objects:    %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
+               fprintf(stderr, "---------------------------------------------------------------------\n");
+               pack_report();
+               fprintf(stderr, "---------------------------------------------------------------------\n");
+               fprintf(stderr, "\n");
+       }
+
+       return failure ? 1 : 0;
 }