]> asedeno.scripts.mit.edu Git - git.git/blob - fast-import.c
Support RFC 2822 date parsing in fast-import.
[git.git] / fast-import.c
1 /*
2 Format of STDIN stream:
3
4   stream ::= cmd*;
5
6   cmd ::= new_blob
7         | new_commit
8         | new_tag
9         | reset_branch
10         | checkpoint
11         ;
12
13   new_blob ::= 'blob' lf
14         mark?
15     file_content;
16   file_content ::= data;
17
18   new_commit ::= 'commit' sp ref_str lf
19     mark?
20     ('author' sp name '<' email '>' when lf)?
21     'committer' sp name '<' email '>' when lf
22     commit_msg
23     ('from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf)?
24     ('merge' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf)*
25     file_change*
26     lf;
27   commit_msg ::= data;
28
29   file_change ::= file_del | file_obm | file_inm;
30   file_del ::= 'D' sp path_str lf;
31   file_obm ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf;
32   file_inm ::= 'M' sp mode sp 'inline' sp path_str lf
33     data;
34
35   new_tag ::= 'tag' sp tag_str lf
36     'from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf
37         'tagger' sp name '<' email '>' when lf
38     tag_msg;
39   tag_msg ::= data;
40
41   reset_branch ::= 'reset' sp ref_str lf
42     ('from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf)?
43     lf;
44
45   checkpoint ::= 'checkpoint' lf
46     lf;
47
48      # note: the first idnum in a stream should be 1 and subsequent
49      # idnums should not have gaps between values as this will cause
50      # the stream parser to reserve space for the gapped values.  An
51          # idnum can be updated in the future to a new object by issuing
52      # a new mark directive with the old idnum.
53          #
54   mark ::= 'mark' sp idnum lf;
55   data ::= (delimited_data | exact_data)
56     lf;
57
58     # note: delim may be any string but must not contain lf.
59     # data_line may contain any data but must not be exactly
60     # delim.
61   delimited_data ::= 'data' sp '<<' delim lf
62     (data_line lf)*
63         delim lf;
64
65      # note: declen indicates the length of binary_data in bytes.
66      # declen does not include the lf preceeding the binary data.
67      #
68   exact_data ::= 'data' sp declen lf
69     binary_data;
70
71      # note: quoted strings are C-style quoting supporting \c for
72      # common escapes of 'c' (e..g \n, \t, \\, \") or \nnn where nnn
73          # is the signed byte value in octal.  Note that the only
74      # characters which must actually be escaped to protect the
75      # stream formatting is: \, " and LF.  Otherwise these values
76          # are UTF8.
77      #
78   ref_str     ::= ref;
79   sha1exp_str ::= sha1exp;
80   tag_str     ::= tag;
81   path_str    ::= path    | '"' quoted(path)    '"' ;
82   mode        ::= '100644' | '644'
83                 | '100755' | '755'
84                 | '140000'
85                 ;
86
87   declen ::= # unsigned 32 bit value, ascii base10 notation;
88   bigint ::= # unsigned integer value, ascii base10 notation;
89   binary_data ::= # file content, not interpreted;
90
91   when         ::= raw_when | rfc2822_when;
92   raw_when     ::= ts sp tz;
93   rfc2822_when ::= # Valid RFC 2822 date and time;
94
95   sp ::= # ASCII space character;
96   lf ::= # ASCII newline (LF) character;
97
98      # note: a colon (':') must precede the numerical value assigned to
99          # an idnum.  This is to distinguish it from a ref or tag name as
100      # GIT does not permit ':' in ref or tag strings.
101          #
102   idnum   ::= ':' bigint;
103   path    ::= # GIT style file path, e.g. "a/b/c";
104   ref     ::= # GIT ref name, e.g. "refs/heads/MOZ_GECKO_EXPERIMENT";
105   tag     ::= # GIT tag name, e.g. "FIREFOX_1_5";
106   sha1exp ::= # Any valid GIT SHA1 expression;
107   hexsha1 ::= # SHA1 in hexadecimal format;
108
109      # note: name and email are UTF8 strings, however name must not
110          # contain '<' or lf and email must not contain any of the
111      # following: '<', '>', lf.
112          #
113   name  ::= # valid GIT author/committer name;
114   email ::= # valid GIT author/committer email;
115   ts    ::= # time since the epoch in seconds, ascii base10 notation;
116   tz    ::= # GIT style timezone;
117 */
118
119 #include "builtin.h"
120 #include "cache.h"
121 #include "object.h"
122 #include "blob.h"
123 #include "tree.h"
124 #include "delta.h"
125 #include "pack.h"
126 #include "refs.h"
127 #include "csum-file.h"
128 #include "strbuf.h"
129 #include "quote.h"
130
131 #define PACK_ID_BITS 16
132 #define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
133
134 struct object_entry
135 {
136         struct object_entry *next;
137         uint32_t offset;
138         unsigned type : TYPE_BITS;
139         unsigned pack_id : PACK_ID_BITS;
140         unsigned char sha1[20];
141 };
142
143 struct object_entry_pool
144 {
145         struct object_entry_pool *next_pool;
146         struct object_entry *next_free;
147         struct object_entry *end;
148         struct object_entry entries[FLEX_ARRAY]; /* more */
149 };
150
151 struct mark_set
152 {
153         union {
154                 struct object_entry *marked[1024];
155                 struct mark_set *sets[1024];
156         } data;
157         unsigned int shift;
158 };
159
160 struct last_object
161 {
162         void *data;
163         unsigned long len;
164         uint32_t offset;
165         unsigned int depth;
166         unsigned no_free:1;
167 };
168
169 struct mem_pool
170 {
171         struct mem_pool *next_pool;
172         char *next_free;
173         char *end;
174         char space[FLEX_ARRAY]; /* more */
175 };
176
177 struct atom_str
178 {
179         struct atom_str *next_atom;
180         unsigned short str_len;
181         char str_dat[FLEX_ARRAY]; /* more */
182 };
183
184 struct tree_content;
185 struct tree_entry
186 {
187         struct tree_content *tree;
188         struct atom_str* name;
189         struct tree_entry_ms
190         {
191                 uint16_t mode;
192                 unsigned char sha1[20];
193         } versions[2];
194 };
195
196 struct tree_content
197 {
198         unsigned int entry_capacity; /* must match avail_tree_content */
199         unsigned int entry_count;
200         unsigned int delta_depth;
201         struct tree_entry *entries[FLEX_ARRAY]; /* more */
202 };
203
204 struct avail_tree_content
205 {
206         unsigned int entry_capacity; /* must match tree_content */
207         struct avail_tree_content *next_avail;
208 };
209
210 struct branch
211 {
212         struct branch *table_next_branch;
213         struct branch *active_next_branch;
214         const char *name;
215         struct tree_entry branch_tree;
216         uintmax_t last_commit;
217         unsigned int pack_id;
218         unsigned char sha1[20];
219 };
220
221 struct tag
222 {
223         struct tag *next_tag;
224         const char *name;
225         unsigned int pack_id;
226         unsigned char sha1[20];
227 };
228
229 struct dbuf
230 {
231         void *buffer;
232         size_t capacity;
233 };
234
235 struct hash_list
236 {
237         struct hash_list *next;
238         unsigned char sha1[20];
239 };
240
241 typedef enum {
242         WHENSPEC_RAW = 1,
243         WHENSPEC_RFC2822,
244         WHENSPEC_NOW,
245 } whenspec_type;
246
247 /* Configured limits on output */
248 static unsigned long max_depth = 10;
249 static unsigned long max_packsize = (1LL << 32) - 1;
250
251 /* Stats and misc. counters */
252 static uintmax_t alloc_count;
253 static uintmax_t marks_set_count;
254 static uintmax_t object_count_by_type[1 << TYPE_BITS];
255 static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
256 static uintmax_t delta_count_by_type[1 << TYPE_BITS];
257 static unsigned long object_count;
258 static unsigned long branch_count;
259 static unsigned long branch_load_count;
260
261 /* Memory pools */
262 static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
263 static size_t total_allocd;
264 static struct mem_pool *mem_pool;
265
266 /* Atom management */
267 static unsigned int atom_table_sz = 4451;
268 static unsigned int atom_cnt;
269 static struct atom_str **atom_table;
270
271 /* The .pack file being generated */
272 static unsigned int pack_id;
273 static struct packed_git *pack_data;
274 static struct packed_git **all_packs;
275 static unsigned long pack_size;
276
277 /* Table of objects we've written. */
278 static unsigned int object_entry_alloc = 5000;
279 static struct object_entry_pool *blocks;
280 static struct object_entry *object_table[1 << 16];
281 static struct mark_set *marks;
282 static const char* mark_file;
283
284 /* Our last blob */
285 static struct last_object last_blob;
286
287 /* Tree management */
288 static unsigned int tree_entry_alloc = 1000;
289 static void *avail_tree_entry;
290 static unsigned int avail_tree_table_sz = 100;
291 static struct avail_tree_content **avail_tree_table;
292 static struct dbuf old_tree;
293 static struct dbuf new_tree;
294
295 /* Branch data */
296 static unsigned long max_active_branches = 5;
297 static unsigned long cur_active_branches;
298 static unsigned long branch_table_sz = 1039;
299 static struct branch **branch_table;
300 static struct branch *active_branches;
301
302 /* Tag data */
303 static struct tag *first_tag;
304 static struct tag *last_tag;
305
306 /* Input stream parsing */
307 static whenspec_type whenspec = WHENSPEC_RAW;
308 static struct strbuf command_buf;
309 static uintmax_t next_mark;
310 static struct dbuf new_data;
311
312
313 static void alloc_objects(unsigned int cnt)
314 {
315         struct object_entry_pool *b;
316
317         b = xmalloc(sizeof(struct object_entry_pool)
318                 + cnt * sizeof(struct object_entry));
319         b->next_pool = blocks;
320         b->next_free = b->entries;
321         b->end = b->entries + cnt;
322         blocks = b;
323         alloc_count += cnt;
324 }
325
326 static struct object_entry *new_object(unsigned char *sha1)
327 {
328         struct object_entry *e;
329
330         if (blocks->next_free == blocks->end)
331                 alloc_objects(object_entry_alloc);
332
333         e = blocks->next_free++;
334         hashcpy(e->sha1, sha1);
335         return e;
336 }
337
338 static struct object_entry *find_object(unsigned char *sha1)
339 {
340         unsigned int h = sha1[0] << 8 | sha1[1];
341         struct object_entry *e;
342         for (e = object_table[h]; e; e = e->next)
343                 if (!hashcmp(sha1, e->sha1))
344                         return e;
345         return NULL;
346 }
347
348 static struct object_entry *insert_object(unsigned char *sha1)
349 {
350         unsigned int h = sha1[0] << 8 | sha1[1];
351         struct object_entry *e = object_table[h];
352         struct object_entry *p = NULL;
353
354         while (e) {
355                 if (!hashcmp(sha1, e->sha1))
356                         return e;
357                 p = e;
358                 e = e->next;
359         }
360
361         e = new_object(sha1);
362         e->next = NULL;
363         e->offset = 0;
364         if (p)
365                 p->next = e;
366         else
367                 object_table[h] = e;
368         return e;
369 }
370
371 static unsigned int hc_str(const char *s, size_t len)
372 {
373         unsigned int r = 0;
374         while (len-- > 0)
375                 r = r * 31 + *s++;
376         return r;
377 }
378
379 static void *pool_alloc(size_t len)
380 {
381         struct mem_pool *p;
382         void *r;
383
384         for (p = mem_pool; p; p = p->next_pool)
385                 if ((p->end - p->next_free >= len))
386                         break;
387
388         if (!p) {
389                 if (len >= (mem_pool_alloc/2)) {
390                         total_allocd += len;
391                         return xmalloc(len);
392                 }
393                 total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
394                 p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc);
395                 p->next_pool = mem_pool;
396                 p->next_free = p->space;
397                 p->end = p->next_free + mem_pool_alloc;
398                 mem_pool = p;
399         }
400
401         r = p->next_free;
402         /* round out to a pointer alignment */
403         if (len & (sizeof(void*) - 1))
404                 len += sizeof(void*) - (len & (sizeof(void*) - 1));
405         p->next_free += len;
406         return r;
407 }
408
409 static void *pool_calloc(size_t count, size_t size)
410 {
411         size_t len = count * size;
412         void *r = pool_alloc(len);
413         memset(r, 0, len);
414         return r;
415 }
416
417 static char *pool_strdup(const char *s)
418 {
419         char *r = pool_alloc(strlen(s) + 1);
420         strcpy(r, s);
421         return r;
422 }
423
424 static void size_dbuf(struct dbuf *b, size_t maxlen)
425 {
426         if (b->buffer) {
427                 if (b->capacity >= maxlen)
428                         return;
429                 free(b->buffer);
430         }
431         b->capacity = ((maxlen / 1024) + 1) * 1024;
432         b->buffer = xmalloc(b->capacity);
433 }
434
435 static void insert_mark(uintmax_t idnum, struct object_entry *oe)
436 {
437         struct mark_set *s = marks;
438         while ((idnum >> s->shift) >= 1024) {
439                 s = pool_calloc(1, sizeof(struct mark_set));
440                 s->shift = marks->shift + 10;
441                 s->data.sets[0] = marks;
442                 marks = s;
443         }
444         while (s->shift) {
445                 uintmax_t i = idnum >> s->shift;
446                 idnum -= i << s->shift;
447                 if (!s->data.sets[i]) {
448                         s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
449                         s->data.sets[i]->shift = s->shift - 10;
450                 }
451                 s = s->data.sets[i];
452         }
453         if (!s->data.marked[idnum])
454                 marks_set_count++;
455         s->data.marked[idnum] = oe;
456 }
457
458 static struct object_entry *find_mark(uintmax_t idnum)
459 {
460         uintmax_t orig_idnum = idnum;
461         struct mark_set *s = marks;
462         struct object_entry *oe = NULL;
463         if ((idnum >> s->shift) < 1024) {
464                 while (s && s->shift) {
465                         uintmax_t i = idnum >> s->shift;
466                         idnum -= i << s->shift;
467                         s = s->data.sets[i];
468                 }
469                 if (s)
470                         oe = s->data.marked[idnum];
471         }
472         if (!oe)
473                 die("mark :%ju not declared", orig_idnum);
474         return oe;
475 }
476
477 static struct atom_str *to_atom(const char *s, unsigned short len)
478 {
479         unsigned int hc = hc_str(s, len) % atom_table_sz;
480         struct atom_str *c;
481
482         for (c = atom_table[hc]; c; c = c->next_atom)
483                 if (c->str_len == len && !strncmp(s, c->str_dat, len))
484                         return c;
485
486         c = pool_alloc(sizeof(struct atom_str) + len + 1);
487         c->str_len = len;
488         strncpy(c->str_dat, s, len);
489         c->str_dat[len] = 0;
490         c->next_atom = atom_table[hc];
491         atom_table[hc] = c;
492         atom_cnt++;
493         return c;
494 }
495
496 static struct branch *lookup_branch(const char *name)
497 {
498         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
499         struct branch *b;
500
501         for (b = branch_table[hc]; b; b = b->table_next_branch)
502                 if (!strcmp(name, b->name))
503                         return b;
504         return NULL;
505 }
506
507 static struct branch *new_branch(const char *name)
508 {
509         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
510         struct branch* b = lookup_branch(name);
511
512         if (b)
513                 die("Invalid attempt to create duplicate branch: %s", name);
514         if (check_ref_format(name))
515                 die("Branch name doesn't conform to GIT standards: %s", name);
516
517         b = pool_calloc(1, sizeof(struct branch));
518         b->name = pool_strdup(name);
519         b->table_next_branch = branch_table[hc];
520         b->branch_tree.versions[0].mode = S_IFDIR;
521         b->branch_tree.versions[1].mode = S_IFDIR;
522         b->pack_id = MAX_PACK_ID;
523         branch_table[hc] = b;
524         branch_count++;
525         return b;
526 }
527
528 static unsigned int hc_entries(unsigned int cnt)
529 {
530         cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
531         return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
532 }
533
534 static struct tree_content *new_tree_content(unsigned int cnt)
535 {
536         struct avail_tree_content *f, *l = NULL;
537         struct tree_content *t;
538         unsigned int hc = hc_entries(cnt);
539
540         for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
541                 if (f->entry_capacity >= cnt)
542                         break;
543
544         if (f) {
545                 if (l)
546                         l->next_avail = f->next_avail;
547                 else
548                         avail_tree_table[hc] = f->next_avail;
549         } else {
550                 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
551                 f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
552                 f->entry_capacity = cnt;
553         }
554
555         t = (struct tree_content*)f;
556         t->entry_count = 0;
557         t->delta_depth = 0;
558         return t;
559 }
560
561 static void release_tree_entry(struct tree_entry *e);
562 static void release_tree_content(struct tree_content *t)
563 {
564         struct avail_tree_content *f = (struct avail_tree_content*)t;
565         unsigned int hc = hc_entries(f->entry_capacity);
566         f->next_avail = avail_tree_table[hc];
567         avail_tree_table[hc] = f;
568 }
569
570 static void release_tree_content_recursive(struct tree_content *t)
571 {
572         unsigned int i;
573         for (i = 0; i < t->entry_count; i++)
574                 release_tree_entry(t->entries[i]);
575         release_tree_content(t);
576 }
577
578 static struct tree_content *grow_tree_content(
579         struct tree_content *t,
580         int amt)
581 {
582         struct tree_content *r = new_tree_content(t->entry_count + amt);
583         r->entry_count = t->entry_count;
584         r->delta_depth = t->delta_depth;
585         memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
586         release_tree_content(t);
587         return r;
588 }
589
590 static struct tree_entry *new_tree_entry(void)
591 {
592         struct tree_entry *e;
593
594         if (!avail_tree_entry) {
595                 unsigned int n = tree_entry_alloc;
596                 total_allocd += n * sizeof(struct tree_entry);
597                 avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry));
598                 while (n-- > 1) {
599                         *((void**)e) = e + 1;
600                         e++;
601                 }
602                 *((void**)e) = NULL;
603         }
604
605         e = avail_tree_entry;
606         avail_tree_entry = *((void**)e);
607         return e;
608 }
609
610 static void release_tree_entry(struct tree_entry *e)
611 {
612         if (e->tree)
613                 release_tree_content_recursive(e->tree);
614         *((void**)e) = avail_tree_entry;
615         avail_tree_entry = e;
616 }
617
618 static void start_packfile(void)
619 {
620         static char tmpfile[PATH_MAX];
621         struct packed_git *p;
622         struct pack_header hdr;
623         int pack_fd;
624
625         snprintf(tmpfile, sizeof(tmpfile),
626                 "%s/pack_XXXXXX", get_object_directory());
627         pack_fd = mkstemp(tmpfile);
628         if (pack_fd < 0)
629                 die("Can't create %s: %s", tmpfile, strerror(errno));
630         p = xcalloc(1, sizeof(*p) + strlen(tmpfile) + 2);
631         strcpy(p->pack_name, tmpfile);
632         p->pack_fd = pack_fd;
633
634         hdr.hdr_signature = htonl(PACK_SIGNATURE);
635         hdr.hdr_version = htonl(2);
636         hdr.hdr_entries = 0;
637         write_or_die(p->pack_fd, &hdr, sizeof(hdr));
638
639         pack_data = p;
640         pack_size = sizeof(hdr);
641         object_count = 0;
642
643         all_packs = xrealloc(all_packs, sizeof(*all_packs) * (pack_id + 1));
644         all_packs[pack_id] = p;
645 }
646
647 static void fixup_header_footer(void)
648 {
649         static const int buf_sz = 128 * 1024;
650         int pack_fd = pack_data->pack_fd;
651         SHA_CTX c;
652         struct pack_header hdr;
653         char *buf;
654
655         if (lseek(pack_fd, 0, SEEK_SET) != 0)
656                 die("Failed seeking to start: %s", strerror(errno));
657         if (read_in_full(pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
658                 die("Unable to reread header of %s", pack_data->pack_name);
659         if (lseek(pack_fd, 0, SEEK_SET) != 0)
660                 die("Failed seeking to start: %s", strerror(errno));
661         hdr.hdr_entries = htonl(object_count);
662         write_or_die(pack_fd, &hdr, sizeof(hdr));
663
664         SHA1_Init(&c);
665         SHA1_Update(&c, &hdr, sizeof(hdr));
666
667         buf = xmalloc(buf_sz);
668         for (;;) {
669                 size_t n = xread(pack_fd, buf, buf_sz);
670                 if (!n)
671                         break;
672                 if (n < 0)
673                         die("Failed to checksum %s", pack_data->pack_name);
674                 SHA1_Update(&c, buf, n);
675         }
676         free(buf);
677
678         SHA1_Final(pack_data->sha1, &c);
679         write_or_die(pack_fd, pack_data->sha1, sizeof(pack_data->sha1));
680         close(pack_fd);
681 }
682
683 static int oecmp (const void *a_, const void *b_)
684 {
685         struct object_entry *a = *((struct object_entry**)a_);
686         struct object_entry *b = *((struct object_entry**)b_);
687         return hashcmp(a->sha1, b->sha1);
688 }
689
690 static char *create_index(void)
691 {
692         static char tmpfile[PATH_MAX];
693         SHA_CTX ctx;
694         struct sha1file *f;
695         struct object_entry **idx, **c, **last, *e;
696         struct object_entry_pool *o;
697         uint32_t array[256];
698         int i, idx_fd;
699
700         /* Build the sorted table of object IDs. */
701         idx = xmalloc(object_count * sizeof(struct object_entry*));
702         c = idx;
703         for (o = blocks; o; o = o->next_pool)
704                 for (e = o->next_free; e-- != o->entries;)
705                         if (pack_id == e->pack_id)
706                                 *c++ = e;
707         last = idx + object_count;
708         if (c != last)
709                 die("internal consistency error creating the index");
710         qsort(idx, object_count, sizeof(struct object_entry*), oecmp);
711
712         /* Generate the fan-out array. */
713         c = idx;
714         for (i = 0; i < 256; i++) {
715                 struct object_entry **next = c;;
716                 while (next < last) {
717                         if ((*next)->sha1[0] != i)
718                                 break;
719                         next++;
720                 }
721                 array[i] = htonl(next - idx);
722                 c = next;
723         }
724
725         snprintf(tmpfile, sizeof(tmpfile),
726                 "%s/index_XXXXXX", get_object_directory());
727         idx_fd = mkstemp(tmpfile);
728         if (idx_fd < 0)
729                 die("Can't create %s: %s", tmpfile, strerror(errno));
730         f = sha1fd(idx_fd, tmpfile);
731         sha1write(f, array, 256 * sizeof(int));
732         SHA1_Init(&ctx);
733         for (c = idx; c != last; c++) {
734                 uint32_t offset = htonl((*c)->offset);
735                 sha1write(f, &offset, 4);
736                 sha1write(f, (*c)->sha1, sizeof((*c)->sha1));
737                 SHA1_Update(&ctx, (*c)->sha1, 20);
738         }
739         sha1write(f, pack_data->sha1, sizeof(pack_data->sha1));
740         sha1close(f, NULL, 1);
741         free(idx);
742         SHA1_Final(pack_data->sha1, &ctx);
743         return tmpfile;
744 }
745
746 static char *keep_pack(char *curr_index_name)
747 {
748         static char name[PATH_MAX];
749         static char *keep_msg = "fast-import";
750         int keep_fd;
751
752         chmod(pack_data->pack_name, 0444);
753         chmod(curr_index_name, 0444);
754
755         snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
756                  get_object_directory(), sha1_to_hex(pack_data->sha1));
757         keep_fd = open(name, O_RDWR|O_CREAT|O_EXCL, 0600);
758         if (keep_fd < 0)
759                 die("cannot create keep file");
760         write(keep_fd, keep_msg, strlen(keep_msg));
761         close(keep_fd);
762
763         snprintf(name, sizeof(name), "%s/pack/pack-%s.pack",
764                  get_object_directory(), sha1_to_hex(pack_data->sha1));
765         if (move_temp_to_file(pack_data->pack_name, name))
766                 die("cannot store pack file");
767
768         snprintf(name, sizeof(name), "%s/pack/pack-%s.idx",
769                  get_object_directory(), sha1_to_hex(pack_data->sha1));
770         if (move_temp_to_file(curr_index_name, name))
771                 die("cannot store index file");
772         return name;
773 }
774
775 static void unkeep_all_packs(void)
776 {
777         static char name[PATH_MAX];
778         int k;
779
780         for (k = 0; k < pack_id; k++) {
781                 struct packed_git *p = all_packs[k];
782                 snprintf(name, sizeof(name), "%s/pack/pack-%s.keep",
783                          get_object_directory(), sha1_to_hex(p->sha1));
784                 unlink(name);
785         }
786 }
787
788 static void end_packfile(void)
789 {
790         struct packed_git *old_p = pack_data, *new_p;
791
792         if (object_count) {
793                 char *idx_name;
794                 int i;
795                 struct branch *b;
796                 struct tag *t;
797
798                 fixup_header_footer();
799                 idx_name = keep_pack(create_index());
800
801                 /* Register the packfile with core git's machinary. */
802                 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
803                 if (!new_p)
804                         die("core git rejected index %s", idx_name);
805                 new_p->windows = old_p->windows;
806                 all_packs[pack_id] = new_p;
807                 install_packed_git(new_p);
808
809                 /* Print the boundary */
810                 fprintf(stdout, "%s:", new_p->pack_name);
811                 for (i = 0; i < branch_table_sz; i++) {
812                         for (b = branch_table[i]; b; b = b->table_next_branch) {
813                                 if (b->pack_id == pack_id)
814                                         fprintf(stdout, " %s", sha1_to_hex(b->sha1));
815                         }
816                 }
817                 for (t = first_tag; t; t = t->next_tag) {
818                         if (t->pack_id == pack_id)
819                                 fprintf(stdout, " %s", sha1_to_hex(t->sha1));
820                 }
821                 fputc('\n', stdout);
822
823                 pack_id++;
824         }
825         else
826                 unlink(old_p->pack_name);
827         free(old_p);
828
829         /* We can't carry a delta across packfiles. */
830         free(last_blob.data);
831         last_blob.data = NULL;
832         last_blob.len = 0;
833         last_blob.offset = 0;
834         last_blob.depth = 0;
835 }
836
837 static void checkpoint(void)
838 {
839         end_packfile();
840         start_packfile();
841 }
842
843 static size_t encode_header(
844         enum object_type type,
845         size_t size,
846         unsigned char *hdr)
847 {
848         int n = 1;
849         unsigned char c;
850
851         if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
852                 die("bad type %d", type);
853
854         c = (type << 4) | (size & 15);
855         size >>= 4;
856         while (size) {
857                 *hdr++ = c | 0x80;
858                 c = size & 0x7f;
859                 size >>= 7;
860                 n++;
861         }
862         *hdr = c;
863         return n;
864 }
865
866 static int store_object(
867         enum object_type type,
868         void *dat,
869         size_t datlen,
870         struct last_object *last,
871         unsigned char *sha1out,
872         uintmax_t mark)
873 {
874         void *out, *delta;
875         struct object_entry *e;
876         unsigned char hdr[96];
877         unsigned char sha1[20];
878         unsigned long hdrlen, deltalen;
879         SHA_CTX c;
880         z_stream s;
881
882         hdrlen = sprintf((char*)hdr,"%s %lu",type_names[type],datlen) + 1;
883         SHA1_Init(&c);
884         SHA1_Update(&c, hdr, hdrlen);
885         SHA1_Update(&c, dat, datlen);
886         SHA1_Final(sha1, &c);
887         if (sha1out)
888                 hashcpy(sha1out, sha1);
889
890         e = insert_object(sha1);
891         if (mark)
892                 insert_mark(mark, e);
893         if (e->offset) {
894                 duplicate_count_by_type[type]++;
895                 return 1;
896         }
897
898         if (last && last->data && last->depth < max_depth) {
899                 delta = diff_delta(last->data, last->len,
900                         dat, datlen,
901                         &deltalen, 0);
902                 if (delta && deltalen >= datlen) {
903                         free(delta);
904                         delta = NULL;
905                 }
906         } else
907                 delta = NULL;
908
909         memset(&s, 0, sizeof(s));
910         deflateInit(&s, zlib_compression_level);
911         if (delta) {
912                 s.next_in = delta;
913                 s.avail_in = deltalen;
914         } else {
915                 s.next_in = dat;
916                 s.avail_in = datlen;
917         }
918         s.avail_out = deflateBound(&s, s.avail_in);
919         s.next_out = out = xmalloc(s.avail_out);
920         while (deflate(&s, Z_FINISH) == Z_OK)
921                 /* nothing */;
922         deflateEnd(&s);
923
924         /* Determine if we should auto-checkpoint. */
925         if ((pack_size + 60 + s.total_out) > max_packsize
926                 || (pack_size + 60 + s.total_out) < pack_size) {
927
928                 /* This new object needs to *not* have the current pack_id. */
929                 e->pack_id = pack_id + 1;
930                 checkpoint();
931
932                 /* We cannot carry a delta into the new pack. */
933                 if (delta) {
934                         free(delta);
935                         delta = NULL;
936
937                         memset(&s, 0, sizeof(s));
938                         deflateInit(&s, zlib_compression_level);
939                         s.next_in = dat;
940                         s.avail_in = datlen;
941                         s.avail_out = deflateBound(&s, s.avail_in);
942                         s.next_out = out = xrealloc(out, s.avail_out);
943                         while (deflate(&s, Z_FINISH) == Z_OK)
944                                 /* nothing */;
945                         deflateEnd(&s);
946                 }
947         }
948
949         e->type = type;
950         e->pack_id = pack_id;
951         e->offset = pack_size;
952         object_count++;
953         object_count_by_type[type]++;
954
955         if (delta) {
956                 unsigned long ofs = e->offset - last->offset;
957                 unsigned pos = sizeof(hdr) - 1;
958
959                 delta_count_by_type[type]++;
960                 last->depth++;
961
962                 hdrlen = encode_header(OBJ_OFS_DELTA, deltalen, hdr);
963                 write_or_die(pack_data->pack_fd, hdr, hdrlen);
964                 pack_size += hdrlen;
965
966                 hdr[pos] = ofs & 127;
967                 while (ofs >>= 7)
968                         hdr[--pos] = 128 | (--ofs & 127);
969                 write_or_die(pack_data->pack_fd, hdr + pos, sizeof(hdr) - pos);
970                 pack_size += sizeof(hdr) - pos;
971         } else {
972                 if (last)
973                         last->depth = 0;
974                 hdrlen = encode_header(type, datlen, hdr);
975                 write_or_die(pack_data->pack_fd, hdr, hdrlen);
976                 pack_size += hdrlen;
977         }
978
979         write_or_die(pack_data->pack_fd, out, s.total_out);
980         pack_size += s.total_out;
981
982         free(out);
983         free(delta);
984         if (last) {
985                 if (!last->no_free)
986                         free(last->data);
987                 last->data = dat;
988                 last->offset = e->offset;
989                 last->len = datlen;
990         }
991         return 0;
992 }
993
994 static void *gfi_unpack_entry(
995         struct object_entry *oe,
996         unsigned long *sizep)
997 {
998         static char type[20];
999         struct packed_git *p = all_packs[oe->pack_id];
1000         if (p == pack_data)
1001                 p->pack_size = pack_size + 20;
1002         return unpack_entry(p, oe->offset, type, sizep);
1003 }
1004
1005 static const char *get_mode(const char *str, uint16_t *modep)
1006 {
1007         unsigned char c;
1008         uint16_t mode = 0;
1009
1010         while ((c = *str++) != ' ') {
1011                 if (c < '0' || c > '7')
1012                         return NULL;
1013                 mode = (mode << 3) + (c - '0');
1014         }
1015         *modep = mode;
1016         return str;
1017 }
1018
1019 static void load_tree(struct tree_entry *root)
1020 {
1021         unsigned char* sha1 = root->versions[1].sha1;
1022         struct object_entry *myoe;
1023         struct tree_content *t;
1024         unsigned long size;
1025         char *buf;
1026         const char *c;
1027
1028         root->tree = t = new_tree_content(8);
1029         if (is_null_sha1(sha1))
1030                 return;
1031
1032         myoe = find_object(sha1);
1033         if (myoe) {
1034                 if (myoe->type != OBJ_TREE)
1035                         die("Not a tree: %s", sha1_to_hex(sha1));
1036                 t->delta_depth = 0;
1037                 buf = gfi_unpack_entry(myoe, &size);
1038         } else {
1039                 char type[20];
1040                 buf = read_sha1_file(sha1, type, &size);
1041                 if (!buf || strcmp(type, tree_type))
1042                         die("Can't load tree %s", sha1_to_hex(sha1));
1043         }
1044
1045         c = buf;
1046         while (c != (buf + size)) {
1047                 struct tree_entry *e = new_tree_entry();
1048
1049                 if (t->entry_count == t->entry_capacity)
1050                         root->tree = t = grow_tree_content(t, 8);
1051                 t->entries[t->entry_count++] = e;
1052
1053                 e->tree = NULL;
1054                 c = get_mode(c, &e->versions[1].mode);
1055                 if (!c)
1056                         die("Corrupt mode in %s", sha1_to_hex(sha1));
1057                 e->versions[0].mode = e->versions[1].mode;
1058                 e->name = to_atom(c, (unsigned short)strlen(c));
1059                 c += e->name->str_len + 1;
1060                 hashcpy(e->versions[0].sha1, (unsigned char*)c);
1061                 hashcpy(e->versions[1].sha1, (unsigned char*)c);
1062                 c += 20;
1063         }
1064         free(buf);
1065 }
1066
1067 static int tecmp0 (const void *_a, const void *_b)
1068 {
1069         struct tree_entry *a = *((struct tree_entry**)_a);
1070         struct tree_entry *b = *((struct tree_entry**)_b);
1071         return base_name_compare(
1072                 a->name->str_dat, a->name->str_len, a->versions[0].mode,
1073                 b->name->str_dat, b->name->str_len, b->versions[0].mode);
1074 }
1075
1076 static int tecmp1 (const void *_a, const void *_b)
1077 {
1078         struct tree_entry *a = *((struct tree_entry**)_a);
1079         struct tree_entry *b = *((struct tree_entry**)_b);
1080         return base_name_compare(
1081                 a->name->str_dat, a->name->str_len, a->versions[1].mode,
1082                 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1083 }
1084
1085 static void mktree(struct tree_content *t,
1086         int v,
1087         unsigned long *szp,
1088         struct dbuf *b)
1089 {
1090         size_t maxlen = 0;
1091         unsigned int i;
1092         char *c;
1093
1094         if (!v)
1095                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0);
1096         else
1097                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1);
1098
1099         for (i = 0; i < t->entry_count; i++) {
1100                 if (t->entries[i]->versions[v].mode)
1101                         maxlen += t->entries[i]->name->str_len + 34;
1102         }
1103
1104         size_dbuf(b, maxlen);
1105         c = b->buffer;
1106         for (i = 0; i < t->entry_count; i++) {
1107                 struct tree_entry *e = t->entries[i];
1108                 if (!e->versions[v].mode)
1109                         continue;
1110                 c += sprintf(c, "%o", (unsigned int)e->versions[v].mode);
1111                 *c++ = ' ';
1112                 strcpy(c, e->name->str_dat);
1113                 c += e->name->str_len + 1;
1114                 hashcpy((unsigned char*)c, e->versions[v].sha1);
1115                 c += 20;
1116         }
1117         *szp = c - (char*)b->buffer;
1118 }
1119
1120 static void store_tree(struct tree_entry *root)
1121 {
1122         struct tree_content *t = root->tree;
1123         unsigned int i, j, del;
1124         unsigned long new_len;
1125         struct last_object lo;
1126         struct object_entry *le;
1127
1128         if (!is_null_sha1(root->versions[1].sha1))
1129                 return;
1130
1131         for (i = 0; i < t->entry_count; i++) {
1132                 if (t->entries[i]->tree)
1133                         store_tree(t->entries[i]);
1134         }
1135
1136         le = find_object(root->versions[0].sha1);
1137         if (!S_ISDIR(root->versions[0].mode)
1138                 || !le
1139                 || le->pack_id != pack_id) {
1140                 lo.data = NULL;
1141                 lo.depth = 0;
1142         } else {
1143                 mktree(t, 0, &lo.len, &old_tree);
1144                 lo.data = old_tree.buffer;
1145                 lo.offset = le->offset;
1146                 lo.depth = t->delta_depth;
1147                 lo.no_free = 1;
1148         }
1149
1150         mktree(t, 1, &new_len, &new_tree);
1151         store_object(OBJ_TREE, new_tree.buffer, new_len,
1152                 &lo, root->versions[1].sha1, 0);
1153
1154         t->delta_depth = lo.depth;
1155         for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1156                 struct tree_entry *e = t->entries[i];
1157                 if (e->versions[1].mode) {
1158                         e->versions[0].mode = e->versions[1].mode;
1159                         hashcpy(e->versions[0].sha1, e->versions[1].sha1);
1160                         t->entries[j++] = e;
1161                 } else {
1162                         release_tree_entry(e);
1163                         del++;
1164                 }
1165         }
1166         t->entry_count -= del;
1167 }
1168
1169 static int tree_content_set(
1170         struct tree_entry *root,
1171         const char *p,
1172         const unsigned char *sha1,
1173         const uint16_t mode)
1174 {
1175         struct tree_content *t = root->tree;
1176         const char *slash1;
1177         unsigned int i, n;
1178         struct tree_entry *e;
1179
1180         slash1 = strchr(p, '/');
1181         if (slash1)
1182                 n = slash1 - p;
1183         else
1184                 n = strlen(p);
1185
1186         for (i = 0; i < t->entry_count; i++) {
1187                 e = t->entries[i];
1188                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1189                         if (!slash1) {
1190                                 if (e->versions[1].mode == mode
1191                                                 && !hashcmp(e->versions[1].sha1, sha1))
1192                                         return 0;
1193                                 e->versions[1].mode = mode;
1194                                 hashcpy(e->versions[1].sha1, sha1);
1195                                 if (e->tree) {
1196                                         release_tree_content_recursive(e->tree);
1197                                         e->tree = NULL;
1198                                 }
1199                                 hashclr(root->versions[1].sha1);
1200                                 return 1;
1201                         }
1202                         if (!S_ISDIR(e->versions[1].mode)) {
1203                                 e->tree = new_tree_content(8);
1204                                 e->versions[1].mode = S_IFDIR;
1205                         }
1206                         if (!e->tree)
1207                                 load_tree(e);
1208                         if (tree_content_set(e, slash1 + 1, sha1, mode)) {
1209                                 hashclr(root->versions[1].sha1);
1210                                 return 1;
1211                         }
1212                         return 0;
1213                 }
1214         }
1215
1216         if (t->entry_count == t->entry_capacity)
1217                 root->tree = t = grow_tree_content(t, 8);
1218         e = new_tree_entry();
1219         e->name = to_atom(p, (unsigned short)n);
1220         e->versions[0].mode = 0;
1221         hashclr(e->versions[0].sha1);
1222         t->entries[t->entry_count++] = e;
1223         if (slash1) {
1224                 e->tree = new_tree_content(8);
1225                 e->versions[1].mode = S_IFDIR;
1226                 tree_content_set(e, slash1 + 1, sha1, mode);
1227         } else {
1228                 e->tree = NULL;
1229                 e->versions[1].mode = mode;
1230                 hashcpy(e->versions[1].sha1, sha1);
1231         }
1232         hashclr(root->versions[1].sha1);
1233         return 1;
1234 }
1235
1236 static int tree_content_remove(struct tree_entry *root, const char *p)
1237 {
1238         struct tree_content *t = root->tree;
1239         const char *slash1;
1240         unsigned int i, n;
1241         struct tree_entry *e;
1242
1243         slash1 = strchr(p, '/');
1244         if (slash1)
1245                 n = slash1 - p;
1246         else
1247                 n = strlen(p);
1248
1249         for (i = 0; i < t->entry_count; i++) {
1250                 e = t->entries[i];
1251                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1252                         if (!slash1 || !S_ISDIR(e->versions[1].mode))
1253                                 goto del_entry;
1254                         if (!e->tree)
1255                                 load_tree(e);
1256                         if (tree_content_remove(e, slash1 + 1)) {
1257                                 for (n = 0; n < e->tree->entry_count; n++) {
1258                                         if (e->tree->entries[n]->versions[1].mode) {
1259                                                 hashclr(root->versions[1].sha1);
1260                                                 return 1;
1261                                         }
1262                                 }
1263                                 goto del_entry;
1264                         }
1265                         return 0;
1266                 }
1267         }
1268         return 0;
1269
1270 del_entry:
1271         if (e->tree) {
1272                 release_tree_content_recursive(e->tree);
1273                 e->tree = NULL;
1274         }
1275         e->versions[1].mode = 0;
1276         hashclr(e->versions[1].sha1);
1277         hashclr(root->versions[1].sha1);
1278         return 1;
1279 }
1280
1281 static void dump_branches(void)
1282 {
1283         static const char *msg = "fast-import";
1284         unsigned int i;
1285         struct branch *b;
1286         struct ref_lock *lock;
1287
1288         for (i = 0; i < branch_table_sz; i++) {
1289                 for (b = branch_table[i]; b; b = b->table_next_branch) {
1290                         lock = lock_any_ref_for_update(b->name, NULL);
1291                         if (!lock || write_ref_sha1(lock, b->sha1, msg) < 0)
1292                                 die("Can't write %s", b->name);
1293                 }
1294         }
1295 }
1296
1297 static void dump_tags(void)
1298 {
1299         static const char *msg = "fast-import";
1300         struct tag *t;
1301         struct ref_lock *lock;
1302         char path[PATH_MAX];
1303
1304         for (t = first_tag; t; t = t->next_tag) {
1305                 sprintf(path, "refs/tags/%s", t->name);
1306                 lock = lock_any_ref_for_update(path, NULL);
1307                 if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
1308                         die("Can't write %s", path);
1309         }
1310 }
1311
1312 static void dump_marks_helper(FILE *f,
1313         uintmax_t base,
1314         struct mark_set *m)
1315 {
1316         uintmax_t k;
1317         if (m->shift) {
1318                 for (k = 0; k < 1024; k++) {
1319                         if (m->data.sets[k])
1320                                 dump_marks_helper(f, (base + k) << m->shift,
1321                                         m->data.sets[k]);
1322                 }
1323         } else {
1324                 for (k = 0; k < 1024; k++) {
1325                         if (m->data.marked[k])
1326                                 fprintf(f, ":%ju %s\n", base + k,
1327                                         sha1_to_hex(m->data.marked[k]->sha1));
1328                 }
1329         }
1330 }
1331
1332 static void dump_marks(void)
1333 {
1334         if (mark_file)
1335         {
1336                 FILE *f = fopen(mark_file, "w");
1337                 dump_marks_helper(f, 0, marks);
1338                 fclose(f);
1339         }
1340 }
1341
1342 static void read_next_command(void)
1343 {
1344         read_line(&command_buf, stdin, '\n');
1345 }
1346
1347 static void cmd_mark(void)
1348 {
1349         if (!strncmp("mark :", command_buf.buf, 6)) {
1350                 next_mark = strtoumax(command_buf.buf + 6, NULL, 10);
1351                 read_next_command();
1352         }
1353         else
1354                 next_mark = 0;
1355 }
1356
1357 static void *cmd_data (size_t *size)
1358 {
1359         size_t length;
1360         char *buffer;
1361
1362         if (strncmp("data ", command_buf.buf, 5))
1363                 die("Expected 'data n' command, found: %s", command_buf.buf);
1364
1365         if (!strncmp("<<", command_buf.buf + 5, 2)) {
1366                 char *term = xstrdup(command_buf.buf + 5 + 2);
1367                 size_t sz = 8192, term_len = command_buf.len - 5 - 2;
1368                 length = 0;
1369                 buffer = xmalloc(sz);
1370                 for (;;) {
1371                         read_next_command();
1372                         if (command_buf.eof)
1373                                 die("EOF in data (terminator '%s' not found)", term);
1374                         if (term_len == command_buf.len
1375                                 && !strcmp(term, command_buf.buf))
1376                                 break;
1377                         if (sz < (length + command_buf.len)) {
1378                                 sz = sz * 3 / 2 + 16;
1379                                 if (sz < (length + command_buf.len))
1380                                         sz = length + command_buf.len;
1381                                 buffer = xrealloc(buffer, sz);
1382                         }
1383                         memcpy(buffer + length,
1384                                 command_buf.buf,
1385                                 command_buf.len - 1);
1386                         length += command_buf.len - 1;
1387                         buffer[length++] = '\n';
1388                 }
1389                 free(term);
1390         }
1391         else {
1392                 size_t n = 0;
1393                 length = strtoul(command_buf.buf + 5, NULL, 10);
1394                 buffer = xmalloc(length);
1395                 while (n < length) {
1396                         size_t s = fread(buffer + n, 1, length - n, stdin);
1397                         if (!s && feof(stdin))
1398                                 die("EOF in data (%lu bytes remaining)", length - n);
1399                         n += s;
1400                 }
1401         }
1402
1403         if (fgetc(stdin) != '\n')
1404                 die("An lf did not trail the binary data as expected.");
1405
1406         *size = length;
1407         return buffer;
1408 }
1409
1410 static int validate_raw_date(const char *src, char *result, int maxlen)
1411 {
1412         const char *orig_src = src;
1413         char *endp, sign;
1414
1415         strtoul(src, &endp, 10);
1416         if (endp == src || *endp != ' ')
1417                 return -1;
1418
1419         src = endp + 1;
1420         if (*src != '-' && *src != '+')
1421                 return -1;
1422         sign = *src;
1423
1424         strtoul(src + 1, &endp, 10);
1425         if (endp == src || *endp || (endp - orig_src) >= maxlen)
1426                 return -1;
1427
1428         strcpy(result, orig_src);
1429         return 0;
1430 }
1431
1432 static char *parse_ident(const char *buf)
1433 {
1434         const char *gt;
1435         size_t name_len;
1436         char *ident;
1437
1438         gt = strrchr(buf, '>');
1439         if (!gt)
1440                 die("Missing > in ident string: %s", buf);
1441         gt++;
1442         if (*gt != ' ')
1443                 die("Missing space after > in ident string: %s", buf);
1444         gt++;
1445         name_len = gt - buf;
1446         ident = xmalloc(name_len + 24);
1447         strncpy(ident, buf, name_len);
1448
1449         switch (whenspec) {
1450         case WHENSPEC_RAW:
1451                 if (validate_raw_date(gt, ident + name_len, 24) < 0)
1452                         die("Invalid raw date \"%s\" in ident: %s", gt, buf);
1453                 break;
1454         case WHENSPEC_RFC2822:
1455                 if (parse_date(gt, ident + name_len, 24) < 0)
1456                         die("Invalid rfc2822 date \"%s\" in ident: %s", gt, buf);
1457                 break;
1458         case WHENSPEC_NOW:
1459                 if (strcmp("now", gt))
1460                         die("Date in ident must be 'now': %s", buf);
1461                 datestamp(ident + name_len, 24);
1462                 break;
1463         }
1464
1465         return ident;
1466 }
1467
1468 static void cmd_new_blob(void)
1469 {
1470         size_t l;
1471         void *d;
1472
1473         read_next_command();
1474         cmd_mark();
1475         d = cmd_data(&l);
1476
1477         if (store_object(OBJ_BLOB, d, l, &last_blob, NULL, next_mark))
1478                 free(d);
1479 }
1480
1481 static void unload_one_branch(void)
1482 {
1483         while (cur_active_branches
1484                 && cur_active_branches >= max_active_branches) {
1485                 unsigned long min_commit = ULONG_MAX;
1486                 struct branch *e, *l = NULL, *p = NULL;
1487
1488                 for (e = active_branches; e; e = e->active_next_branch) {
1489                         if (e->last_commit < min_commit) {
1490                                 p = l;
1491                                 min_commit = e->last_commit;
1492                         }
1493                         l = e;
1494                 }
1495
1496                 if (p) {
1497                         e = p->active_next_branch;
1498                         p->active_next_branch = e->active_next_branch;
1499                 } else {
1500                         e = active_branches;
1501                         active_branches = e->active_next_branch;
1502                 }
1503                 e->active_next_branch = NULL;
1504                 if (e->branch_tree.tree) {
1505                         release_tree_content_recursive(e->branch_tree.tree);
1506                         e->branch_tree.tree = NULL;
1507                 }
1508                 cur_active_branches--;
1509         }
1510 }
1511
1512 static void load_branch(struct branch *b)
1513 {
1514         load_tree(&b->branch_tree);
1515         b->active_next_branch = active_branches;
1516         active_branches = b;
1517         cur_active_branches++;
1518         branch_load_count++;
1519 }
1520
1521 static void file_change_m(struct branch *b)
1522 {
1523         const char *p = command_buf.buf + 2;
1524         char *p_uq;
1525         const char *endp;
1526         struct object_entry *oe = oe;
1527         unsigned char sha1[20];
1528         uint16_t mode, inline_data = 0;
1529         char type[20];
1530
1531         p = get_mode(p, &mode);
1532         if (!p)
1533                 die("Corrupt mode: %s", command_buf.buf);
1534         switch (mode) {
1535         case S_IFREG | 0644:
1536         case S_IFREG | 0755:
1537         case S_IFLNK:
1538         case 0644:
1539         case 0755:
1540                 /* ok */
1541                 break;
1542         default:
1543                 die("Corrupt mode: %s", command_buf.buf);
1544         }
1545
1546         if (*p == ':') {
1547                 char *x;
1548                 oe = find_mark(strtoumax(p + 1, &x, 10));
1549                 hashcpy(sha1, oe->sha1);
1550                 p = x;
1551         } else if (!strncmp("inline", p, 6)) {
1552                 inline_data = 1;
1553                 p += 6;
1554         } else {
1555                 if (get_sha1_hex(p, sha1))
1556                         die("Invalid SHA1: %s", command_buf.buf);
1557                 oe = find_object(sha1);
1558                 p += 40;
1559         }
1560         if (*p++ != ' ')
1561                 die("Missing space after SHA1: %s", command_buf.buf);
1562
1563         p_uq = unquote_c_style(p, &endp);
1564         if (p_uq) {
1565                 if (*endp)
1566                         die("Garbage after path in: %s", command_buf.buf);
1567                 p = p_uq;
1568         }
1569
1570         if (inline_data) {
1571                 size_t l;
1572                 void *d;
1573                 if (!p_uq)
1574                         p = p_uq = xstrdup(p);
1575                 read_next_command();
1576                 d = cmd_data(&l);
1577                 if (store_object(OBJ_BLOB, d, l, &last_blob, sha1, 0))
1578                         free(d);
1579         } else if (oe) {
1580                 if (oe->type != OBJ_BLOB)
1581                         die("Not a blob (actually a %s): %s",
1582                                 command_buf.buf, type_names[oe->type]);
1583         } else {
1584                 if (sha1_object_info(sha1, type, NULL))
1585                         die("Blob not found: %s", command_buf.buf);
1586                 if (strcmp(blob_type, type))
1587                         die("Not a blob (actually a %s): %s",
1588                                 command_buf.buf, type);
1589         }
1590
1591         tree_content_set(&b->branch_tree, p, sha1, S_IFREG | mode);
1592         free(p_uq);
1593 }
1594
1595 static void file_change_d(struct branch *b)
1596 {
1597         const char *p = command_buf.buf + 2;
1598         char *p_uq;
1599         const char *endp;
1600
1601         p_uq = unquote_c_style(p, &endp);
1602         if (p_uq) {
1603                 if (*endp)
1604                         die("Garbage after path in: %s", command_buf.buf);
1605                 p = p_uq;
1606         }
1607         tree_content_remove(&b->branch_tree, p);
1608         free(p_uq);
1609 }
1610
1611 static void cmd_from(struct branch *b)
1612 {
1613         const char *from;
1614         struct branch *s;
1615
1616         if (strncmp("from ", command_buf.buf, 5))
1617                 return;
1618
1619         if (b->last_commit)
1620                 die("Can't reinitailize branch %s", b->name);
1621
1622         from = strchr(command_buf.buf, ' ') + 1;
1623         s = lookup_branch(from);
1624         if (b == s)
1625                 die("Can't create a branch from itself: %s", b->name);
1626         else if (s) {
1627                 unsigned char *t = s->branch_tree.versions[1].sha1;
1628                 hashcpy(b->sha1, s->sha1);
1629                 hashcpy(b->branch_tree.versions[0].sha1, t);
1630                 hashcpy(b->branch_tree.versions[1].sha1, t);
1631         } else if (*from == ':') {
1632                 uintmax_t idnum = strtoumax(from + 1, NULL, 10);
1633                 struct object_entry *oe = find_mark(idnum);
1634                 unsigned long size;
1635                 char *buf;
1636                 if (oe->type != OBJ_COMMIT)
1637                         die("Mark :%ju not a commit", idnum);
1638                 hashcpy(b->sha1, oe->sha1);
1639                 buf = gfi_unpack_entry(oe, &size);
1640                 if (!buf || size < 46)
1641                         die("Not a valid commit: %s", from);
1642                 if (memcmp("tree ", buf, 5)
1643                         || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
1644                         die("The commit %s is corrupt", sha1_to_hex(b->sha1));
1645                 free(buf);
1646                 hashcpy(b->branch_tree.versions[0].sha1,
1647                         b->branch_tree.versions[1].sha1);
1648         } else if (!get_sha1(from, b->sha1)) {
1649                 if (is_null_sha1(b->sha1)) {
1650                         hashclr(b->branch_tree.versions[0].sha1);
1651                         hashclr(b->branch_tree.versions[1].sha1);
1652                 } else {
1653                         unsigned long size;
1654                         char *buf;
1655
1656                         buf = read_object_with_reference(b->sha1,
1657                                 type_names[OBJ_COMMIT], &size, b->sha1);
1658                         if (!buf || size < 46)
1659                                 die("Not a valid commit: %s", from);
1660                         if (memcmp("tree ", buf, 5)
1661                                 || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
1662                                 die("The commit %s is corrupt", sha1_to_hex(b->sha1));
1663                         free(buf);
1664                         hashcpy(b->branch_tree.versions[0].sha1,
1665                                 b->branch_tree.versions[1].sha1);
1666                 }
1667         } else
1668                 die("Invalid ref name or SHA1 expression: %s", from);
1669
1670         read_next_command();
1671 }
1672
1673 static struct hash_list *cmd_merge(unsigned int *count)
1674 {
1675         struct hash_list *list = NULL, *n, *e = e;
1676         const char *from;
1677         struct branch *s;
1678
1679         *count = 0;
1680         while (!strncmp("merge ", command_buf.buf, 6)) {
1681                 from = strchr(command_buf.buf, ' ') + 1;
1682                 n = xmalloc(sizeof(*n));
1683                 s = lookup_branch(from);
1684                 if (s)
1685                         hashcpy(n->sha1, s->sha1);
1686                 else if (*from == ':') {
1687                         uintmax_t idnum = strtoumax(from + 1, NULL, 10);
1688                         struct object_entry *oe = find_mark(idnum);
1689                         if (oe->type != OBJ_COMMIT)
1690                                 die("Mark :%ju not a commit", idnum);
1691                         hashcpy(n->sha1, oe->sha1);
1692                 } else if (get_sha1(from, n->sha1))
1693                         die("Invalid ref name or SHA1 expression: %s", from);
1694
1695                 n->next = NULL;
1696                 if (list)
1697                         e->next = n;
1698                 else
1699                         list = n;
1700                 e = n;
1701                 (*count)++;
1702                 read_next_command();
1703         }
1704         return list;
1705 }
1706
1707 static void cmd_new_commit(void)
1708 {
1709         struct branch *b;
1710         void *msg;
1711         size_t msglen;
1712         char *sp;
1713         char *author = NULL;
1714         char *committer = NULL;
1715         struct hash_list *merge_list = NULL;
1716         unsigned int merge_count;
1717
1718         /* Obtain the branch name from the rest of our command */
1719         sp = strchr(command_buf.buf, ' ') + 1;
1720         b = lookup_branch(sp);
1721         if (!b)
1722                 b = new_branch(sp);
1723
1724         read_next_command();
1725         cmd_mark();
1726         if (!strncmp("author ", command_buf.buf, 7)) {
1727                 author = parse_ident(command_buf.buf + 7);
1728                 read_next_command();
1729         }
1730         if (!strncmp("committer ", command_buf.buf, 10)) {
1731                 committer = parse_ident(command_buf.buf + 10);
1732                 read_next_command();
1733         }
1734         if (!committer)
1735                 die("Expected committer but didn't get one");
1736         msg = cmd_data(&msglen);
1737         read_next_command();
1738         cmd_from(b);
1739         merge_list = cmd_merge(&merge_count);
1740
1741         /* ensure the branch is active/loaded */
1742         if (!b->branch_tree.tree || !max_active_branches) {
1743                 unload_one_branch();
1744                 load_branch(b);
1745         }
1746
1747         /* file_change* */
1748         for (;;) {
1749                 if (1 == command_buf.len)
1750                         break;
1751                 else if (!strncmp("M ", command_buf.buf, 2))
1752                         file_change_m(b);
1753                 else if (!strncmp("D ", command_buf.buf, 2))
1754                         file_change_d(b);
1755                 else
1756                         die("Unsupported file_change: %s", command_buf.buf);
1757                 read_next_command();
1758         }
1759
1760         /* build the tree and the commit */
1761         store_tree(&b->branch_tree);
1762         hashcpy(b->branch_tree.versions[0].sha1,
1763                 b->branch_tree.versions[1].sha1);
1764         size_dbuf(&new_data, 114 + msglen
1765                 + merge_count * 49
1766                 + (author
1767                         ? strlen(author) + strlen(committer)
1768                         : 2 * strlen(committer)));
1769         sp = new_data.buffer;
1770         sp += sprintf(sp, "tree %s\n",
1771                 sha1_to_hex(b->branch_tree.versions[1].sha1));
1772         if (!is_null_sha1(b->sha1))
1773                 sp += sprintf(sp, "parent %s\n", sha1_to_hex(b->sha1));
1774         while (merge_list) {
1775                 struct hash_list *next = merge_list->next;
1776                 sp += sprintf(sp, "parent %s\n", sha1_to_hex(merge_list->sha1));
1777                 free(merge_list);
1778                 merge_list = next;
1779         }
1780         sp += sprintf(sp, "author %s\n", author ? author : committer);
1781         sp += sprintf(sp, "committer %s\n", committer);
1782         *sp++ = '\n';
1783         memcpy(sp, msg, msglen);
1784         sp += msglen;
1785         free(author);
1786         free(committer);
1787         free(msg);
1788
1789         if (!store_object(OBJ_COMMIT,
1790                 new_data.buffer, sp - (char*)new_data.buffer,
1791                 NULL, b->sha1, next_mark))
1792                 b->pack_id = pack_id;
1793         b->last_commit = object_count_by_type[OBJ_COMMIT];
1794 }
1795
1796 static void cmd_new_tag(void)
1797 {
1798         char *sp;
1799         const char *from;
1800         char *tagger;
1801         struct branch *s;
1802         void *msg;
1803         size_t msglen;
1804         struct tag *t;
1805         uintmax_t from_mark = 0;
1806         unsigned char sha1[20];
1807
1808         /* Obtain the new tag name from the rest of our command */
1809         sp = strchr(command_buf.buf, ' ') + 1;
1810         t = pool_alloc(sizeof(struct tag));
1811         t->next_tag = NULL;
1812         t->name = pool_strdup(sp);
1813         if (last_tag)
1814                 last_tag->next_tag = t;
1815         else
1816                 first_tag = t;
1817         last_tag = t;
1818         read_next_command();
1819
1820         /* from ... */
1821         if (strncmp("from ", command_buf.buf, 5))
1822                 die("Expected from command, got %s", command_buf.buf);
1823         from = strchr(command_buf.buf, ' ') + 1;
1824         s = lookup_branch(from);
1825         if (s) {
1826                 hashcpy(sha1, s->sha1);
1827         } else if (*from == ':') {
1828                 struct object_entry *oe;
1829                 from_mark = strtoumax(from + 1, NULL, 10);
1830                 oe = find_mark(from_mark);
1831                 if (oe->type != OBJ_COMMIT)
1832                         die("Mark :%ju not a commit", from_mark);
1833                 hashcpy(sha1, oe->sha1);
1834         } else if (!get_sha1(from, sha1)) {
1835                 unsigned long size;
1836                 char *buf;
1837
1838                 buf = read_object_with_reference(sha1,
1839                         type_names[OBJ_COMMIT], &size, sha1);
1840                 if (!buf || size < 46)
1841                         die("Not a valid commit: %s", from);
1842                 free(buf);
1843         } else
1844                 die("Invalid ref name or SHA1 expression: %s", from);
1845         read_next_command();
1846
1847         /* tagger ... */
1848         if (strncmp("tagger ", command_buf.buf, 7))
1849                 die("Expected tagger command, got %s", command_buf.buf);
1850         tagger = parse_ident(command_buf.buf + 7);
1851
1852         /* tag payload/message */
1853         read_next_command();
1854         msg = cmd_data(&msglen);
1855
1856         /* build the tag object */
1857         size_dbuf(&new_data, 67+strlen(t->name)+strlen(tagger)+msglen);
1858         sp = new_data.buffer;
1859         sp += sprintf(sp, "object %s\n", sha1_to_hex(sha1));
1860         sp += sprintf(sp, "type %s\n", type_names[OBJ_COMMIT]);
1861         sp += sprintf(sp, "tag %s\n", t->name);
1862         sp += sprintf(sp, "tagger %s\n", tagger);
1863         *sp++ = '\n';
1864         memcpy(sp, msg, msglen);
1865         sp += msglen;
1866         free(tagger);
1867         free(msg);
1868
1869         if (store_object(OBJ_TAG, new_data.buffer,
1870                 sp - (char*)new_data.buffer,
1871                 NULL, t->sha1, 0))
1872                 t->pack_id = MAX_PACK_ID;
1873         else
1874                 t->pack_id = pack_id;
1875 }
1876
1877 static void cmd_reset_branch(void)
1878 {
1879         struct branch *b;
1880         char *sp;
1881
1882         /* Obtain the branch name from the rest of our command */
1883         sp = strchr(command_buf.buf, ' ') + 1;
1884         b = lookup_branch(sp);
1885         if (b) {
1886                 b->last_commit = 0;
1887                 if (b->branch_tree.tree) {
1888                         release_tree_content_recursive(b->branch_tree.tree);
1889                         b->branch_tree.tree = NULL;
1890                 }
1891         }
1892         else
1893                 b = new_branch(sp);
1894         read_next_command();
1895         cmd_from(b);
1896 }
1897
1898 static void cmd_checkpoint(void)
1899 {
1900         if (object_count)
1901                 checkpoint();
1902         read_next_command();
1903 }
1904
1905 static const char fast_import_usage[] =
1906 "git-fast-import [--date-format=f] [--max-pack-size=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file]";
1907
1908 int main(int argc, const char **argv)
1909 {
1910         int i;
1911         uintmax_t total_count, duplicate_count;
1912
1913         git_config(git_default_config);
1914
1915         for (i = 1; i < argc; i++) {
1916                 const char *a = argv[i];
1917
1918                 if (*a != '-' || !strcmp(a, "--"))
1919                         break;
1920                 else if (!strncmp(a, "--date-format=", 14)) {
1921                         const char *fmt = a + 14;
1922                         if (!strcmp(fmt, "raw"))
1923                                 whenspec = WHENSPEC_RAW;
1924                         else if (!strcmp(fmt, "rfc2822"))
1925                                 whenspec = WHENSPEC_RFC2822;
1926                         else if (!strcmp(fmt, "now"))
1927                                 whenspec = WHENSPEC_NOW;
1928                         else
1929                                 die("unknown --date-format argument %s", fmt);
1930                 }
1931                 else if (!strncmp(a, "--max-pack-size=", 16))
1932                         max_packsize = strtoumax(a + 16, NULL, 0) * 1024 * 1024;
1933                 else if (!strncmp(a, "--depth=", 8))
1934                         max_depth = strtoul(a + 8, NULL, 0);
1935                 else if (!strncmp(a, "--active-branches=", 18))
1936                         max_active_branches = strtoul(a + 18, NULL, 0);
1937                 else if (!strncmp(a, "--export-marks=", 15))
1938                         mark_file = a + 15;
1939                 else
1940                         die("unknown option %s", a);
1941         }
1942         if (i != argc)
1943                 usage(fast_import_usage);
1944
1945         alloc_objects(object_entry_alloc);
1946         strbuf_init(&command_buf);
1947
1948         atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
1949         branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
1950         avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
1951         marks = pool_calloc(1, sizeof(struct mark_set));
1952
1953         start_packfile();
1954         for (;;) {
1955                 read_next_command();
1956                 if (command_buf.eof)
1957                         break;
1958                 else if (!strcmp("blob", command_buf.buf))
1959                         cmd_new_blob();
1960                 else if (!strncmp("commit ", command_buf.buf, 7))
1961                         cmd_new_commit();
1962                 else if (!strncmp("tag ", command_buf.buf, 4))
1963                         cmd_new_tag();
1964                 else if (!strncmp("reset ", command_buf.buf, 6))
1965                         cmd_reset_branch();
1966                 else if (!strcmp("checkpoint", command_buf.buf))
1967                         cmd_checkpoint();
1968                 else
1969                         die("Unsupported command: %s", command_buf.buf);
1970         }
1971         end_packfile();
1972
1973         dump_branches();
1974         dump_tags();
1975         unkeep_all_packs();
1976         dump_marks();
1977
1978         total_count = 0;
1979         for (i = 0; i < ARRAY_SIZE(object_count_by_type); i++)
1980                 total_count += object_count_by_type[i];
1981         duplicate_count = 0;
1982         for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
1983                 duplicate_count += duplicate_count_by_type[i];
1984
1985         fprintf(stderr, "%s statistics:\n", argv[0]);
1986         fprintf(stderr, "---------------------------------------------------------------------\n");
1987         fprintf(stderr, "Alloc'd objects: %10ju\n", alloc_count);
1988         fprintf(stderr, "Total objects:   %10ju (%10ju duplicates                  )\n", total_count, duplicate_count);
1989         fprintf(stderr, "      blobs  :   %10ju (%10ju duplicates %10ju deltas)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB]);
1990         fprintf(stderr, "      trees  :   %10ju (%10ju duplicates %10ju deltas)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE]);
1991         fprintf(stderr, "      commits:   %10ju (%10ju duplicates %10ju deltas)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT]);
1992         fprintf(stderr, "      tags   :   %10ju (%10ju duplicates %10ju deltas)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG]);
1993         fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
1994         fprintf(stderr, "      marks:     %10ju (%10ju unique    )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
1995         fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
1996         fprintf(stderr, "Memory total:    %10ju KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
1997         fprintf(stderr, "       pools:    %10lu KiB\n", total_allocd/1024);
1998         fprintf(stderr, "     objects:    %10ju KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
1999         fprintf(stderr, "---------------------------------------------------------------------\n");
2000         pack_report();
2001         fprintf(stderr, "---------------------------------------------------------------------\n");
2002         fprintf(stderr, "\n");
2003
2004         return 0;
2005 }