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