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