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