Code

Implemented automatic checkpoints within fast-import.
[git.git] / fast-import.c
1 /*
2 Format of STDIN stream:
4   stream ::= cmd*;
6   cmd ::= new_blob
7         | new_commit
8         | new_tag
9         | reset_branch
10         ;
12   new_blob ::= 'blob' lf
13         mark?
14     file_content;
15   file_content ::= data;
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;
28   file_change ::= 'M' sp mode sp (hexsha1 | idnum) sp path_str lf
29                 | 'D' sp path_str lf
30                 ;
31   mode ::= '644' | '755';
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;
39   reset_branch ::= 'reset' sp ref_str lf
40     ('from' sp (ref_str | hexsha1 | sha1exp_str | idnum) lf)?
41     lf;
43   checkpoint ::= 'checkpoint' lf
44     lf;
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;
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;
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)    '"' ;
74   declen ::= # unsigned 32 bit value, ascii base10 notation;
75   binary_data ::= # file content, not interpreted;
77   sp ::= # ASCII space character;
78   lf ::= # ASCII newline (LF) character;
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;
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 */
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"
113 struct object_entry
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 };
122 struct object_entry_pool
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 };
130 struct mark_set
132         int shift;
133         union {
134                 struct object_entry *marked[1024];
135                 struct mark_set *sets[1024];
136         } data;
137 };
139 struct last_object
141         void *data;
142         unsigned long len;
143         unsigned long offset;
144         unsigned int depth;
145         unsigned no_free:1;
146 };
148 struct mem_pool
150         struct mem_pool *next_pool;
151         char *next_free;
152         char *end;
153         char space[FLEX_ARRAY]; /* more */
154 };
156 struct atom_str
158         struct atom_str *next_atom;
159         int str_len;
160         char str_dat[FLEX_ARRAY]; /* more */
161 };
163 struct tree_content;
164 struct tree_entry
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 };
175 struct tree_content
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 };
183 struct avail_tree_content
185         unsigned int entry_capacity; /* must match tree_content */
186         struct avail_tree_content *next_avail;
187 };
189 struct branch
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 };
199 struct tag
201         struct tag *next_tag;
202         const char *name;
203         unsigned char sha1[20];
204 };
206 struct dbuf
208         void *buffer;
209         size_t capacity;
210 };
212 struct hash_list
214         struct hash_list *next;
215         unsigned char sha1[20];
216 };
218 /* Stats and misc. counters */
219 static unsigned long max_depth = 10;
220 static unsigned long max_objects = -1;
221 static unsigned long max_packsize = -1;
222 static unsigned long alloc_count;
223 static unsigned long branch_count;
224 static unsigned long branch_load_count;
225 static unsigned long object_count;
226 static unsigned long marks_set_count;
227 static unsigned long object_count_by_type[1 << TYPE_BITS];
228 static unsigned long duplicate_count_by_type[1 << TYPE_BITS];
229 static unsigned long delta_count_by_type[1 << TYPE_BITS];
231 /* Memory pools */
232 static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
233 static size_t total_allocd;
234 static struct mem_pool *mem_pool;
236 /* Atom management */
237 static unsigned int atom_table_sz = 4451;
238 static unsigned int atom_cnt;
239 static struct atom_str **atom_table;
241 /* The .pack file being generated */
242 static const char *base_name;
243 static unsigned int pack_id;
244 static char *idx_name;
245 static struct packed_git *pack_data;
246 static struct packed_git **all_packs;
247 static int pack_fd;
248 static unsigned long pack_size;
249 static unsigned char pack_sha1[20];
251 /* Table of objects we've written. */
252 static unsigned int object_entry_alloc = 5000;
253 static struct object_entry_pool *blocks;
254 static struct object_entry *object_table[1 << 16];
255 static struct mark_set *marks;
256 static const char* mark_file;
258 /* Our last blob */
259 static struct last_object last_blob;
261 /* Tree management */
262 static unsigned int tree_entry_alloc = 1000;
263 static void *avail_tree_entry;
264 static unsigned int avail_tree_table_sz = 100;
265 static struct avail_tree_content **avail_tree_table;
266 static struct dbuf old_tree;
267 static struct dbuf new_tree;
269 /* Branch data */
270 static unsigned long max_active_branches = 5;
271 static unsigned long cur_active_branches;
272 static unsigned long branch_table_sz = 1039;
273 static struct branch **branch_table;
274 static struct branch *active_branches;
276 /* Tag data */
277 static struct tag *first_tag;
278 static struct tag *last_tag;
280 /* Input stream parsing */
281 static struct strbuf command_buf;
282 static unsigned long next_mark;
283 static struct dbuf new_data;
284 static FILE* branch_log;
287 static void alloc_objects(unsigned int cnt)
289         struct object_entry_pool *b;
291         b = xmalloc(sizeof(struct object_entry_pool)
292                 + cnt * sizeof(struct object_entry));
293         b->next_pool = blocks;
294         b->next_free = b->entries;
295         b->end = b->entries + cnt;
296         blocks = b;
297         alloc_count += cnt;
300 static struct object_entry* new_object(unsigned char *sha1)
302         struct object_entry *e;
304         if (blocks->next_free == blocks->end)
305                 alloc_objects(object_entry_alloc);
307         e = blocks->next_free++;
308         hashcpy(e->sha1, sha1);
309         return e;
312 static struct object_entry* find_object(unsigned char *sha1)
314         unsigned int h = sha1[0] << 8 | sha1[1];
315         struct object_entry *e;
316         for (e = object_table[h]; e; e = e->next)
317                 if (!hashcmp(sha1, e->sha1))
318                         return e;
319         return NULL;
322 static struct object_entry* insert_object(unsigned char *sha1)
324         unsigned int h = sha1[0] << 8 | sha1[1];
325         struct object_entry *e = object_table[h];
326         struct object_entry *p = NULL;
328         while (e) {
329                 if (!hashcmp(sha1, e->sha1))
330                         return e;
331                 p = e;
332                 e = e->next;
333         }
335         e = new_object(sha1);
336         e->next = NULL;
337         e->offset = 0;
338         if (p)
339                 p->next = e;
340         else
341                 object_table[h] = e;
342         return e;
345 static unsigned int hc_str(const char *s, size_t len)
347         unsigned int r = 0;
348         while (len-- > 0)
349                 r = r * 31 + *s++;
350         return r;
353 static void* pool_alloc(size_t len)
355         struct mem_pool *p;
356         void *r;
358         for (p = mem_pool; p; p = p->next_pool)
359                 if ((p->end - p->next_free >= len))
360                         break;
362         if (!p) {
363                 if (len >= (mem_pool_alloc/2)) {
364                         total_allocd += len;
365                         return xmalloc(len);
366                 }
367                 total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
368                 p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc);
369                 p->next_pool = mem_pool;
370                 p->next_free = p->space;
371                 p->end = p->next_free + mem_pool_alloc;
372                 mem_pool = p;
373         }
375         r = p->next_free;
376         /* round out to a pointer alignment */
377         if (len & (sizeof(void*) - 1))
378                 len += sizeof(void*) - (len & (sizeof(void*) - 1));
379         p->next_free += len;
380         return r;
383 static void* pool_calloc(size_t count, size_t size)
385         size_t len = count * size;
386         void *r = pool_alloc(len);
387         memset(r, 0, len);
388         return r;
391 static char* pool_strdup(const char *s)
393         char *r = pool_alloc(strlen(s) + 1);
394         strcpy(r, s);
395         return r;
398 static void size_dbuf(struct dbuf *b, size_t maxlen)
400         if (b->buffer) {
401                 if (b->capacity >= maxlen)
402                         return;
403                 free(b->buffer);
404         }
405         b->capacity = ((maxlen / 1024) + 1) * 1024;
406         b->buffer = xmalloc(b->capacity);
409 static void insert_mark(unsigned long idnum, struct object_entry *oe)
411         struct mark_set *s = marks;
412         while ((idnum >> s->shift) >= 1024) {
413                 s = pool_calloc(1, sizeof(struct mark_set));
414                 s->shift = marks->shift + 10;
415                 s->data.sets[0] = marks;
416                 marks = s;
417         }
418         while (s->shift) {
419                 unsigned long i = idnum >> s->shift;
420                 idnum -= i << s->shift;
421                 if (!s->data.sets[i]) {
422                         s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
423                         s->data.sets[i]->shift = s->shift - 10;
424                 }
425                 s = s->data.sets[i];
426         }
427         if (!s->data.marked[idnum])
428                 marks_set_count++;
429         s->data.marked[idnum] = oe;
432 static struct object_entry* find_mark(unsigned long idnum)
434         unsigned long orig_idnum = idnum;
435         struct mark_set *s = marks;
436         struct object_entry *oe = NULL;
437         if ((idnum >> s->shift) < 1024) {
438                 while (s && s->shift) {
439                         unsigned long i = idnum >> s->shift;
440                         idnum -= i << s->shift;
441                         s = s->data.sets[i];
442                 }
443                 if (s)
444                         oe = s->data.marked[idnum];
445         }
446         if (!oe)
447                 die("mark :%lu not declared", orig_idnum);
448         return oe;
451 static struct atom_str* to_atom(const char *s, size_t len)
453         unsigned int hc = hc_str(s, len) % atom_table_sz;
454         struct atom_str *c;
456         for (c = atom_table[hc]; c; c = c->next_atom)
457                 if (c->str_len == len && !strncmp(s, c->str_dat, len))
458                         return c;
460         c = pool_alloc(sizeof(struct atom_str) + len + 1);
461         c->str_len = len;
462         strncpy(c->str_dat, s, len);
463         c->str_dat[len] = 0;
464         c->next_atom = atom_table[hc];
465         atom_table[hc] = c;
466         atom_cnt++;
467         return c;
470 static struct branch* lookup_branch(const char *name)
472         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
473         struct branch *b;
475         for (b = branch_table[hc]; b; b = b->table_next_branch)
476                 if (!strcmp(name, b->name))
477                         return b;
478         return NULL;
481 static struct branch* new_branch(const char *name)
483         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
484         struct branch* b = lookup_branch(name);
486         if (b)
487                 die("Invalid attempt to create duplicate branch: %s", name);
488         if (check_ref_format(name))
489                 die("Branch name doesn't conform to GIT standards: %s", name);
491         b = pool_calloc(1, sizeof(struct branch));
492         b->name = pool_strdup(name);
493         b->table_next_branch = branch_table[hc];
494         b->branch_tree.versions[0].mode = S_IFDIR;
495         b->branch_tree.versions[1].mode = S_IFDIR;
496         branch_table[hc] = b;
497         branch_count++;
498         return b;
501 static unsigned int hc_entries(unsigned int cnt)
503         cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
504         return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
507 static struct tree_content* new_tree_content(unsigned int cnt)
509         struct avail_tree_content *f, *l = NULL;
510         struct tree_content *t;
511         unsigned int hc = hc_entries(cnt);
513         for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
514                 if (f->entry_capacity >= cnt)
515                         break;
517         if (f) {
518                 if (l)
519                         l->next_avail = f->next_avail;
520                 else
521                         avail_tree_table[hc] = f->next_avail;
522         } else {
523                 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
524                 f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
525                 f->entry_capacity = cnt;
526         }
528         t = (struct tree_content*)f;
529         t->entry_count = 0;
530         t->delta_depth = 0;
531         return t;
534 static void release_tree_entry(struct tree_entry *e);
535 static void release_tree_content(struct tree_content *t)
537         struct avail_tree_content *f = (struct avail_tree_content*)t;
538         unsigned int hc = hc_entries(f->entry_capacity);
539         f->next_avail = avail_tree_table[hc];
540         avail_tree_table[hc] = f;
543 static void release_tree_content_recursive(struct tree_content *t)
545         unsigned int i;
546         for (i = 0; i < t->entry_count; i++)
547                 release_tree_entry(t->entries[i]);
548         release_tree_content(t);
551 static struct tree_content* grow_tree_content(
552         struct tree_content *t,
553         int amt)
555         struct tree_content *r = new_tree_content(t->entry_count + amt);
556         r->entry_count = t->entry_count;
557         r->delta_depth = t->delta_depth;
558         memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
559         release_tree_content(t);
560         return r;
563 static struct tree_entry* new_tree_entry()
565         struct tree_entry *e;
567         if (!avail_tree_entry) {
568                 unsigned int n = tree_entry_alloc;
569                 total_allocd += n * sizeof(struct tree_entry);
570                 avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry));
571                 while (n-- > 1) {
572                         *((void**)e) = e + 1;
573                         e++;
574                 }
575                 *((void**)e) = NULL;
576         }
578         e = avail_tree_entry;
579         avail_tree_entry = *((void**)e);
580         return e;
583 static void release_tree_entry(struct tree_entry *e)
585         if (e->tree)
586                 release_tree_content_recursive(e->tree);
587         *((void**)e) = avail_tree_entry;
588         avail_tree_entry = e;
591 static void yread(int fd, void *buffer, size_t length)
593         ssize_t ret = 0;
594         while (ret < length) {
595                 ssize_t size = xread(fd, (char *) buffer + ret, length - ret);
596                 if (!size)
597                         die("Read from descriptor %i: end of stream", fd);
598                 if (size < 0)
599                         die("Read from descriptor %i: %s", fd, strerror(errno));
600                 ret += size;
601         }
604 static void start_packfile()
606         struct packed_git *p;
607         struct pack_header hdr;
609         idx_name = xmalloc(strlen(base_name) + 11);
610         p = xcalloc(1, sizeof(*p) + strlen(base_name) + 13);
611         sprintf(p->pack_name, "%s%5.5i.pack", base_name, pack_id + 1);
612         sprintf(idx_name, "%s%5.5i.idx", base_name, pack_id + 1);
614         pack_fd = open(p->pack_name, O_RDWR|O_CREAT|O_EXCL, 0666);
615         if (pack_fd < 0)
616                 die("Can't create %s: %s", p->pack_name, strerror(errno));
617         p->pack_fd = pack_fd;
619         hdr.hdr_signature = htonl(PACK_SIGNATURE);
620         hdr.hdr_version = htonl(2);
621         hdr.hdr_entries = 0;
622         write_or_die(pack_fd, &hdr, sizeof(hdr));
624         pack_data = p;
625         pack_size = sizeof(hdr);
626         object_count = 0;
628         all_packs = xrealloc(all_packs, sizeof(*all_packs) * (pack_id + 1));
629         all_packs[pack_id] = p;
632 static void fixup_header_footer()
634         SHA_CTX c;
635         char hdr[8];
636         unsigned long cnt;
637         char *buf;
639         if (lseek(pack_fd, 0, SEEK_SET) != 0)
640                 die("Failed seeking to start: %s", strerror(errno));
642         SHA1_Init(&c);
643         yread(pack_fd, hdr, 8);
644         SHA1_Update(&c, hdr, 8);
646         cnt = htonl(object_count);
647         SHA1_Update(&c, &cnt, 4);
648         write_or_die(pack_fd, &cnt, 4);
650         buf = xmalloc(128 * 1024);
651         for (;;) {
652                 size_t n = xread(pack_fd, buf, 128 * 1024);
653                 if (n <= 0)
654                         break;
655                 SHA1_Update(&c, buf, n);
656         }
657         free(buf);
659         SHA1_Final(pack_sha1, &c);
660         write_or_die(pack_fd, pack_sha1, sizeof(pack_sha1));
663 static int oecmp (const void *a_, const void *b_)
665         struct object_entry *a = *((struct object_entry**)a_);
666         struct object_entry *b = *((struct object_entry**)b_);
667         return hashcmp(a->sha1, b->sha1);
670 static void write_index(const char *idx_name)
672         struct sha1file *f;
673         struct object_entry **idx, **c, **last, *e;
674         struct object_entry_pool *o;
675         unsigned int array[256];
676         int i;
678         /* Build the sorted table of object IDs. */
679         idx = xmalloc(object_count * sizeof(struct object_entry*));
680         c = idx;
681         for (o = blocks; o; o = o->next_pool)
682                 for (e = o->next_free; e-- != o->entries;)
683                         if (pack_id == e->pack_id)
684                                 *c++ = e;
685         last = idx + object_count;
686         if (c != last)
687                 die("internal consistency error creating the index");
688         qsort(idx, object_count, sizeof(struct object_entry*), oecmp);
690         /* Generate the fan-out array. */
691         c = idx;
692         for (i = 0; i < 256; i++) {
693                 struct object_entry **next = c;;
694                 while (next < last) {
695                         if ((*next)->sha1[0] != i)
696                                 break;
697                         next++;
698                 }
699                 array[i] = htonl(next - idx);
700                 c = next;
701         }
703         f = sha1create("%s", idx_name);
704         sha1write(f, array, 256 * sizeof(int));
705         for (c = idx; c != last; c++) {
706                 unsigned int offset = htonl((*c)->offset);
707                 sha1write(f, &offset, 4);
708                 sha1write(f, (*c)->sha1, sizeof((*c)->sha1));
709         }
710         sha1write(f, pack_sha1, sizeof(pack_sha1));
711         sha1close(f, NULL, 1);
712         free(idx);
715 static void end_packfile()
717         struct packed_git *old_p = pack_data, *new_p;
719         if (object_count) {
720                 fixup_header_footer();
721                 write_index(idx_name);
723                 /* Register the packfile with core git's machinary. */
724                 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
725                 if (!new_p)
726                         die("core git rejected index %s", idx_name);
727                 new_p->windows = old_p->windows;
728                 new_p->pack_fd = old_p->pack_fd;
729                 all_packs[pack_id++] = new_p;
730                 install_packed_git(new_p);
731         }
732         else {
733                 close(pack_fd);
734                 unlink(old_p->pack_name);
735         }
736         free(old_p);
737         free(idx_name);
739         /* We can't carry a delta across packfiles. */
740         free(last_blob.data);
741         last_blob.data = NULL;
742         last_blob.len = 0;
743         last_blob.offset = 0;
744         last_blob.depth = 0;
747 static void checkpoint()
749         end_packfile();
750         start_packfile();
753 static size_t encode_header(
754         enum object_type type,
755         size_t size,
756         unsigned char *hdr)
758         int n = 1;
759         unsigned char c;
761         if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
762                 die("bad type %d", type);
764         c = (type << 4) | (size & 15);
765         size >>= 4;
766         while (size) {
767                 *hdr++ = c | 0x80;
768                 c = size & 0x7f;
769                 size >>= 7;
770                 n++;
771         }
772         *hdr = c;
773         return n;
776 static int store_object(
777         enum object_type type,
778         void *dat,
779         size_t datlen,
780         struct last_object *last,
781         unsigned char *sha1out,
782         unsigned long mark)
784         void *out, *delta;
785         struct object_entry *e;
786         unsigned char hdr[96];
787         unsigned char sha1[20];
788         unsigned long hdrlen, deltalen;
789         SHA_CTX c;
790         z_stream s;
792         hdrlen = sprintf((char*)hdr,"%s %lu",type_names[type],datlen) + 1;
793         SHA1_Init(&c);
794         SHA1_Update(&c, hdr, hdrlen);
795         SHA1_Update(&c, dat, datlen);
796         SHA1_Final(sha1, &c);
797         if (sha1out)
798                 hashcpy(sha1out, sha1);
800         e = insert_object(sha1);
801         if (mark)
802                 insert_mark(mark, e);
803         if (e->offset) {
804                 duplicate_count_by_type[type]++;
805                 return 1;
806         }
808         if (last && last->data && last->depth < max_depth) {
809                 delta = diff_delta(last->data, last->len,
810                         dat, datlen,
811                         &deltalen, 0);
812                 if (delta && deltalen >= datlen) {
813                         free(delta);
814                         delta = NULL;
815                 }
816         } else
817                 delta = NULL;
819         memset(&s, 0, sizeof(s));
820         deflateInit(&s, zlib_compression_level);
821         if (delta) {
822                 s.next_in = delta;
823                 s.avail_in = deltalen;
824         } else {
825                 s.next_in = dat;
826                 s.avail_in = datlen;
827         }
828         s.avail_out = deflateBound(&s, s.avail_in);
829         s.next_out = out = xmalloc(s.avail_out);
830         while (deflate(&s, Z_FINISH) == Z_OK)
831                 /* nothing */;
832         deflateEnd(&s);
834         /* Determine if we should auto-checkpoint. */
835         if ((object_count + 1) > max_objects
836                 || (object_count + 1) < object_count
837                 || (pack_size + 60 + s.total_out) > max_packsize
838                 || (pack_size + 60 + s.total_out) < pack_size) {
840                 /* This new object needs to *not* have the current pack_id. */
841                 e->pack_id = pack_id + 1;
842                 checkpoint();
844                 /* We cannot carry a delta into the new pack. */
845                 if (delta) {
846                         free(delta);
847                         delta = NULL;
848                 }
849                 memset(&s, 0, sizeof(s));
850                 deflateInit(&s, zlib_compression_level);
851                 s.next_in = dat;
852                 s.avail_in = datlen;
853                 s.avail_out = deflateBound(&s, s.avail_in);
854                 s.next_out = out;
855                 while (deflate(&s, Z_FINISH) == Z_OK)
856                         /* nothing */;
857                 deflateEnd(&s);
858         }
860         e->type = type;
861         e->pack_id = pack_id;
862         e->offset = pack_size;
863         object_count++;
864         object_count_by_type[type]++;
866         if (delta) {
867                 unsigned long ofs = e->offset - last->offset;
868                 unsigned pos = sizeof(hdr) - 1;
870                 delta_count_by_type[type]++;
871                 last->depth++;
873                 hdrlen = encode_header(OBJ_OFS_DELTA, deltalen, hdr);
874                 write_or_die(pack_fd, hdr, hdrlen);
875                 pack_size += hdrlen;
877                 hdr[pos] = ofs & 127;
878                 while (ofs >>= 7)
879                         hdr[--pos] = 128 | (--ofs & 127);
880                 write_or_die(pack_fd, hdr + pos, sizeof(hdr) - pos);
881                 pack_size += sizeof(hdr) - pos;
882         } else {
883                 if (last)
884                         last->depth = 0;
885                 hdrlen = encode_header(type, datlen, hdr);
886                 write_or_die(pack_fd, hdr, hdrlen);
887                 pack_size += hdrlen;
888         }
890         write_or_die(pack_fd, out, s.total_out);
891         pack_size += s.total_out;
893         free(out);
894         if (delta)
895                 free(delta);
896         if (last) {
897                 if (last->data && !last->no_free)
898                         free(last->data);
899                 last->data = dat;
900                 last->offset = e->offset;
901                 last->len = datlen;
902         }
903         return 0;
906 static void *gfi_unpack_entry(
907         struct object_entry *oe,
908         unsigned long *sizep)
910         static char type[20];
911         struct packed_git *p = all_packs[oe->pack_id];
912         if (p == pack_data)
913                 p->pack_size = pack_size + 20;
914         return unpack_entry(p, oe->offset, type, sizep);
917 static const char *get_mode(const char *str, unsigned int *modep)
919         unsigned char c;
920         unsigned int mode = 0;
922         while ((c = *str++) != ' ') {
923                 if (c < '0' || c > '7')
924                         return NULL;
925                 mode = (mode << 3) + (c - '0');
926         }
927         *modep = mode;
928         return str;
931 static void load_tree(struct tree_entry *root)
933         unsigned char* sha1 = root->versions[1].sha1;
934         struct object_entry *myoe;
935         struct tree_content *t;
936         unsigned long size;
937         char *buf;
938         const char *c;
940         root->tree = t = new_tree_content(8);
941         if (is_null_sha1(sha1))
942                 return;
944         myoe = find_object(sha1);
945         if (myoe) {
946                 if (myoe->type != OBJ_TREE)
947                         die("Not a tree: %s", sha1_to_hex(sha1));
948                 t->delta_depth = 0;
949                 buf = gfi_unpack_entry(myoe, &size);
950         } else {
951                 char type[20];
952                 buf = read_sha1_file(sha1, type, &size);
953                 if (!buf || strcmp(type, tree_type))
954                         die("Can't load tree %s", sha1_to_hex(sha1));
955         }
957         c = buf;
958         while (c != (buf + size)) {
959                 struct tree_entry *e = new_tree_entry();
961                 if (t->entry_count == t->entry_capacity)
962                         root->tree = t = grow_tree_content(t, 8);
963                 t->entries[t->entry_count++] = e;
965                 e->tree = NULL;
966                 c = get_mode(c, &e->versions[1].mode);
967                 if (!c)
968                         die("Corrupt mode in %s", sha1_to_hex(sha1));
969                 e->versions[0].mode = e->versions[1].mode;
970                 e->name = to_atom(c, strlen(c));
971                 c += e->name->str_len + 1;
972                 hashcpy(e->versions[0].sha1, (unsigned char*)c);
973                 hashcpy(e->versions[1].sha1, (unsigned char*)c);
974                 c += 20;
975         }
976         free(buf);
979 static int tecmp0 (const void *_a, const void *_b)
981         struct tree_entry *a = *((struct tree_entry**)_a);
982         struct tree_entry *b = *((struct tree_entry**)_b);
983         return base_name_compare(
984                 a->name->str_dat, a->name->str_len, a->versions[0].mode,
985                 b->name->str_dat, b->name->str_len, b->versions[0].mode);
988 static int tecmp1 (const void *_a, const void *_b)
990         struct tree_entry *a = *((struct tree_entry**)_a);
991         struct tree_entry *b = *((struct tree_entry**)_b);
992         return base_name_compare(
993                 a->name->str_dat, a->name->str_len, a->versions[1].mode,
994                 b->name->str_dat, b->name->str_len, b->versions[1].mode);
997 static void mktree(struct tree_content *t,
998         int v,
999         unsigned long *szp,
1000         struct dbuf *b)
1002         size_t maxlen = 0;
1003         unsigned int i;
1004         char *c;
1006         if (!v)
1007                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0);
1008         else
1009                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1);
1011         for (i = 0; i < t->entry_count; i++) {
1012                 if (t->entries[i]->versions[v].mode)
1013                         maxlen += t->entries[i]->name->str_len + 34;
1014         }
1016         size_dbuf(b, maxlen);
1017         c = b->buffer;
1018         for (i = 0; i < t->entry_count; i++) {
1019                 struct tree_entry *e = t->entries[i];
1020                 if (!e->versions[v].mode)
1021                         continue;
1022                 c += sprintf(c, "%o", e->versions[v].mode);
1023                 *c++ = ' ';
1024                 strcpy(c, e->name->str_dat);
1025                 c += e->name->str_len + 1;
1026                 hashcpy((unsigned char*)c, e->versions[v].sha1);
1027                 c += 20;
1028         }
1029         *szp = c - (char*)b->buffer;
1032 static void store_tree(struct tree_entry *root)
1034         struct tree_content *t = root->tree;
1035         unsigned int i, j, del;
1036         unsigned long new_len;
1037         struct last_object lo;
1038         struct object_entry *le;
1040         if (!is_null_sha1(root->versions[1].sha1))
1041                 return;
1043         for (i = 0; i < t->entry_count; i++) {
1044                 if (t->entries[i]->tree)
1045                         store_tree(t->entries[i]);
1046         }
1048         le = find_object(root->versions[0].sha1);
1049         if (!S_ISDIR(root->versions[0].mode)
1050                 || !le
1051                 || le->pack_id != pack_id) {
1052                 lo.data = NULL;
1053                 lo.depth = 0;
1054         } else {
1055                 mktree(t, 0, &lo.len, &old_tree);
1056                 lo.data = old_tree.buffer;
1057                 lo.offset = le->offset;
1058                 lo.depth = t->delta_depth;
1059                 lo.no_free = 1;
1060         }
1062         mktree(t, 1, &new_len, &new_tree);
1063         store_object(OBJ_TREE, new_tree.buffer, new_len,
1064                 &lo, root->versions[1].sha1, 0);
1066         t->delta_depth = lo.depth;
1067         for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1068                 struct tree_entry *e = t->entries[i];
1069                 if (e->versions[1].mode) {
1070                         e->versions[0].mode = e->versions[1].mode;
1071                         hashcpy(e->versions[0].sha1, e->versions[1].sha1);
1072                         t->entries[j++] = e;
1073                 } else {
1074                         release_tree_entry(e);
1075                         del++;
1076                 }
1077         }
1078         t->entry_count -= del;
1081 static int tree_content_set(
1082         struct tree_entry *root,
1083         const char *p,
1084         const unsigned char *sha1,
1085         const unsigned int mode)
1087         struct tree_content *t = root->tree;
1088         const char *slash1;
1089         unsigned int i, n;
1090         struct tree_entry *e;
1092         slash1 = strchr(p, '/');
1093         if (slash1)
1094                 n = slash1 - p;
1095         else
1096                 n = strlen(p);
1098         for (i = 0; i < t->entry_count; i++) {
1099                 e = t->entries[i];
1100                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1101                         if (!slash1) {
1102                                 if (e->versions[1].mode == mode
1103                                                 && !hashcmp(e->versions[1].sha1, sha1))
1104                                         return 0;
1105                                 e->versions[1].mode = mode;
1106                                 hashcpy(e->versions[1].sha1, sha1);
1107                                 if (e->tree) {
1108                                         release_tree_content_recursive(e->tree);
1109                                         e->tree = NULL;
1110                                 }
1111                                 hashclr(root->versions[1].sha1);
1112                                 return 1;
1113                         }
1114                         if (!S_ISDIR(e->versions[1].mode)) {
1115                                 e->tree = new_tree_content(8);
1116                                 e->versions[1].mode = S_IFDIR;
1117                         }
1118                         if (!e->tree)
1119                                 load_tree(e);
1120                         if (tree_content_set(e, slash1 + 1, sha1, mode)) {
1121                                 hashclr(root->versions[1].sha1);
1122                                 return 1;
1123                         }
1124                         return 0;
1125                 }
1126         }
1128         if (t->entry_count == t->entry_capacity)
1129                 root->tree = t = grow_tree_content(t, 8);
1130         e = new_tree_entry();
1131         e->name = to_atom(p, n);
1132         e->versions[0].mode = 0;
1133         hashclr(e->versions[0].sha1);
1134         t->entries[t->entry_count++] = e;
1135         if (slash1) {
1136                 e->tree = new_tree_content(8);
1137                 e->versions[1].mode = S_IFDIR;
1138                 tree_content_set(e, slash1 + 1, sha1, mode);
1139         } else {
1140                 e->tree = NULL;
1141                 e->versions[1].mode = mode;
1142                 hashcpy(e->versions[1].sha1, sha1);
1143         }
1144         hashclr(root->versions[1].sha1);
1145         return 1;
1148 static int tree_content_remove(struct tree_entry *root, const char *p)
1150         struct tree_content *t = root->tree;
1151         const char *slash1;
1152         unsigned int i, n;
1153         struct tree_entry *e;
1155         slash1 = strchr(p, '/');
1156         if (slash1)
1157                 n = slash1 - p;
1158         else
1159                 n = strlen(p);
1161         for (i = 0; i < t->entry_count; i++) {
1162                 e = t->entries[i];
1163                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1164                         if (!slash1 || !S_ISDIR(e->versions[1].mode))
1165                                 goto del_entry;
1166                         if (!e->tree)
1167                                 load_tree(e);
1168                         if (tree_content_remove(e, slash1 + 1)) {
1169                                 for (n = 0; n < e->tree->entry_count; n++) {
1170                                         if (e->tree->entries[n]->versions[1].mode) {
1171                                                 hashclr(root->versions[1].sha1);
1172                                                 return 1;
1173                                         }
1174                                 }
1175                                 goto del_entry;
1176                         }
1177                         return 0;
1178                 }
1179         }
1180         return 0;
1182 del_entry:
1183         if (e->tree) {
1184                 release_tree_content_recursive(e->tree);
1185                 e->tree = NULL;
1186         }
1187         e->versions[1].mode = 0;
1188         hashclr(e->versions[1].sha1);
1189         hashclr(root->versions[1].sha1);
1190         return 1;
1193 static void dump_branches()
1195         static const char *msg = "fast-import";
1196         unsigned int i;
1197         struct branch *b;
1198         struct ref_lock *lock;
1200         for (i = 0; i < branch_table_sz; i++) {
1201                 for (b = branch_table[i]; b; b = b->table_next_branch) {
1202                         lock = lock_any_ref_for_update(b->name, NULL);
1203                         if (!lock || write_ref_sha1(lock, b->sha1, msg) < 0)
1204                                 die("Can't write %s", b->name);
1205                 }
1206         }
1209 static void dump_tags()
1211         static const char *msg = "fast-import";
1212         struct tag *t;
1213         struct ref_lock *lock;
1214         char path[PATH_MAX];
1216         for (t = first_tag; t; t = t->next_tag) {
1217                 sprintf(path, "refs/tags/%s", t->name);
1218                 lock = lock_any_ref_for_update(path, NULL);
1219                 if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
1220                         die("Can't write %s", path);
1221         }
1224 static void dump_marks_helper(FILE *f,
1225         unsigned long base,
1226         struct mark_set *m)
1228         int k;
1229         if (m->shift) {
1230                 for (k = 0; k < 1024; k++) {
1231                         if (m->data.sets[k])
1232                                 dump_marks_helper(f, (base + k) << m->shift,
1233                                         m->data.sets[k]);
1234                 }
1235         } else {
1236                 for (k = 0; k < 1024; k++) {
1237                         if (m->data.marked[k])
1238                                 fprintf(f, ":%lu %s\n", base + k,
1239                                         sha1_to_hex(m->data.marked[k]->sha1));
1240                 }
1241         }
1244 static void dump_marks()
1246         if (mark_file)
1247         {
1248                 FILE *f = fopen(mark_file, "w");
1249                 dump_marks_helper(f, 0, marks);
1250                 fclose(f);
1251         }
1254 static void read_next_command()
1256         read_line(&command_buf, stdin, '\n');
1259 static void cmd_mark()
1261         if (!strncmp("mark :", command_buf.buf, 6)) {
1262                 next_mark = strtoul(command_buf.buf + 6, NULL, 10);
1263                 read_next_command();
1264         }
1265         else
1266                 next_mark = 0;
1269 static void* cmd_data (size_t *size)
1271         size_t n = 0;
1272         void *buffer;
1273         size_t length;
1275         if (strncmp("data ", command_buf.buf, 5))
1276                 die("Expected 'data n' command, found: %s", command_buf.buf);
1278         length = strtoul(command_buf.buf + 5, NULL, 10);
1279         buffer = xmalloc(length);
1281         while (n < length) {
1282                 size_t s = fread((char*)buffer + n, 1, length - n, stdin);
1283                 if (!s && feof(stdin))
1284                         die("EOF in data (%lu bytes remaining)", length - n);
1285                 n += s;
1286         }
1288         if (fgetc(stdin) != '\n')
1289                 die("An lf did not trail the binary data as expected.");
1291         *size = length;
1292         return buffer;
1295 static void cmd_new_blob()
1297         size_t l;
1298         void *d;
1300         read_next_command();
1301         cmd_mark();
1302         d = cmd_data(&l);
1304         if (store_object(OBJ_BLOB, d, l, &last_blob, NULL, next_mark))
1305                 free(d);
1308 static void unload_one_branch()
1310         while (cur_active_branches
1311                 && cur_active_branches >= max_active_branches) {
1312                 unsigned long min_commit = ULONG_MAX;
1313                 struct branch *e, *l = NULL, *p = NULL;
1315                 for (e = active_branches; e; e = e->active_next_branch) {
1316                         if (e->last_commit < min_commit) {
1317                                 p = l;
1318                                 min_commit = e->last_commit;
1319                         }
1320                         l = e;
1321                 }
1323                 if (p) {
1324                         e = p->active_next_branch;
1325                         p->active_next_branch = e->active_next_branch;
1326                 } else {
1327                         e = active_branches;
1328                         active_branches = e->active_next_branch;
1329                 }
1330                 e->active_next_branch = NULL;
1331                 if (e->branch_tree.tree) {
1332                         release_tree_content_recursive(e->branch_tree.tree);
1333                         e->branch_tree.tree = NULL;
1334                 }
1335                 cur_active_branches--;
1336         }
1339 static void load_branch(struct branch *b)
1341         load_tree(&b->branch_tree);
1342         b->active_next_branch = active_branches;
1343         active_branches = b;
1344         cur_active_branches++;
1345         branch_load_count++;
1348 static void file_change_m(struct branch *b)
1350         const char *p = command_buf.buf + 2;
1351         char *p_uq;
1352         const char *endp;
1353         struct object_entry *oe;
1354         unsigned char sha1[20];
1355         unsigned int mode;
1356         char type[20];
1358         p = get_mode(p, &mode);
1359         if (!p)
1360                 die("Corrupt mode: %s", command_buf.buf);
1361         switch (mode) {
1362         case S_IFREG | 0644:
1363         case S_IFREG | 0755:
1364         case S_IFLNK:
1365         case 0644:
1366         case 0755:
1367                 /* ok */
1368                 break;
1369         default:
1370                 die("Corrupt mode: %s", command_buf.buf);
1371         }
1373         if (*p == ':') {
1374                 char *x;
1375                 oe = find_mark(strtoul(p + 1, &x, 10));
1376                 hashcpy(sha1, oe->sha1);
1377                 p = x;
1378         } else {
1379                 if (get_sha1_hex(p, sha1))
1380                         die("Invalid SHA1: %s", command_buf.buf);
1381                 oe = find_object(sha1);
1382                 p += 40;
1383         }
1384         if (*p++ != ' ')
1385                 die("Missing space after SHA1: %s", command_buf.buf);
1387         p_uq = unquote_c_style(p, &endp);
1388         if (p_uq) {
1389                 if (*endp)
1390                         die("Garbage after path in: %s", command_buf.buf);
1391                 p = p_uq;
1392         }
1394         if (oe) {
1395                 if (oe->type != OBJ_BLOB)
1396                         die("Not a blob (actually a %s): %s",
1397                                 command_buf.buf, type_names[oe->type]);
1398         } else {
1399                 if (sha1_object_info(sha1, type, NULL))
1400                         die("Blob not found: %s", command_buf.buf);
1401                 if (strcmp(blob_type, type))
1402                         die("Not a blob (actually a %s): %s",
1403                                 command_buf.buf, type);
1404         }
1406         tree_content_set(&b->branch_tree, p, sha1, S_IFREG | mode);
1408         if (p_uq)
1409                 free(p_uq);
1412 static void file_change_d(struct branch *b)
1414         const char *p = command_buf.buf + 2;
1415         char *p_uq;
1416         const char *endp;
1418         p_uq = unquote_c_style(p, &endp);
1419         if (p_uq) {
1420                 if (*endp)
1421                         die("Garbage after path in: %s", command_buf.buf);
1422                 p = p_uq;
1423         }
1424         tree_content_remove(&b->branch_tree, p);
1425         if (p_uq)
1426                 free(p_uq);
1429 static void cmd_from(struct branch *b)
1431         const char *from, *endp;
1432         char *str_uq;
1433         struct branch *s;
1435         if (strncmp("from ", command_buf.buf, 5))
1436                 return;
1438         if (b->last_commit)
1439                 die("Can't reinitailize branch %s", b->name);
1441         from = strchr(command_buf.buf, ' ') + 1;
1442         str_uq = unquote_c_style(from, &endp);
1443         if (str_uq) {
1444                 if (*endp)
1445                         die("Garbage after string in: %s", command_buf.buf);
1446                 from = str_uq;
1447         }
1449         s = lookup_branch(from);
1450         if (b == s)
1451                 die("Can't create a branch from itself: %s", b->name);
1452         else if (s) {
1453                 unsigned char *t = s->branch_tree.versions[1].sha1;
1454                 hashcpy(b->sha1, s->sha1);
1455                 hashcpy(b->branch_tree.versions[0].sha1, t);
1456                 hashcpy(b->branch_tree.versions[1].sha1, t);
1457         } else if (*from == ':') {
1458                 unsigned long idnum = strtoul(from + 1, NULL, 10);
1459                 struct object_entry *oe = find_mark(idnum);
1460                 unsigned long size;
1461                 char *buf;
1462                 if (oe->type != OBJ_COMMIT)
1463                         die("Mark :%lu not a commit", idnum);
1464                 hashcpy(b->sha1, oe->sha1);
1465                 buf = gfi_unpack_entry(oe, &size);
1466                 if (!buf || size < 46)
1467                         die("Not a valid commit: %s", from);
1468                 if (memcmp("tree ", buf, 5)
1469                         || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
1470                         die("The commit %s is corrupt", sha1_to_hex(b->sha1));
1471                 free(buf);
1472                 hashcpy(b->branch_tree.versions[0].sha1,
1473                         b->branch_tree.versions[1].sha1);
1474         } else if (!get_sha1(from, b->sha1)) {
1475                 if (is_null_sha1(b->sha1)) {
1476                         hashclr(b->branch_tree.versions[0].sha1);
1477                         hashclr(b->branch_tree.versions[1].sha1);
1478                 } else {
1479                         unsigned long size;
1480                         char *buf;
1482                         buf = read_object_with_reference(b->sha1,
1483                                 type_names[OBJ_COMMIT], &size, b->sha1);
1484                         if (!buf || size < 46)
1485                                 die("Not a valid commit: %s", from);
1486                         if (memcmp("tree ", buf, 5)
1487                                 || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
1488                                 die("The commit %s is corrupt", sha1_to_hex(b->sha1));
1489                         free(buf);
1490                         hashcpy(b->branch_tree.versions[0].sha1,
1491                                 b->branch_tree.versions[1].sha1);
1492                 }
1493         } else
1494                 die("Invalid ref name or SHA1 expression: %s", from);
1496         read_next_command();
1499 static struct hash_list* cmd_merge(unsigned int *count)
1501         struct hash_list *list = NULL, *n, *e;
1502         const char *from, *endp;
1503         char *str_uq;
1504         struct branch *s;
1506         *count = 0;
1507         while (!strncmp("merge ", command_buf.buf, 6)) {
1508                 from = strchr(command_buf.buf, ' ') + 1;
1509                 str_uq = unquote_c_style(from, &endp);
1510                 if (str_uq) {
1511                         if (*endp)
1512                                 die("Garbage after string in: %s", command_buf.buf);
1513                         from = str_uq;
1514                 }
1516                 n = xmalloc(sizeof(*n));
1517                 s = lookup_branch(from);
1518                 if (s)
1519                         hashcpy(n->sha1, s->sha1);
1520                 else if (*from == ':') {
1521                         unsigned long idnum = strtoul(from + 1, NULL, 10);
1522                         struct object_entry *oe = find_mark(idnum);
1523                         if (oe->type != OBJ_COMMIT)
1524                                 die("Mark :%lu not a commit", idnum);
1525                         hashcpy(n->sha1, oe->sha1);
1526                 } else if (get_sha1(from, n->sha1))
1527                         die("Invalid ref name or SHA1 expression: %s", from);
1529                 n->next = NULL;
1530                 if (list)
1531                         e->next = n;
1532                 else
1533                         list = n;
1534                 e = n;
1535                 *count++;
1536                 read_next_command();
1537         }
1538         return list;
1541 static void cmd_new_commit()
1543         struct branch *b;
1544         void *msg;
1545         size_t msglen;
1546         char *str_uq;
1547         const char *endp;
1548         char *sp;
1549         char *author = NULL;
1550         char *committer = NULL;
1551         struct hash_list *merge_list = NULL;
1552         unsigned int merge_count;
1554         /* Obtain the branch name from the rest of our command */
1555         sp = strchr(command_buf.buf, ' ') + 1;
1556         str_uq = unquote_c_style(sp, &endp);
1557         if (str_uq) {
1558                 if (*endp)
1559                         die("Garbage after ref in: %s", command_buf.buf);
1560                 sp = str_uq;
1561         }
1562         b = lookup_branch(sp);
1563         if (!b)
1564                 b = new_branch(sp);
1565         if (str_uq)
1566                 free(str_uq);
1568         read_next_command();
1569         cmd_mark();
1570         if (!strncmp("author ", command_buf.buf, 7)) {
1571                 author = strdup(command_buf.buf);
1572                 read_next_command();
1573         }
1574         if (!strncmp("committer ", command_buf.buf, 10)) {
1575                 committer = strdup(command_buf.buf);
1576                 read_next_command();
1577         }
1578         if (!committer)
1579                 die("Expected committer but didn't get one");
1580         msg = cmd_data(&msglen);
1581         read_next_command();
1582         cmd_from(b);
1583         merge_list = cmd_merge(&merge_count);
1585         /* ensure the branch is active/loaded */
1586         if (!b->branch_tree.tree || !max_active_branches) {
1587                 unload_one_branch();
1588                 load_branch(b);
1589         }
1591         /* file_change* */
1592         for (;;) {
1593                 if (1 == command_buf.len)
1594                         break;
1595                 else if (!strncmp("M ", command_buf.buf, 2))
1596                         file_change_m(b);
1597                 else if (!strncmp("D ", command_buf.buf, 2))
1598                         file_change_d(b);
1599                 else
1600                         die("Unsupported file_change: %s", command_buf.buf);
1601                 read_next_command();
1602         }
1604         /* build the tree and the commit */
1605         store_tree(&b->branch_tree);
1606         hashcpy(b->branch_tree.versions[0].sha1,
1607                 b->branch_tree.versions[1].sha1);
1608         size_dbuf(&new_data, 97 + msglen
1609                 + merge_count * 49
1610                 + (author
1611                         ? strlen(author) + strlen(committer)
1612                         : 2 * strlen(committer)));
1613         sp = new_data.buffer;
1614         sp += sprintf(sp, "tree %s\n",
1615                 sha1_to_hex(b->branch_tree.versions[1].sha1));
1616         if (!is_null_sha1(b->sha1))
1617                 sp += sprintf(sp, "parent %s\n", sha1_to_hex(b->sha1));
1618         while (merge_list) {
1619                 struct hash_list *next = merge_list->next;
1620                 sp += sprintf(sp, "parent %s\n", sha1_to_hex(merge_list->sha1));
1621                 free(merge_list);
1622                 merge_list = next;
1623         }
1624         if (author)
1625                 sp += sprintf(sp, "%s\n", author);
1626         else
1627                 sp += sprintf(sp, "author %s\n", committer + 10);
1628         sp += sprintf(sp, "%s\n\n", committer);
1629         memcpy(sp, msg, msglen);
1630         sp += msglen;
1631         if (author)
1632                 free(author);
1633         free(committer);
1634         free(msg);
1636         store_object(OBJ_COMMIT,
1637                 new_data.buffer, sp - (char*)new_data.buffer,
1638                 NULL, b->sha1, next_mark);
1639         b->last_commit = object_count_by_type[OBJ_COMMIT];
1641         if (branch_log) {
1642                 int need_dq = quote_c_style(b->name, NULL, NULL, 0);
1643                 fprintf(branch_log, "commit ");
1644                 if (need_dq) {
1645                         fputc('"', branch_log);
1646                         quote_c_style(b->name, NULL, branch_log, 0);
1647                         fputc('"', branch_log);
1648                 } else
1649                         fprintf(branch_log, "%s", b->name);
1650                 fprintf(branch_log," :%lu %s\n",next_mark,sha1_to_hex(b->sha1));
1651         }
1654 static void cmd_new_tag()
1656         char *str_uq;
1657         const char *endp;
1658         char *sp;
1659         const char *from;
1660         char *tagger;
1661         struct branch *s;
1662         void *msg;
1663         size_t msglen;
1664         struct tag *t;
1665         unsigned long from_mark = 0;
1666         unsigned char sha1[20];
1668         /* Obtain the new tag name from the rest of our command */
1669         sp = strchr(command_buf.buf, ' ') + 1;
1670         str_uq = unquote_c_style(sp, &endp);
1671         if (str_uq) {
1672                 if (*endp)
1673                         die("Garbage after tag name in: %s", command_buf.buf);
1674                 sp = str_uq;
1675         }
1676         t = pool_alloc(sizeof(struct tag));
1677         t->next_tag = NULL;
1678         t->name = pool_strdup(sp);
1679         if (last_tag)
1680                 last_tag->next_tag = t;
1681         else
1682                 first_tag = t;
1683         last_tag = t;
1684         if (str_uq)
1685                 free(str_uq);
1686         read_next_command();
1688         /* from ... */
1689         if (strncmp("from ", command_buf.buf, 5))
1690                 die("Expected from command, got %s", command_buf.buf);
1692         from = strchr(command_buf.buf, ' ') + 1;
1693         str_uq = unquote_c_style(from, &endp);
1694         if (str_uq) {
1695                 if (*endp)
1696                         die("Garbage after string in: %s", command_buf.buf);
1697                 from = str_uq;
1698         }
1700         s = lookup_branch(from);
1701         if (s) {
1702                 hashcpy(sha1, s->sha1);
1703         } else if (*from == ':') {
1704                 from_mark = strtoul(from + 1, NULL, 10);
1705                 struct object_entry *oe = find_mark(from_mark);
1706                 if (oe->type != OBJ_COMMIT)
1707                         die("Mark :%lu not a commit", from_mark);
1708                 hashcpy(sha1, oe->sha1);
1709         } else if (!get_sha1(from, sha1)) {
1710                 unsigned long size;
1711                 char *buf;
1713                 buf = read_object_with_reference(sha1,
1714                         type_names[OBJ_COMMIT], &size, sha1);
1715                 if (!buf || size < 46)
1716                         die("Not a valid commit: %s", from);
1717                 free(buf);
1718         } else
1719                 die("Invalid ref name or SHA1 expression: %s", from);
1721         if (str_uq)
1722                 free(str_uq);
1723         read_next_command();
1725         /* tagger ... */
1726         if (strncmp("tagger ", command_buf.buf, 7))
1727                 die("Expected tagger command, got %s", command_buf.buf);
1728         tagger = strdup(command_buf.buf);
1730         /* tag payload/message */
1731         read_next_command();
1732         msg = cmd_data(&msglen);
1734         /* build the tag object */
1735         size_dbuf(&new_data, 67+strlen(t->name)+strlen(tagger)+msglen);
1736         sp = new_data.buffer;
1737         sp += sprintf(sp, "object %s\n", sha1_to_hex(sha1));
1738         sp += sprintf(sp, "type %s\n", type_names[OBJ_COMMIT]);
1739         sp += sprintf(sp, "tag %s\n", t->name);
1740         sp += sprintf(sp, "%s\n\n", tagger);
1741         memcpy(sp, msg, msglen);
1742         sp += msglen;
1743         free(tagger);
1744         free(msg);
1746         store_object(OBJ_TAG, new_data.buffer, sp - (char*)new_data.buffer,
1747                 NULL, t->sha1, 0);
1749         if (branch_log) {
1750                 int need_dq = quote_c_style(t->name, NULL, NULL, 0);
1751                 fprintf(branch_log, "tag ");
1752                 if (need_dq) {
1753                         fputc('"', branch_log);
1754                         quote_c_style(t->name, NULL, branch_log, 0);
1755                         fputc('"', branch_log);
1756                 } else
1757                         fprintf(branch_log, "%s", t->name);
1758                 fprintf(branch_log," :%lu %s\n",from_mark,sha1_to_hex(t->sha1));
1759         }
1762 static void cmd_reset_branch()
1764         struct branch *b;
1765         char *str_uq;
1766         const char *endp;
1767         char *sp;
1769         /* Obtain the branch name from the rest of our command */
1770         sp = strchr(command_buf.buf, ' ') + 1;
1771         str_uq = unquote_c_style(sp, &endp);
1772         if (str_uq) {
1773                 if (*endp)
1774                         die("Garbage after ref in: %s", command_buf.buf);
1775                 sp = str_uq;
1776         }
1777         b = lookup_branch(sp);
1778         if (b) {
1779                 b->last_commit = 0;
1780                 if (b->branch_tree.tree) {
1781                         release_tree_content_recursive(b->branch_tree.tree);
1782                         b->branch_tree.tree = NULL;
1783                 }
1784         }
1785         else
1786                 b = new_branch(sp);
1787         if (str_uq)
1788                 free(str_uq);
1789         read_next_command();
1790         cmd_from(b);
1793 static void cmd_checkpoint()
1795         if (object_count)
1796                 checkpoint();
1797         read_next_command();
1800 static const char fast_import_usage[] =
1801 "git-fast-import [--objects=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file] [--branch-log=log] temp.pack";
1803 int main(int argc, const char **argv)
1805         int i;
1806         unsigned long est_obj_cnt = object_entry_alloc;
1807         unsigned long duplicate_count;
1809         setup_ident();
1810         git_config(git_default_config);
1812         for (i = 1; i < argc; i++) {
1813                 const char *a = argv[i];
1815                 if (*a != '-' || !strcmp(a, "--"))
1816                         break;
1817                 else if (!strncmp(a, "--objects=", 10))
1818                         est_obj_cnt = strtoul(a + 10, NULL, 0);
1819                 else if (!strncmp(a, "--max-objects-per-pack=", 23))
1820                         max_objects = strtoul(a + 23, NULL, 0);
1821                 else if (!strncmp(a, "--max-pack-size=", 16))
1822                         max_packsize = strtoul(a + 16, NULL, 0) * 1024 * 1024;
1823                 else if (!strncmp(a, "--depth=", 8))
1824                         max_depth = strtoul(a + 8, NULL, 0);
1825                 else if (!strncmp(a, "--active-branches=", 18))
1826                         max_active_branches = strtoul(a + 18, NULL, 0);
1827                 else if (!strncmp(a, "--export-marks=", 15))
1828                         mark_file = a + 15;
1829                 else if (!strncmp(a, "--branch-log=", 13)) {
1830                         branch_log = fopen(a + 13, "w");
1831                         if (!branch_log)
1832                                 die("Can't create %s: %s", a + 13, strerror(errno));
1833                 }
1834                 else
1835                         die("unknown option %s", a);
1836         }
1837         if ((i+1) != argc)
1838                 usage(fast_import_usage);
1839         base_name = argv[i];
1841         alloc_objects(est_obj_cnt);
1842         strbuf_init(&command_buf);
1844         atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
1845         branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
1846         avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
1847         marks = pool_calloc(1, sizeof(struct mark_set));
1849         start_packfile();
1850         for (;;) {
1851                 read_next_command();
1852                 if (command_buf.eof)
1853                         break;
1854                 else if (!strcmp("blob", command_buf.buf))
1855                         cmd_new_blob();
1856                 else if (!strncmp("commit ", command_buf.buf, 7))
1857                         cmd_new_commit();
1858                 else if (!strncmp("tag ", command_buf.buf, 4))
1859                         cmd_new_tag();
1860                 else if (!strncmp("reset ", command_buf.buf, 6))
1861                         cmd_reset_branch();
1862                 else if (!strcmp("checkpoint", command_buf.buf))
1863                         cmd_checkpoint();
1864                 else
1865                         die("Unsupported command: %s", command_buf.buf);
1866         }
1867         end_packfile();
1869         dump_branches();
1870         dump_tags();
1871         dump_marks();
1872         if (branch_log)
1873                 fclose(branch_log);
1875         for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
1876                 duplicate_count += duplicate_count_by_type[i];
1878         fprintf(stderr, "%s statistics:\n", argv[0]);
1879         fprintf(stderr, "---------------------------------------------------------------------\n");
1880         fprintf(stderr, "Alloc'd objects: %10lu (%10lu overflow  )\n", alloc_count, alloc_count - est_obj_cnt);
1881         fprintf(stderr, "Total objects:   %10lu (%10lu duplicates                  )\n", object_count, duplicate_count);
1882         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]);
1883         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]);
1884         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]);
1885         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]);
1886         fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
1887         fprintf(stderr, "      marks:     %10u (%10lu unique    )\n", (1 << marks->shift) * 1024, marks_set_count);
1888         fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
1889         fprintf(stderr, "Memory total:    %10lu KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
1890         fprintf(stderr, "       pools:    %10lu KiB\n", total_allocd/1024);
1891         fprintf(stderr, "     objects:    %10lu KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
1892         fprintf(stderr, "---------------------------------------------------------------------\n");
1893         pack_report();
1894         fprintf(stderr, "---------------------------------------------------------------------\n");
1895         fprintf(stderr, "\n");
1897         return 0;