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