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