Code

ebffa7c904bc892dc086aa8a53257253764d2453
[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 /* Configured limits on output */
219 static unsigned long max_depth = 10;
220 static unsigned long max_packsize = -1;
221 static uintmax_t max_objects = -1;
223 /* Stats and misc. counters */
224 static uintmax_t alloc_count;
225 static uintmax_t object_count;
226 static uintmax_t marks_set_count;
227 static uintmax_t object_count_by_type[1 << TYPE_BITS];
228 static uintmax_t duplicate_count_by_type[1 << TYPE_BITS];
229 static uintmax_t delta_count_by_type[1 << TYPE_BITS];
230 static unsigned long branch_count;
231 static unsigned long branch_load_count;
233 /* Memory pools */
234 static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
235 static size_t total_allocd;
236 static struct mem_pool *mem_pool;
238 /* Atom management */
239 static unsigned int atom_table_sz = 4451;
240 static unsigned int atom_cnt;
241 static struct atom_str **atom_table;
243 /* The .pack file being generated */
244 static const char *base_name;
245 static unsigned int pack_id;
246 static char *idx_name;
247 static struct packed_git *pack_data;
248 static struct packed_git **all_packs;
249 static int pack_fd;
250 static unsigned long pack_size;
251 static unsigned char pack_sha1[20];
253 /* Table of objects we've written. */
254 static unsigned int object_entry_alloc = 5000;
255 static struct object_entry_pool *blocks;
256 static struct object_entry *object_table[1 << 16];
257 static struct mark_set *marks;
258 static const char* mark_file;
260 /* Our last blob */
261 static struct last_object last_blob;
263 /* Tree management */
264 static unsigned int tree_entry_alloc = 1000;
265 static void *avail_tree_entry;
266 static unsigned int avail_tree_table_sz = 100;
267 static struct avail_tree_content **avail_tree_table;
268 static struct dbuf old_tree;
269 static struct dbuf new_tree;
271 /* Branch data */
272 static unsigned long max_active_branches = 5;
273 static unsigned long cur_active_branches;
274 static unsigned long branch_table_sz = 1039;
275 static struct branch **branch_table;
276 static struct branch *active_branches;
278 /* Tag data */
279 static struct tag *first_tag;
280 static struct tag *last_tag;
282 /* Input stream parsing */
283 static struct strbuf command_buf;
284 static uintmax_t next_mark;
285 static struct dbuf new_data;
286 static FILE* branch_log;
289 static void alloc_objects(unsigned int cnt)
291         struct object_entry_pool *b;
293         b = xmalloc(sizeof(struct object_entry_pool)
294                 + cnt * sizeof(struct object_entry));
295         b->next_pool = blocks;
296         b->next_free = b->entries;
297         b->end = b->entries + cnt;
298         blocks = b;
299         alloc_count += cnt;
302 static struct object_entry* new_object(unsigned char *sha1)
304         struct object_entry *e;
306         if (blocks->next_free == blocks->end)
307                 alloc_objects(object_entry_alloc);
309         e = blocks->next_free++;
310         hashcpy(e->sha1, sha1);
311         return e;
314 static struct object_entry* find_object(unsigned char *sha1)
316         unsigned int h = sha1[0] << 8 | sha1[1];
317         struct object_entry *e;
318         for (e = object_table[h]; e; e = e->next)
319                 if (!hashcmp(sha1, e->sha1))
320                         return e;
321         return NULL;
324 static struct object_entry* insert_object(unsigned char *sha1)
326         unsigned int h = sha1[0] << 8 | sha1[1];
327         struct object_entry *e = object_table[h];
328         struct object_entry *p = NULL;
330         while (e) {
331                 if (!hashcmp(sha1, e->sha1))
332                         return e;
333                 p = e;
334                 e = e->next;
335         }
337         e = new_object(sha1);
338         e->next = NULL;
339         e->offset = 0;
340         if (p)
341                 p->next = e;
342         else
343                 object_table[h] = e;
344         return e;
347 static unsigned int hc_str(const char *s, size_t len)
349         unsigned int r = 0;
350         while (len-- > 0)
351                 r = r * 31 + *s++;
352         return r;
355 static void* pool_alloc(size_t len)
357         struct mem_pool *p;
358         void *r;
360         for (p = mem_pool; p; p = p->next_pool)
361                 if ((p->end - p->next_free >= len))
362                         break;
364         if (!p) {
365                 if (len >= (mem_pool_alloc/2)) {
366                         total_allocd += len;
367                         return xmalloc(len);
368                 }
369                 total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
370                 p = xmalloc(sizeof(struct mem_pool) + mem_pool_alloc);
371                 p->next_pool = mem_pool;
372                 p->next_free = p->space;
373                 p->end = p->next_free + mem_pool_alloc;
374                 mem_pool = p;
375         }
377         r = p->next_free;
378         /* round out to a pointer alignment */
379         if (len & (sizeof(void*) - 1))
380                 len += sizeof(void*) - (len & (sizeof(void*) - 1));
381         p->next_free += len;
382         return r;
385 static void* pool_calloc(size_t count, size_t size)
387         size_t len = count * size;
388         void *r = pool_alloc(len);
389         memset(r, 0, len);
390         return r;
393 static char* pool_strdup(const char *s)
395         char *r = pool_alloc(strlen(s) + 1);
396         strcpy(r, s);
397         return r;
400 static void size_dbuf(struct dbuf *b, size_t maxlen)
402         if (b->buffer) {
403                 if (b->capacity >= maxlen)
404                         return;
405                 free(b->buffer);
406         }
407         b->capacity = ((maxlen / 1024) + 1) * 1024;
408         b->buffer = xmalloc(b->capacity);
411 static void insert_mark(uintmax_t idnum, struct object_entry *oe)
413         struct mark_set *s = marks;
414         while ((idnum >> s->shift) >= 1024) {
415                 s = pool_calloc(1, sizeof(struct mark_set));
416                 s->shift = marks->shift + 10;
417                 s->data.sets[0] = marks;
418                 marks = s;
419         }
420         while (s->shift) {
421                 uintmax_t i = idnum >> s->shift;
422                 idnum -= i << s->shift;
423                 if (!s->data.sets[i]) {
424                         s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
425                         s->data.sets[i]->shift = s->shift - 10;
426                 }
427                 s = s->data.sets[i];
428         }
429         if (!s->data.marked[idnum])
430                 marks_set_count++;
431         s->data.marked[idnum] = oe;
434 static struct object_entry* find_mark(uintmax_t idnum)
436         uintmax_t orig_idnum = idnum;
437         struct mark_set *s = marks;
438         struct object_entry *oe = NULL;
439         if ((idnum >> s->shift) < 1024) {
440                 while (s && s->shift) {
441                         uintmax_t i = idnum >> s->shift;
442                         idnum -= i << s->shift;
443                         s = s->data.sets[i];
444                 }
445                 if (s)
446                         oe = s->data.marked[idnum];
447         }
448         if (!oe)
449                 die("mark :%ju not declared", orig_idnum);
450         return oe;
453 static struct atom_str* to_atom(const char *s, size_t len)
455         unsigned int hc = hc_str(s, len) % atom_table_sz;
456         struct atom_str *c;
458         for (c = atom_table[hc]; c; c = c->next_atom)
459                 if (c->str_len == len && !strncmp(s, c->str_dat, len))
460                         return c;
462         c = pool_alloc(sizeof(struct atom_str) + len + 1);
463         c->str_len = len;
464         strncpy(c->str_dat, s, len);
465         c->str_dat[len] = 0;
466         c->next_atom = atom_table[hc];
467         atom_table[hc] = c;
468         atom_cnt++;
469         return c;
472 static struct branch* lookup_branch(const char *name)
474         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
475         struct branch *b;
477         for (b = branch_table[hc]; b; b = b->table_next_branch)
478                 if (!strcmp(name, b->name))
479                         return b;
480         return NULL;
483 static struct branch* new_branch(const char *name)
485         unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
486         struct branch* b = lookup_branch(name);
488         if (b)
489                 die("Invalid attempt to create duplicate branch: %s", name);
490         if (check_ref_format(name))
491                 die("Branch name doesn't conform to GIT standards: %s", name);
493         b = pool_calloc(1, sizeof(struct branch));
494         b->name = pool_strdup(name);
495         b->table_next_branch = branch_table[hc];
496         b->branch_tree.versions[0].mode = S_IFDIR;
497         b->branch_tree.versions[1].mode = S_IFDIR;
498         branch_table[hc] = b;
499         branch_count++;
500         return b;
503 static unsigned int hc_entries(unsigned int cnt)
505         cnt = cnt & 7 ? (cnt / 8) + 1 : cnt / 8;
506         return cnt < avail_tree_table_sz ? cnt : avail_tree_table_sz - 1;
509 static struct tree_content* new_tree_content(unsigned int cnt)
511         struct avail_tree_content *f, *l = NULL;
512         struct tree_content *t;
513         unsigned int hc = hc_entries(cnt);
515         for (f = avail_tree_table[hc]; f; l = f, f = f->next_avail)
516                 if (f->entry_capacity >= cnt)
517                         break;
519         if (f) {
520                 if (l)
521                         l->next_avail = f->next_avail;
522                 else
523                         avail_tree_table[hc] = f->next_avail;
524         } else {
525                 cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
526                 f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
527                 f->entry_capacity = cnt;
528         }
530         t = (struct tree_content*)f;
531         t->entry_count = 0;
532         t->delta_depth = 0;
533         return t;
536 static void release_tree_entry(struct tree_entry *e);
537 static void release_tree_content(struct tree_content *t)
539         struct avail_tree_content *f = (struct avail_tree_content*)t;
540         unsigned int hc = hc_entries(f->entry_capacity);
541         f->next_avail = avail_tree_table[hc];
542         avail_tree_table[hc] = f;
545 static void release_tree_content_recursive(struct tree_content *t)
547         unsigned int i;
548         for (i = 0; i < t->entry_count; i++)
549                 release_tree_entry(t->entries[i]);
550         release_tree_content(t);
553 static struct tree_content* grow_tree_content(
554         struct tree_content *t,
555         int amt)
557         struct tree_content *r = new_tree_content(t->entry_count + amt);
558         r->entry_count = t->entry_count;
559         r->delta_depth = t->delta_depth;
560         memcpy(r->entries,t->entries,t->entry_count*sizeof(t->entries[0]));
561         release_tree_content(t);
562         return r;
565 static struct tree_entry* new_tree_entry()
567         struct tree_entry *e;
569         if (!avail_tree_entry) {
570                 unsigned int n = tree_entry_alloc;
571                 total_allocd += n * sizeof(struct tree_entry);
572                 avail_tree_entry = e = xmalloc(n * sizeof(struct tree_entry));
573                 while (n-- > 1) {
574                         *((void**)e) = e + 1;
575                         e++;
576                 }
577                 *((void**)e) = NULL;
578         }
580         e = avail_tree_entry;
581         avail_tree_entry = *((void**)e);
582         return e;
585 static void release_tree_entry(struct tree_entry *e)
587         if (e->tree)
588                 release_tree_content_recursive(e->tree);
589         *((void**)e) = avail_tree_entry;
590         avail_tree_entry = e;
593 static void yread(int fd, void *buffer, size_t length)
595         ssize_t ret = 0;
596         while (ret < length) {
597                 ssize_t size = xread(fd, (char *) buffer + ret, length - ret);
598                 if (!size)
599                         die("Read from descriptor %i: end of stream", fd);
600                 if (size < 0)
601                         die("Read from descriptor %i: %s", fd, strerror(errno));
602                 ret += size;
603         }
606 static void start_packfile()
608         struct packed_git *p;
609         struct pack_header hdr;
611         idx_name = xmalloc(strlen(base_name) + 11);
612         p = xcalloc(1, sizeof(*p) + strlen(base_name) + 13);
613         sprintf(p->pack_name, "%s%5.5i.pack", base_name, pack_id + 1);
614         sprintf(idx_name, "%s%5.5i.idx", base_name, pack_id + 1);
616         pack_fd = open(p->pack_name, O_RDWR|O_CREAT|O_EXCL, 0666);
617         if (pack_fd < 0)
618                 die("Can't create %s: %s", p->pack_name, strerror(errno));
619         p->pack_fd = pack_fd;
621         hdr.hdr_signature = htonl(PACK_SIGNATURE);
622         hdr.hdr_version = htonl(2);
623         hdr.hdr_entries = 0;
624         write_or_die(pack_fd, &hdr, sizeof(hdr));
626         pack_data = p;
627         pack_size = sizeof(hdr);
628         object_count = 0;
630         all_packs = xrealloc(all_packs, sizeof(*all_packs) * (pack_id + 1));
631         all_packs[pack_id] = p;
634 static void fixup_header_footer()
636         SHA_CTX c;
637         char hdr[8];
638         unsigned long cnt;
639         char *buf;
641         if (lseek(pack_fd, 0, SEEK_SET) != 0)
642                 die("Failed seeking to start: %s", strerror(errno));
644         SHA1_Init(&c);
645         yread(pack_fd, hdr, 8);
646         SHA1_Update(&c, hdr, 8);
648         cnt = htonl(object_count);
649         SHA1_Update(&c, &cnt, 4);
650         write_or_die(pack_fd, &cnt, 4);
652         buf = xmalloc(128 * 1024);
653         for (;;) {
654                 size_t n = xread(pack_fd, buf, 128 * 1024);
655                 if (n <= 0)
656                         break;
657                 SHA1_Update(&c, buf, n);
658         }
659         free(buf);
661         SHA1_Final(pack_sha1, &c);
662         write_or_die(pack_fd, pack_sha1, sizeof(pack_sha1));
665 static int oecmp (const void *a_, const void *b_)
667         struct object_entry *a = *((struct object_entry**)a_);
668         struct object_entry *b = *((struct object_entry**)b_);
669         return hashcmp(a->sha1, b->sha1);
672 static void write_index(const char *idx_name)
674         struct sha1file *f;
675         struct object_entry **idx, **c, **last, *e;
676         struct object_entry_pool *o;
677         unsigned int array[256];
678         int i;
680         /* Build the sorted table of object IDs. */
681         idx = xmalloc(object_count * sizeof(struct object_entry*));
682         c = idx;
683         for (o = blocks; o; o = o->next_pool)
684                 for (e = o->next_free; e-- != o->entries;)
685                         if (pack_id == e->pack_id)
686                                 *c++ = e;
687         last = idx + object_count;
688         if (c != last)
689                 die("internal consistency error creating the index");
690         qsort(idx, object_count, sizeof(struct object_entry*), oecmp);
692         /* Generate the fan-out array. */
693         c = idx;
694         for (i = 0; i < 256; i++) {
695                 struct object_entry **next = c;;
696                 while (next < last) {
697                         if ((*next)->sha1[0] != i)
698                                 break;
699                         next++;
700                 }
701                 array[i] = htonl(next - idx);
702                 c = next;
703         }
705         f = sha1create("%s", idx_name);
706         sha1write(f, array, 256 * sizeof(int));
707         for (c = idx; c != last; c++) {
708                 unsigned int offset = htonl((*c)->offset);
709                 sha1write(f, &offset, 4);
710                 sha1write(f, (*c)->sha1, sizeof((*c)->sha1));
711         }
712         sha1write(f, pack_sha1, sizeof(pack_sha1));
713         sha1close(f, NULL, 1);
714         free(idx);
717 static void end_packfile()
719         struct packed_git *old_p = pack_data, *new_p;
721         if (object_count) {
722                 fixup_header_footer();
723                 write_index(idx_name);
724                 fprintf(stdout, "%s\n", old_p->pack_name);
725                 fflush(stdout);
727                 /* Register the packfile with core git's machinary. */
728                 new_p = add_packed_git(idx_name, strlen(idx_name), 1);
729                 if (!new_p)
730                         die("core git rejected index %s", idx_name);
731                 new_p->windows = old_p->windows;
732                 new_p->pack_fd = old_p->pack_fd;
733                 all_packs[pack_id++] = new_p;
734                 install_packed_git(new_p);
735         }
736         else {
737                 close(pack_fd);
738                 unlink(old_p->pack_name);
739         }
740         free(old_p);
741         free(idx_name);
743         /* We can't carry a delta across packfiles. */
744         free(last_blob.data);
745         last_blob.data = NULL;
746         last_blob.len = 0;
747         last_blob.offset = 0;
748         last_blob.depth = 0;
751 static void checkpoint()
753         end_packfile();
754         start_packfile();
757 static size_t encode_header(
758         enum object_type type,
759         size_t size,
760         unsigned char *hdr)
762         int n = 1;
763         unsigned char c;
765         if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
766                 die("bad type %d", type);
768         c = (type << 4) | (size & 15);
769         size >>= 4;
770         while (size) {
771                 *hdr++ = c | 0x80;
772                 c = size & 0x7f;
773                 size >>= 7;
774                 n++;
775         }
776         *hdr = c;
777         return n;
780 static int store_object(
781         enum object_type type,
782         void *dat,
783         size_t datlen,
784         struct last_object *last,
785         unsigned char *sha1out,
786         uintmax_t mark)
788         void *out, *delta;
789         struct object_entry *e;
790         unsigned char hdr[96];
791         unsigned char sha1[20];
792         unsigned long hdrlen, deltalen;
793         SHA_CTX c;
794         z_stream s;
796         hdrlen = sprintf((char*)hdr,"%s %lu",type_names[type],datlen) + 1;
797         SHA1_Init(&c);
798         SHA1_Update(&c, hdr, hdrlen);
799         SHA1_Update(&c, dat, datlen);
800         SHA1_Final(sha1, &c);
801         if (sha1out)
802                 hashcpy(sha1out, sha1);
804         e = insert_object(sha1);
805         if (mark)
806                 insert_mark(mark, e);
807         if (e->offset) {
808                 duplicate_count_by_type[type]++;
809                 return 1;
810         }
812         if (last && last->data && last->depth < max_depth) {
813                 delta = diff_delta(last->data, last->len,
814                         dat, datlen,
815                         &deltalen, 0);
816                 if (delta && deltalen >= datlen) {
817                         free(delta);
818                         delta = NULL;
819                 }
820         } else
821                 delta = NULL;
823         memset(&s, 0, sizeof(s));
824         deflateInit(&s, zlib_compression_level);
825         if (delta) {
826                 s.next_in = delta;
827                 s.avail_in = deltalen;
828         } else {
829                 s.next_in = dat;
830                 s.avail_in = datlen;
831         }
832         s.avail_out = deflateBound(&s, s.avail_in);
833         s.next_out = out = xmalloc(s.avail_out);
834         while (deflate(&s, Z_FINISH) == Z_OK)
835                 /* nothing */;
836         deflateEnd(&s);
838         /* Determine if we should auto-checkpoint. */
839         if ((object_count + 1) > max_objects
840                 || (object_count + 1) < object_count
841                 || (pack_size + 60 + s.total_out) > max_packsize
842                 || (pack_size + 60 + s.total_out) < pack_size) {
844                 /* This new object needs to *not* have the current pack_id. */
845                 e->pack_id = pack_id + 1;
846                 checkpoint();
848                 /* We cannot carry a delta into the new pack. */
849                 if (delta) {
850                         free(delta);
851                         delta = NULL;
853                         memset(&s, 0, sizeof(s));
854                         deflateInit(&s, zlib_compression_level);
855                         s.next_in = dat;
856                         s.avail_in = datlen;
857                         s.avail_out = deflateBound(&s, s.avail_in);
858                         s.next_out = out = xrealloc(out, s.avail_out);
859                         while (deflate(&s, Z_FINISH) == Z_OK)
860                                 /* nothing */;
861                         deflateEnd(&s);
862                 }
863         }
865         e->type = type;
866         e->pack_id = pack_id;
867         e->offset = pack_size;
868         object_count++;
869         object_count_by_type[type]++;
871         if (delta) {
872                 unsigned long ofs = e->offset - last->offset;
873                 unsigned pos = sizeof(hdr) - 1;
875                 delta_count_by_type[type]++;
876                 last->depth++;
878                 hdrlen = encode_header(OBJ_OFS_DELTA, deltalen, hdr);
879                 write_or_die(pack_fd, hdr, hdrlen);
880                 pack_size += hdrlen;
882                 hdr[pos] = ofs & 127;
883                 while (ofs >>= 7)
884                         hdr[--pos] = 128 | (--ofs & 127);
885                 write_or_die(pack_fd, hdr + pos, sizeof(hdr) - pos);
886                 pack_size += sizeof(hdr) - pos;
887         } else {
888                 if (last)
889                         last->depth = 0;
890                 hdrlen = encode_header(type, datlen, hdr);
891                 write_or_die(pack_fd, hdr, hdrlen);
892                 pack_size += hdrlen;
893         }
895         write_or_die(pack_fd, out, s.total_out);
896         pack_size += s.total_out;
898         free(out);
899         if (delta)
900                 free(delta);
901         if (last) {
902                 if (last->data && !last->no_free)
903                         free(last->data);
904                 last->data = dat;
905                 last->offset = e->offset;
906                 last->len = datlen;
907         }
908         return 0;
911 static void *gfi_unpack_entry(
912         struct object_entry *oe,
913         unsigned long *sizep)
915         static char type[20];
916         struct packed_git *p = all_packs[oe->pack_id];
917         if (p == pack_data)
918                 p->pack_size = pack_size + 20;
919         return unpack_entry(p, oe->offset, type, sizep);
922 static const char *get_mode(const char *str, unsigned int *modep)
924         unsigned char c;
925         unsigned int mode = 0;
927         while ((c = *str++) != ' ') {
928                 if (c < '0' || c > '7')
929                         return NULL;
930                 mode = (mode << 3) + (c - '0');
931         }
932         *modep = mode;
933         return str;
936 static void load_tree(struct tree_entry *root)
938         unsigned char* sha1 = root->versions[1].sha1;
939         struct object_entry *myoe;
940         struct tree_content *t;
941         unsigned long size;
942         char *buf;
943         const char *c;
945         root->tree = t = new_tree_content(8);
946         if (is_null_sha1(sha1))
947                 return;
949         myoe = find_object(sha1);
950         if (myoe) {
951                 if (myoe->type != OBJ_TREE)
952                         die("Not a tree: %s", sha1_to_hex(sha1));
953                 t->delta_depth = 0;
954                 buf = gfi_unpack_entry(myoe, &size);
955         } else {
956                 char type[20];
957                 buf = read_sha1_file(sha1, type, &size);
958                 if (!buf || strcmp(type, tree_type))
959                         die("Can't load tree %s", sha1_to_hex(sha1));
960         }
962         c = buf;
963         while (c != (buf + size)) {
964                 struct tree_entry *e = new_tree_entry();
966                 if (t->entry_count == t->entry_capacity)
967                         root->tree = t = grow_tree_content(t, 8);
968                 t->entries[t->entry_count++] = e;
970                 e->tree = NULL;
971                 c = get_mode(c, &e->versions[1].mode);
972                 if (!c)
973                         die("Corrupt mode in %s", sha1_to_hex(sha1));
974                 e->versions[0].mode = e->versions[1].mode;
975                 e->name = to_atom(c, strlen(c));
976                 c += e->name->str_len + 1;
977                 hashcpy(e->versions[0].sha1, (unsigned char*)c);
978                 hashcpy(e->versions[1].sha1, (unsigned char*)c);
979                 c += 20;
980         }
981         free(buf);
984 static int tecmp0 (const void *_a, const void *_b)
986         struct tree_entry *a = *((struct tree_entry**)_a);
987         struct tree_entry *b = *((struct tree_entry**)_b);
988         return base_name_compare(
989                 a->name->str_dat, a->name->str_len, a->versions[0].mode,
990                 b->name->str_dat, b->name->str_len, b->versions[0].mode);
993 static int tecmp1 (const void *_a, const void *_b)
995         struct tree_entry *a = *((struct tree_entry**)_a);
996         struct tree_entry *b = *((struct tree_entry**)_b);
997         return base_name_compare(
998                 a->name->str_dat, a->name->str_len, a->versions[1].mode,
999                 b->name->str_dat, b->name->str_len, b->versions[1].mode);
1002 static void mktree(struct tree_content *t,
1003         int v,
1004         unsigned long *szp,
1005         struct dbuf *b)
1007         size_t maxlen = 0;
1008         unsigned int i;
1009         char *c;
1011         if (!v)
1012                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp0);
1013         else
1014                 qsort(t->entries,t->entry_count,sizeof(t->entries[0]),tecmp1);
1016         for (i = 0; i < t->entry_count; i++) {
1017                 if (t->entries[i]->versions[v].mode)
1018                         maxlen += t->entries[i]->name->str_len + 34;
1019         }
1021         size_dbuf(b, maxlen);
1022         c = b->buffer;
1023         for (i = 0; i < t->entry_count; i++) {
1024                 struct tree_entry *e = t->entries[i];
1025                 if (!e->versions[v].mode)
1026                         continue;
1027                 c += sprintf(c, "%o", e->versions[v].mode);
1028                 *c++ = ' ';
1029                 strcpy(c, e->name->str_dat);
1030                 c += e->name->str_len + 1;
1031                 hashcpy((unsigned char*)c, e->versions[v].sha1);
1032                 c += 20;
1033         }
1034         *szp = c - (char*)b->buffer;
1037 static void store_tree(struct tree_entry *root)
1039         struct tree_content *t = root->tree;
1040         unsigned int i, j, del;
1041         unsigned long new_len;
1042         struct last_object lo;
1043         struct object_entry *le;
1045         if (!is_null_sha1(root->versions[1].sha1))
1046                 return;
1048         for (i = 0; i < t->entry_count; i++) {
1049                 if (t->entries[i]->tree)
1050                         store_tree(t->entries[i]);
1051         }
1053         le = find_object(root->versions[0].sha1);
1054         if (!S_ISDIR(root->versions[0].mode)
1055                 || !le
1056                 || le->pack_id != pack_id) {
1057                 lo.data = NULL;
1058                 lo.depth = 0;
1059         } else {
1060                 mktree(t, 0, &lo.len, &old_tree);
1061                 lo.data = old_tree.buffer;
1062                 lo.offset = le->offset;
1063                 lo.depth = t->delta_depth;
1064                 lo.no_free = 1;
1065         }
1067         mktree(t, 1, &new_len, &new_tree);
1068         store_object(OBJ_TREE, new_tree.buffer, new_len,
1069                 &lo, root->versions[1].sha1, 0);
1071         t->delta_depth = lo.depth;
1072         for (i = 0, j = 0, del = 0; i < t->entry_count; i++) {
1073                 struct tree_entry *e = t->entries[i];
1074                 if (e->versions[1].mode) {
1075                         e->versions[0].mode = e->versions[1].mode;
1076                         hashcpy(e->versions[0].sha1, e->versions[1].sha1);
1077                         t->entries[j++] = e;
1078                 } else {
1079                         release_tree_entry(e);
1080                         del++;
1081                 }
1082         }
1083         t->entry_count -= del;
1086 static int tree_content_set(
1087         struct tree_entry *root,
1088         const char *p,
1089         const unsigned char *sha1,
1090         const unsigned int mode)
1092         struct tree_content *t = root->tree;
1093         const char *slash1;
1094         unsigned int i, n;
1095         struct tree_entry *e;
1097         slash1 = strchr(p, '/');
1098         if (slash1)
1099                 n = slash1 - p;
1100         else
1101                 n = strlen(p);
1103         for (i = 0; i < t->entry_count; i++) {
1104                 e = t->entries[i];
1105                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1106                         if (!slash1) {
1107                                 if (e->versions[1].mode == mode
1108                                                 && !hashcmp(e->versions[1].sha1, sha1))
1109                                         return 0;
1110                                 e->versions[1].mode = mode;
1111                                 hashcpy(e->versions[1].sha1, sha1);
1112                                 if (e->tree) {
1113                                         release_tree_content_recursive(e->tree);
1114                                         e->tree = NULL;
1115                                 }
1116                                 hashclr(root->versions[1].sha1);
1117                                 return 1;
1118                         }
1119                         if (!S_ISDIR(e->versions[1].mode)) {
1120                                 e->tree = new_tree_content(8);
1121                                 e->versions[1].mode = S_IFDIR;
1122                         }
1123                         if (!e->tree)
1124                                 load_tree(e);
1125                         if (tree_content_set(e, slash1 + 1, sha1, mode)) {
1126                                 hashclr(root->versions[1].sha1);
1127                                 return 1;
1128                         }
1129                         return 0;
1130                 }
1131         }
1133         if (t->entry_count == t->entry_capacity)
1134                 root->tree = t = grow_tree_content(t, 8);
1135         e = new_tree_entry();
1136         e->name = to_atom(p, n);
1137         e->versions[0].mode = 0;
1138         hashclr(e->versions[0].sha1);
1139         t->entries[t->entry_count++] = e;
1140         if (slash1) {
1141                 e->tree = new_tree_content(8);
1142                 e->versions[1].mode = S_IFDIR;
1143                 tree_content_set(e, slash1 + 1, sha1, mode);
1144         } else {
1145                 e->tree = NULL;
1146                 e->versions[1].mode = mode;
1147                 hashcpy(e->versions[1].sha1, sha1);
1148         }
1149         hashclr(root->versions[1].sha1);
1150         return 1;
1153 static int tree_content_remove(struct tree_entry *root, const char *p)
1155         struct tree_content *t = root->tree;
1156         const char *slash1;
1157         unsigned int i, n;
1158         struct tree_entry *e;
1160         slash1 = strchr(p, '/');
1161         if (slash1)
1162                 n = slash1 - p;
1163         else
1164                 n = strlen(p);
1166         for (i = 0; i < t->entry_count; i++) {
1167                 e = t->entries[i];
1168                 if (e->name->str_len == n && !strncmp(p, e->name->str_dat, n)) {
1169                         if (!slash1 || !S_ISDIR(e->versions[1].mode))
1170                                 goto del_entry;
1171                         if (!e->tree)
1172                                 load_tree(e);
1173                         if (tree_content_remove(e, slash1 + 1)) {
1174                                 for (n = 0; n < e->tree->entry_count; n++) {
1175                                         if (e->tree->entries[n]->versions[1].mode) {
1176                                                 hashclr(root->versions[1].sha1);
1177                                                 return 1;
1178                                         }
1179                                 }
1180                                 goto del_entry;
1181                         }
1182                         return 0;
1183                 }
1184         }
1185         return 0;
1187 del_entry:
1188         if (e->tree) {
1189                 release_tree_content_recursive(e->tree);
1190                 e->tree = NULL;
1191         }
1192         e->versions[1].mode = 0;
1193         hashclr(e->versions[1].sha1);
1194         hashclr(root->versions[1].sha1);
1195         return 1;
1198 static void dump_branches()
1200         static const char *msg = "fast-import";
1201         unsigned int i;
1202         struct branch *b;
1203         struct ref_lock *lock;
1205         for (i = 0; i < branch_table_sz; i++) {
1206                 for (b = branch_table[i]; b; b = b->table_next_branch) {
1207                         lock = lock_any_ref_for_update(b->name, NULL);
1208                         if (!lock || write_ref_sha1(lock, b->sha1, msg) < 0)
1209                                 die("Can't write %s", b->name);
1210                 }
1211         }
1214 static void dump_tags()
1216         static const char *msg = "fast-import";
1217         struct tag *t;
1218         struct ref_lock *lock;
1219         char path[PATH_MAX];
1221         for (t = first_tag; t; t = t->next_tag) {
1222                 sprintf(path, "refs/tags/%s", t->name);
1223                 lock = lock_any_ref_for_update(path, NULL);
1224                 if (!lock || write_ref_sha1(lock, t->sha1, msg) < 0)
1225                         die("Can't write %s", path);
1226         }
1229 static void dump_marks_helper(FILE *f,
1230         uintmax_t base,
1231         struct mark_set *m)
1233         uintmax_t k;
1234         if (m->shift) {
1235                 for (k = 0; k < 1024; k++) {
1236                         if (m->data.sets[k])
1237                                 dump_marks_helper(f, (base + k) << m->shift,
1238                                         m->data.sets[k]);
1239                 }
1240         } else {
1241                 for (k = 0; k < 1024; k++) {
1242                         if (m->data.marked[k])
1243                                 fprintf(f, ":%ju %s\n", base + k,
1244                                         sha1_to_hex(m->data.marked[k]->sha1));
1245                 }
1246         }
1249 static void dump_marks()
1251         if (mark_file)
1252         {
1253                 FILE *f = fopen(mark_file, "w");
1254                 dump_marks_helper(f, 0, marks);
1255                 fclose(f);
1256         }
1259 static void read_next_command()
1261         read_line(&command_buf, stdin, '\n');
1264 static void cmd_mark()
1266         if (!strncmp("mark :", command_buf.buf, 6)) {
1267                 next_mark = strtoumax(command_buf.buf + 6, NULL, 10);
1268                 read_next_command();
1269         }
1270         else
1271                 next_mark = 0;
1274 static void* cmd_data (size_t *size)
1276         size_t n = 0;
1277         void *buffer;
1278         size_t length;
1280         if (strncmp("data ", command_buf.buf, 5))
1281                 die("Expected 'data n' command, found: %s", command_buf.buf);
1283         length = strtoul(command_buf.buf + 5, NULL, 10);
1284         buffer = xmalloc(length);
1286         while (n < length) {
1287                 size_t s = fread((char*)buffer + n, 1, length - n, stdin);
1288                 if (!s && feof(stdin))
1289                         die("EOF in data (%lu bytes remaining)", length - n);
1290                 n += s;
1291         }
1293         if (fgetc(stdin) != '\n')
1294                 die("An lf did not trail the binary data as expected.");
1296         *size = length;
1297         return buffer;
1300 static void cmd_new_blob()
1302         size_t l;
1303         void *d;
1305         read_next_command();
1306         cmd_mark();
1307         d = cmd_data(&l);
1309         if (store_object(OBJ_BLOB, d, l, &last_blob, NULL, next_mark))
1310                 free(d);
1313 static void unload_one_branch()
1315         while (cur_active_branches
1316                 && cur_active_branches >= max_active_branches) {
1317                 unsigned long min_commit = ULONG_MAX;
1318                 struct branch *e, *l = NULL, *p = NULL;
1320                 for (e = active_branches; e; e = e->active_next_branch) {
1321                         if (e->last_commit < min_commit) {
1322                                 p = l;
1323                                 min_commit = e->last_commit;
1324                         }
1325                         l = e;
1326                 }
1328                 if (p) {
1329                         e = p->active_next_branch;
1330                         p->active_next_branch = e->active_next_branch;
1331                 } else {
1332                         e = active_branches;
1333                         active_branches = e->active_next_branch;
1334                 }
1335                 e->active_next_branch = NULL;
1336                 if (e->branch_tree.tree) {
1337                         release_tree_content_recursive(e->branch_tree.tree);
1338                         e->branch_tree.tree = NULL;
1339                 }
1340                 cur_active_branches--;
1341         }
1344 static void load_branch(struct branch *b)
1346         load_tree(&b->branch_tree);
1347         b->active_next_branch = active_branches;
1348         active_branches = b;
1349         cur_active_branches++;
1350         branch_load_count++;
1353 static void file_change_m(struct branch *b)
1355         const char *p = command_buf.buf + 2;
1356         char *p_uq;
1357         const char *endp;
1358         struct object_entry *oe;
1359         unsigned char sha1[20];
1360         unsigned int mode;
1361         char type[20];
1363         p = get_mode(p, &mode);
1364         if (!p)
1365                 die("Corrupt mode: %s", command_buf.buf);
1366         switch (mode) {
1367         case S_IFREG | 0644:
1368         case S_IFREG | 0755:
1369         case S_IFLNK:
1370         case 0644:
1371         case 0755:
1372                 /* ok */
1373                 break;
1374         default:
1375                 die("Corrupt mode: %s", command_buf.buf);
1376         }
1378         if (*p == ':') {
1379                 char *x;
1380                 oe = find_mark(strtoumax(p + 1, &x, 10));
1381                 hashcpy(sha1, oe->sha1);
1382                 p = x;
1383         } else {
1384                 if (get_sha1_hex(p, sha1))
1385                         die("Invalid SHA1: %s", command_buf.buf);
1386                 oe = find_object(sha1);
1387                 p += 40;
1388         }
1389         if (*p++ != ' ')
1390                 die("Missing space after SHA1: %s", command_buf.buf);
1392         p_uq = unquote_c_style(p, &endp);
1393         if (p_uq) {
1394                 if (*endp)
1395                         die("Garbage after path in: %s", command_buf.buf);
1396                 p = p_uq;
1397         }
1399         if (oe) {
1400                 if (oe->type != OBJ_BLOB)
1401                         die("Not a blob (actually a %s): %s",
1402                                 command_buf.buf, type_names[oe->type]);
1403         } else {
1404                 if (sha1_object_info(sha1, type, NULL))
1405                         die("Blob not found: %s", command_buf.buf);
1406                 if (strcmp(blob_type, type))
1407                         die("Not a blob (actually a %s): %s",
1408                                 command_buf.buf, type);
1409         }
1411         tree_content_set(&b->branch_tree, p, sha1, S_IFREG | mode);
1413         if (p_uq)
1414                 free(p_uq);
1417 static void file_change_d(struct branch *b)
1419         const char *p = command_buf.buf + 2;
1420         char *p_uq;
1421         const char *endp;
1423         p_uq = unquote_c_style(p, &endp);
1424         if (p_uq) {
1425                 if (*endp)
1426                         die("Garbage after path in: %s", command_buf.buf);
1427                 p = p_uq;
1428         }
1429         tree_content_remove(&b->branch_tree, p);
1430         if (p_uq)
1431                 free(p_uq);
1434 static void cmd_from(struct branch *b)
1436         const char *from, *endp;
1437         char *str_uq;
1438         struct branch *s;
1440         if (strncmp("from ", command_buf.buf, 5))
1441                 return;
1443         if (b->last_commit)
1444                 die("Can't reinitailize branch %s", b->name);
1446         from = strchr(command_buf.buf, ' ') + 1;
1447         str_uq = unquote_c_style(from, &endp);
1448         if (str_uq) {
1449                 if (*endp)
1450                         die("Garbage after string in: %s", command_buf.buf);
1451                 from = str_uq;
1452         }
1454         s = lookup_branch(from);
1455         if (b == s)
1456                 die("Can't create a branch from itself: %s", b->name);
1457         else if (s) {
1458                 unsigned char *t = s->branch_tree.versions[1].sha1;
1459                 hashcpy(b->sha1, s->sha1);
1460                 hashcpy(b->branch_tree.versions[0].sha1, t);
1461                 hashcpy(b->branch_tree.versions[1].sha1, t);
1462         } else if (*from == ':') {
1463                 uintmax_t idnum = strtoumax(from + 1, NULL, 10);
1464                 struct object_entry *oe = find_mark(idnum);
1465                 unsigned long size;
1466                 char *buf;
1467                 if (oe->type != OBJ_COMMIT)
1468                         die("Mark :%ju not a commit", idnum);
1469                 hashcpy(b->sha1, oe->sha1);
1470                 buf = gfi_unpack_entry(oe, &size);
1471                 if (!buf || size < 46)
1472                         die("Not a valid commit: %s", from);
1473                 if (memcmp("tree ", buf, 5)
1474                         || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
1475                         die("The commit %s is corrupt", sha1_to_hex(b->sha1));
1476                 free(buf);
1477                 hashcpy(b->branch_tree.versions[0].sha1,
1478                         b->branch_tree.versions[1].sha1);
1479         } else if (!get_sha1(from, b->sha1)) {
1480                 if (is_null_sha1(b->sha1)) {
1481                         hashclr(b->branch_tree.versions[0].sha1);
1482                         hashclr(b->branch_tree.versions[1].sha1);
1483                 } else {
1484                         unsigned long size;
1485                         char *buf;
1487                         buf = read_object_with_reference(b->sha1,
1488                                 type_names[OBJ_COMMIT], &size, b->sha1);
1489                         if (!buf || size < 46)
1490                                 die("Not a valid commit: %s", from);
1491                         if (memcmp("tree ", buf, 5)
1492                                 || get_sha1_hex(buf + 5, b->branch_tree.versions[1].sha1))
1493                                 die("The commit %s is corrupt", sha1_to_hex(b->sha1));
1494                         free(buf);
1495                         hashcpy(b->branch_tree.versions[0].sha1,
1496                                 b->branch_tree.versions[1].sha1);
1497                 }
1498         } else
1499                 die("Invalid ref name or SHA1 expression: %s", from);
1501         read_next_command();
1504 static struct hash_list* cmd_merge(unsigned int *count)
1506         struct hash_list *list = NULL, *n, *e;
1507         const char *from, *endp;
1508         char *str_uq;
1509         struct branch *s;
1511         *count = 0;
1512         while (!strncmp("merge ", command_buf.buf, 6)) {
1513                 from = strchr(command_buf.buf, ' ') + 1;
1514                 str_uq = unquote_c_style(from, &endp);
1515                 if (str_uq) {
1516                         if (*endp)
1517                                 die("Garbage after string in: %s", command_buf.buf);
1518                         from = str_uq;
1519                 }
1521                 n = xmalloc(sizeof(*n));
1522                 s = lookup_branch(from);
1523                 if (s)
1524                         hashcpy(n->sha1, s->sha1);
1525                 else if (*from == ':') {
1526                         uintmax_t idnum = strtoumax(from + 1, NULL, 10);
1527                         struct object_entry *oe = find_mark(idnum);
1528                         if (oe->type != OBJ_COMMIT)
1529                                 die("Mark :%ju not a commit", idnum);
1530                         hashcpy(n->sha1, oe->sha1);
1531                 } else if (get_sha1(from, n->sha1))
1532                         die("Invalid ref name or SHA1 expression: %s", from);
1534                 n->next = NULL;
1535                 if (list)
1536                         e->next = n;
1537                 else
1538                         list = n;
1539                 e = n;
1540                 *count++;
1541                 read_next_command();
1542         }
1543         return list;
1546 static void cmd_new_commit()
1548         struct branch *b;
1549         void *msg;
1550         size_t msglen;
1551         char *str_uq;
1552         const char *endp;
1553         char *sp;
1554         char *author = NULL;
1555         char *committer = NULL;
1556         struct hash_list *merge_list = NULL;
1557         unsigned int merge_count;
1559         /* Obtain the branch name from the rest of our command */
1560         sp = strchr(command_buf.buf, ' ') + 1;
1561         str_uq = unquote_c_style(sp, &endp);
1562         if (str_uq) {
1563                 if (*endp)
1564                         die("Garbage after ref in: %s", command_buf.buf);
1565                 sp = str_uq;
1566         }
1567         b = lookup_branch(sp);
1568         if (!b)
1569                 b = new_branch(sp);
1570         if (str_uq)
1571                 free(str_uq);
1573         read_next_command();
1574         cmd_mark();
1575         if (!strncmp("author ", command_buf.buf, 7)) {
1576                 author = strdup(command_buf.buf);
1577                 read_next_command();
1578         }
1579         if (!strncmp("committer ", command_buf.buf, 10)) {
1580                 committer = strdup(command_buf.buf);
1581                 read_next_command();
1582         }
1583         if (!committer)
1584                 die("Expected committer but didn't get one");
1585         msg = cmd_data(&msglen);
1586         read_next_command();
1587         cmd_from(b);
1588         merge_list = cmd_merge(&merge_count);
1590         /* ensure the branch is active/loaded */
1591         if (!b->branch_tree.tree || !max_active_branches) {
1592                 unload_one_branch();
1593                 load_branch(b);
1594         }
1596         /* file_change* */
1597         for (;;) {
1598                 if (1 == command_buf.len)
1599                         break;
1600                 else if (!strncmp("M ", command_buf.buf, 2))
1601                         file_change_m(b);
1602                 else if (!strncmp("D ", command_buf.buf, 2))
1603                         file_change_d(b);
1604                 else
1605                         die("Unsupported file_change: %s", command_buf.buf);
1606                 read_next_command();
1607         }
1609         /* build the tree and the commit */
1610         store_tree(&b->branch_tree);
1611         hashcpy(b->branch_tree.versions[0].sha1,
1612                 b->branch_tree.versions[1].sha1);
1613         size_dbuf(&new_data, 97 + msglen
1614                 + merge_count * 49
1615                 + (author
1616                         ? strlen(author) + strlen(committer)
1617                         : 2 * strlen(committer)));
1618         sp = new_data.buffer;
1619         sp += sprintf(sp, "tree %s\n",
1620                 sha1_to_hex(b->branch_tree.versions[1].sha1));
1621         if (!is_null_sha1(b->sha1))
1622                 sp += sprintf(sp, "parent %s\n", sha1_to_hex(b->sha1));
1623         while (merge_list) {
1624                 struct hash_list *next = merge_list->next;
1625                 sp += sprintf(sp, "parent %s\n", sha1_to_hex(merge_list->sha1));
1626                 free(merge_list);
1627                 merge_list = next;
1628         }
1629         if (author)
1630                 sp += sprintf(sp, "%s\n", author);
1631         else
1632                 sp += sprintf(sp, "author %s\n", committer + 10);
1633         sp += sprintf(sp, "%s\n\n", committer);
1634         memcpy(sp, msg, msglen);
1635         sp += msglen;
1636         if (author)
1637                 free(author);
1638         free(committer);
1639         free(msg);
1641         store_object(OBJ_COMMIT,
1642                 new_data.buffer, sp - (char*)new_data.buffer,
1643                 NULL, b->sha1, next_mark);
1644         b->last_commit = object_count_by_type[OBJ_COMMIT];
1646         if (branch_log) {
1647                 int need_dq = quote_c_style(b->name, NULL, NULL, 0);
1648                 fprintf(branch_log, "commit ");
1649                 if (need_dq) {
1650                         fputc('"', branch_log);
1651                         quote_c_style(b->name, NULL, branch_log, 0);
1652                         fputc('"', branch_log);
1653                 } else
1654                         fprintf(branch_log, "%s", b->name);
1655                 fprintf(branch_log," :%ju %s\n",next_mark,sha1_to_hex(b->sha1));
1656         }
1659 static void cmd_new_tag()
1661         char *str_uq;
1662         const char *endp;
1663         char *sp;
1664         const char *from;
1665         char *tagger;
1666         struct branch *s;
1667         void *msg;
1668         size_t msglen;
1669         struct tag *t;
1670         uintmax_t from_mark = 0;
1671         unsigned char sha1[20];
1673         /* Obtain the new tag name from the rest of our command */
1674         sp = strchr(command_buf.buf, ' ') + 1;
1675         str_uq = unquote_c_style(sp, &endp);
1676         if (str_uq) {
1677                 if (*endp)
1678                         die("Garbage after tag name in: %s", command_buf.buf);
1679                 sp = str_uq;
1680         }
1681         t = pool_alloc(sizeof(struct tag));
1682         t->next_tag = NULL;
1683         t->name = pool_strdup(sp);
1684         if (last_tag)
1685                 last_tag->next_tag = t;
1686         else
1687                 first_tag = t;
1688         last_tag = t;
1689         if (str_uq)
1690                 free(str_uq);
1691         read_next_command();
1693         /* from ... */
1694         if (strncmp("from ", command_buf.buf, 5))
1695                 die("Expected from command, got %s", command_buf.buf);
1697         from = strchr(command_buf.buf, ' ') + 1;
1698         str_uq = unquote_c_style(from, &endp);
1699         if (str_uq) {
1700                 if (*endp)
1701                         die("Garbage after string in: %s", command_buf.buf);
1702                 from = str_uq;
1703         }
1705         s = lookup_branch(from);
1706         if (s) {
1707                 hashcpy(sha1, s->sha1);
1708         } else if (*from == ':') {
1709                 from_mark = strtoumax(from + 1, NULL, 10);
1710                 struct object_entry *oe = find_mark(from_mark);
1711                 if (oe->type != OBJ_COMMIT)
1712                         die("Mark :%ju not a commit", from_mark);
1713                 hashcpy(sha1, oe->sha1);
1714         } else if (!get_sha1(from, sha1)) {
1715                 unsigned long size;
1716                 char *buf;
1718                 buf = read_object_with_reference(sha1,
1719                         type_names[OBJ_COMMIT], &size, sha1);
1720                 if (!buf || size < 46)
1721                         die("Not a valid commit: %s", from);
1722                 free(buf);
1723         } else
1724                 die("Invalid ref name or SHA1 expression: %s", from);
1726         if (str_uq)
1727                 free(str_uq);
1728         read_next_command();
1730         /* tagger ... */
1731         if (strncmp("tagger ", command_buf.buf, 7))
1732                 die("Expected tagger command, got %s", command_buf.buf);
1733         tagger = strdup(command_buf.buf);
1735         /* tag payload/message */
1736         read_next_command();
1737         msg = cmd_data(&msglen);
1739         /* build the tag object */
1740         size_dbuf(&new_data, 67+strlen(t->name)+strlen(tagger)+msglen);
1741         sp = new_data.buffer;
1742         sp += sprintf(sp, "object %s\n", sha1_to_hex(sha1));
1743         sp += sprintf(sp, "type %s\n", type_names[OBJ_COMMIT]);
1744         sp += sprintf(sp, "tag %s\n", t->name);
1745         sp += sprintf(sp, "%s\n\n", tagger);
1746         memcpy(sp, msg, msglen);
1747         sp += msglen;
1748         free(tagger);
1749         free(msg);
1751         store_object(OBJ_TAG, new_data.buffer, sp - (char*)new_data.buffer,
1752                 NULL, t->sha1, 0);
1754         if (branch_log) {
1755                 int need_dq = quote_c_style(t->name, NULL, NULL, 0);
1756                 fprintf(branch_log, "tag ");
1757                 if (need_dq) {
1758                         fputc('"', branch_log);
1759                         quote_c_style(t->name, NULL, branch_log, 0);
1760                         fputc('"', branch_log);
1761                 } else
1762                         fprintf(branch_log, "%s", t->name);
1763                 fprintf(branch_log," :%ju %s\n",from_mark,sha1_to_hex(t->sha1));
1764         }
1767 static void cmd_reset_branch()
1769         struct branch *b;
1770         char *str_uq;
1771         const char *endp;
1772         char *sp;
1774         /* Obtain the branch name from the rest of our command */
1775         sp = strchr(command_buf.buf, ' ') + 1;
1776         str_uq = unquote_c_style(sp, &endp);
1777         if (str_uq) {
1778                 if (*endp)
1779                         die("Garbage after ref in: %s", command_buf.buf);
1780                 sp = str_uq;
1781         }
1782         b = lookup_branch(sp);
1783         if (b) {
1784                 b->last_commit = 0;
1785                 if (b->branch_tree.tree) {
1786                         release_tree_content_recursive(b->branch_tree.tree);
1787                         b->branch_tree.tree = NULL;
1788                 }
1789         }
1790         else
1791                 b = new_branch(sp);
1792         if (str_uq)
1793                 free(str_uq);
1794         read_next_command();
1795         cmd_from(b);
1798 static void cmd_checkpoint()
1800         if (object_count)
1801                 checkpoint();
1802         read_next_command();
1805 static const char fast_import_usage[] =
1806 "git-fast-import [--objects=n] [--depth=n] [--active-branches=n] [--export-marks=marks.file] [--branch-log=log] temp.pack";
1808 int main(int argc, const char **argv)
1810         int i;
1811         uintmax_t est_obj_cnt = object_entry_alloc;
1812         uintmax_t duplicate_count;
1814         setup_ident();
1815         git_config(git_default_config);
1817         for (i = 1; i < argc; i++) {
1818                 const char *a = argv[i];
1820                 if (*a != '-' || !strcmp(a, "--"))
1821                         break;
1822                 else if (!strncmp(a, "--objects=", 10))
1823                         est_obj_cnt = strtoumax(a + 10, NULL, 0);
1824                 else if (!strncmp(a, "--max-objects-per-pack=", 23))
1825                         max_objects = strtoumax(a + 23, NULL, 0);
1826                 else if (!strncmp(a, "--max-pack-size=", 16))
1827                         max_packsize = strtoumax(a + 16, NULL, 0) * 1024 * 1024;
1828                 else if (!strncmp(a, "--depth=", 8))
1829                         max_depth = strtoul(a + 8, NULL, 0);
1830                 else if (!strncmp(a, "--active-branches=", 18))
1831                         max_active_branches = strtoul(a + 18, NULL, 0);
1832                 else if (!strncmp(a, "--export-marks=", 15))
1833                         mark_file = a + 15;
1834                 else if (!strncmp(a, "--branch-log=", 13)) {
1835                         branch_log = fopen(a + 13, "w");
1836                         if (!branch_log)
1837                                 die("Can't create %s: %s", a + 13, strerror(errno));
1838                 }
1839                 else
1840                         die("unknown option %s", a);
1841         }
1842         if ((i+1) != argc)
1843                 usage(fast_import_usage);
1844         base_name = argv[i];
1846         alloc_objects(est_obj_cnt);
1847         strbuf_init(&command_buf);
1849         atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
1850         branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
1851         avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
1852         marks = pool_calloc(1, sizeof(struct mark_set));
1854         start_packfile();
1855         for (;;) {
1856                 read_next_command();
1857                 if (command_buf.eof)
1858                         break;
1859                 else if (!strcmp("blob", command_buf.buf))
1860                         cmd_new_blob();
1861                 else if (!strncmp("commit ", command_buf.buf, 7))
1862                         cmd_new_commit();
1863                 else if (!strncmp("tag ", command_buf.buf, 4))
1864                         cmd_new_tag();
1865                 else if (!strncmp("reset ", command_buf.buf, 6))
1866                         cmd_reset_branch();
1867                 else if (!strcmp("checkpoint", command_buf.buf))
1868                         cmd_checkpoint();
1869                 else
1870                         die("Unsupported command: %s", command_buf.buf);
1871         }
1872         end_packfile();
1874         dump_branches();
1875         dump_tags();
1876         dump_marks();
1877         if (branch_log)
1878                 fclose(branch_log);
1880         duplicate_count = 0;
1881         for (i = 0; i < ARRAY_SIZE(duplicate_count_by_type); i++)
1882                 duplicate_count += duplicate_count_by_type[i];
1884         fprintf(stderr, "%s statistics:\n", argv[0]);
1885         fprintf(stderr, "---------------------------------------------------------------------\n");
1886         fprintf(stderr, "Alloc'd objects: %10ju (%10ju overflow  )\n", alloc_count, alloc_count - est_obj_cnt);
1887         fprintf(stderr, "Total objects:   %10ju (%10ju duplicates                  )\n", object_count, duplicate_count);
1888         fprintf(stderr, "      blobs  :   %10ju (%10ju duplicates %10ju deltas)\n", object_count_by_type[OBJ_BLOB], duplicate_count_by_type[OBJ_BLOB], delta_count_by_type[OBJ_BLOB]);
1889         fprintf(stderr, "      trees  :   %10ju (%10ju duplicates %10ju deltas)\n", object_count_by_type[OBJ_TREE], duplicate_count_by_type[OBJ_TREE], delta_count_by_type[OBJ_TREE]);
1890         fprintf(stderr, "      commits:   %10ju (%10ju duplicates %10ju deltas)\n", object_count_by_type[OBJ_COMMIT], duplicate_count_by_type[OBJ_COMMIT], delta_count_by_type[OBJ_COMMIT]);
1891         fprintf(stderr, "      tags   :   %10ju (%10ju duplicates %10ju deltas)\n", object_count_by_type[OBJ_TAG], duplicate_count_by_type[OBJ_TAG], delta_count_by_type[OBJ_TAG]);
1892         fprintf(stderr, "Total branches:  %10lu (%10lu loads     )\n", branch_count, branch_load_count);
1893         fprintf(stderr, "      marks:     %10ju (%10ju unique    )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
1894         fprintf(stderr, "      atoms:     %10u\n", atom_cnt);
1895         fprintf(stderr, "Memory total:    %10ju KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
1896         fprintf(stderr, "       pools:    %10lu KiB\n", total_allocd/1024);
1897         fprintf(stderr, "     objects:    %10ju KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
1898         fprintf(stderr, "---------------------------------------------------------------------\n");
1899         pack_report();
1900         fprintf(stderr, "---------------------------------------------------------------------\n");
1901         fprintf(stderr, "\n");
1903         return 0;